#!/bin/bash

function debug() {
	echo "DEBUG:" $*
}

function camera_zoom_in() {
	debug "Zooming in"
	./d_pelco 08 20; ./d_pelco 00 00;
}

function camera_zoom_out() {
	debug "Zooming out"
	./d_pelco 08 40; ./d_pelco 00 00;
}

function camera_focus_near() {
	debug "Focusing near"
	./d_pelco 01 00; ./d_pelco 00 00;
}

function camera_focus_far() {
	debug "Focusing far"
	./d_pelco 00 80; ./d_pelco 00 00;
}

function camera_zoom_max() {
	debug "Zoom set to max"
	./d_pelco 08 20; 
}

function camera_zoom_min() {
	debug "Zoom set to min"
	./d_pelco 08 40;
}

function camera_menu() {
	debug "Menu invocation"
	./d_pelco 08
}

function camera_control() {
	local key_press="$1"
	case "$key_press" in
		"[A") camera_zoom_in ;;    # Cursor Up
		"[B") camera_zoom_out ;;   # Cursor Down
		"[C") camera_focus_far ;;  # Cursor Right 
		"[D") camera_focus_near ;; # Cursor Left
		\?) echo ;;
	esac
}

while :
do
	# Read key press, 1 byte
	read -rsn1 -d '' PRESS
	# Store its value as hex number
	printf -v KEY "%#x" \'$PRESS
	debug KEY=$KEY	

    # Perform operation after keypress
	if (( KEY == 0x1b )) ; then
	    # Cursor key starts with ESCAPE 0x1b character
	    debug "Special char!"
	    read -rsn2 -d '' PRESS # two more bytes with cursor code
	    debug "KEY=$PRESS"
	    camera_control $PRESS 
	elif (( KEY == 0x6d || KEY == 0x4d )) ; then
	    # Key 'M' or 'm'
	    debug "Menu"
	    camera_menu
	elif (( KEY == 0x7a || KEY == 0x5a )) ; then
        # Key 'Z' or 'z'
	    camera_zoom_min
	elif (( KEY == 0x78 || KEY == 0x58 )) ; then
        # Key 'X' or 'x'
	    camera_zoom_max
    fi
done

