#!/bin/sh
# r0v: the visual raw editor
# copyleft: pancake at nopcode dot org @ 2009-2013

PATH=.:$PATH

ttyset=`stty -g`
bye() {
  [ -n "$ttyset" ] && stty $ttyset
  exit 0
}
case "$1" in
-) : ; ;;
'') echo "r0v [-hv] [file]" ; exit 1 ; ;;
*) $0 - | r0 -n $@ ; bye ; ;;
esac

ttyset=`stty -g`
stty -echo -icanon min 1
trap bye 2

getkey() {
  read -n 1 A
  echo "$A"
  #echo "` stty -echo -icanon min 1 ; dd if=/dev/tty count=1 bs=1 2>/dev/null`"
}

getstr() {
  stty icanon echo 2>/dev/null
  read A
  echo "$A"
  stty -icanon -echo 2>/dev/null
}

OLINES=0
autobs() {
  NLINES=`tput lines 2> /dev/null`
  #echo "b "$(($NLINES*16))
#return
  if [ -n "${NLINES}" -a "${OLINES}" != "${NLINES}" ]; then
    LINES=${NLINES}
    [ -n "${LINES}" ] && \
      echo "b "$((($LINES-1)*16))
    OLINES=${LINES}
  fi
}

trap autobs 28

P=''
echo "b 256"
while : ; do
  echo '!clear'
  # autobs
  case $P in
  #'d') echo '!echo X | r0 -n $| rasm2 -o $OFFSET -vd -|head -n '$LINES ;  ;;
  d) echo d ;;
  *) echo x ;;
  esac
  case "`getkey`" in
  'j') echo "s+16" ;;
  'k') echo "s-16" ;;
  'J') echo "s+b" ;;
  'K') echo "s-b" ;;
  'h') echo "s-1" ;;
  'l') echo "s+1" ;;
  'q') bye ; ;;
  'b') printf 'b'>/dev/tty; echo b`getstr` ;;
  'w') printf 'w'>/dev/tty; echo w`getstr` ;;
  'i') printf 'w'>/dev/tty; echo w`getstr` ;;  ## alias to mimic r2
  's') printf 's'>/dev/tty; echo s`getstr` ;;
  'r') printf 'r '>/dev/tty; echo r`getstr` ;;
  ':') printf ': '>/dev/tty; getstr; getkey >/dev/null ; ;;
  '?') echo '!clear' ; echo '?'; getkey ; ;;
  '+') echo "b+1" ;;
  '-') echo "b-1" ;;
  '.') echo "s0" ;;
  '^') echo "s0" ;;
  '^') echo "s0" ;;
  '$') echo 's`r`' ;;
  'G') echo 's`r`' ;;
  '*') echo "b+16" ;;
  '/') echo "b-16" ;;
  p|P) if [ -n "$P" ]; then P=''; else P=d; fi ;;
  esac
done
