#!/bin/tcsh -f
#

# for debugging
#set echo=1

set WATCH_DIR=.
set WATCH_INTERVAL=120
set SNAP_NAME=snap
set GIF=0
set SCALE=0

set bin=/u/rae/bin/graphics
set convert=$bin/convert
set mogrify=$bin/mogrify

set usage="Usage: snap [-d dir] [-i interval] [-g] [-s n] basename"
set args=(`getopt d:i:s:g $argv`)

if($status) then
	echo $usage
	exit 1
endif

while ($#args > 0)
	set i=$args[1]; shift args
	switch ($i)
		case -d:
			set WATCH_DIR=$args[1]
			shift args
			breaksw
		case -i:
			set WATCH_INTERVAL=$args[1]
			shift args
			breaksw
		case -s:
			set SCALE=$args[1]
			shift args
			breaksw
		case -g:
			set GIF=1
			breaksw
		case --:
			break
		default:
			echo $usage
			exit 1
	endsw
end

if($#args > 0) then
	set SNAP_NAME=$args[1]
endif

# don't change the below, though
set nonomatch

# check for existance of watch directory
if(! -d ${WATCH_DIR}) then
	/bin/echo "### ${0}: Error"
	/bin/echo "### The directory ${WATCH_DIR} does not exist."
	exit 1;
endif

cd ${WATCH_DIR}

# make sure they aren't already there
/bin/rm -f ${SNAP_NAME}-00000.rgb

set sflag=""
if("$SCALE") then
	set sflag="-z 1/$SCALE"
endif
set ext="jpg"
if($GIF) set ext="gif"

echo "#"
echo "# Will now take a snapshot every $WATCH_INTERVAL seconds,"
echo -n "# saving the result "
if($SCALE) echo -n "at 1/$SCALE size "
echo "in $SNAP_NAME.$ext"
echo "#"

while(1)
	echo -n "# `date`: ${SNAP_NAME}.$ext .. "
	vidtomem -f ${SNAP_NAME} $sflag >& /dev/null
	if($status) then
		/bin/echo "## `date`: Unable to take a snapshot"
	else
		# convert ${SNAP_NAME}-00000.rgb to ${filename}
		$convert \
			-normalize -quality 65 -gamma 1.5 \
			-contrast -contrast -comment "`date`" -sharpen -normalize -despeckle -noise \
			${SNAP_NAME}-00000.rgb ${SNAP_NAME}.$ext

		/bin/rm -f ${SNAP_NAME}-00000.rgb
	endif
	echo "done."
	sleep $WATCH_INTERVAL
end
