#!/data/data/com.termux/files/usr/bin/sh
# vired: 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 "vired [-hv] [file]" ; exit 1 ; ;;
*) $0 - | ired -n $@ ; bye ; ;;
esac

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

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

getstr() {
  stty icanon echo
  read A
  echo "$A"
  stty -icanon -echo
}

OLINES=0
autobs() {
  LINES=`tput lines`
  if [ "${OLINES}" != "${LINES}" ]; then
    [ -n "${LINES}" ] && \
      echo "b"$((($LINES-1)*16))
    OLINES=${LINES}
  fi
}

trap autobs 28

P=''
echo "b 256"
while : ; do
  autobs
  echo "!clear"
  case $P in
  #'d') echo '!echo X | ired -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` ;;
  's') printf 's'>/dev/tty; echo s`getstr` ;;
  'r') printf 'r '>/dev/tty; echo r`getstr` ;;
  ':') printf ': '>/dev/tty; getstr; getkey >/dev/null ; ;;
  '?') echo '?'; getkey >/dev/null; ;;
  '+') echo "b+1" ;;
  '-') echo "b-1" ;;
  '*') echo "b+16" ;;
  '/') echo "b-16" ;;
  p|P) if [ -n "$P" ]; then P=''; else P=d; fi ;;
  esac
done
