#!/bin/sh

print_help() {
	echo "usage: $0 command ..."
	echo "    commands: "
	echo "    dump bank [addr_type]"
	echo "        bank - register bank in hex"
	echo "        addr_type - 8 or 16 (default) bit addressing mode"
	echo "    write bank reg val [addr_type]"
	echo "        bank - register bank in hex"
	echo "        reg - register in hex"
	echo "        val - value to be written in hex - ALWAYS WRITES 16 BITS!" 
	echo "        addr_type - 8 or 16 (default) bit addressing mode"
}

if [ $# -lt 2 ] ; then 
	print_help
	exit 1
fi

COMMAND="$1"
case $COMMAND in
dump)
	bank=$2
	addr_mul=8

	if [ $# -ge 3 ]; then
		case $3 in
		8)
			addr_mul=16
			;;
		16)
			addr_mul=8
			;;
		*)
			print_help
			exit 1
			;;
		esac
	fi

	for i in $(seq 0 15); do
		printf "0x%04x_%02x:  " $bank $(($i * $addr_mul))
		for j in $(seq 0 7); do 
			addr=$((0x1f000000 + $bank * 0x200 + 32 * $i + 4 * $j))
			val=$(($(busybox devmem $(printf "0x%08x" $addr))))
			printf "  %04x" $val
		done
		echo ""
	done
   	;;
write)
	if [ $# -lt 4 ] ; then 
		print_help
		exit 1
	fi
	bank=$2
	reg=$3
	val=$4

	addr_mul=8
	addr=$((0x1f000000 + $bank * 0x200 + $reg * 4))

	if [ $# -ge 5 ]; then
		case $5 in
		8)
			addr_mul=16
			addr=$((0x1f000000 + $bank * 0x200 + $reg * 2))
			;;
		16)
			addr_mul=8
			addr=$((0x1f000000 + $bank * 0x200 + $reg * 4))
			;;
		*)
			print_help
			exit 1
			;;
		esac
	fi

	busybox devmem $(printf "0x%08x" $addr) 16 $val
	;;
*)
	print_help
	;;
esac

