#!/bin/bash

###########################
#
# Draws all svgs in a sequence. Starts with a 
# fieldguide unless beginning the sequence not
# on the first frame, provided as the second argument.
#
###########################

source ./common.sh

if [[ "${1}" == "" ]]; then
	echo "Please provide a directory as the first argument"
	exit 1
fi

dbSetup

FRAMES=$(realpath "${1}")/

END=-1
if [[ "${3}" != "" ]]; then
	END=${3}
fi

if [[ "${2}" == "" ]] || [[ $2 -eq 0 ]]; then
	echo "Drawing focus field..."
	name=`basename "${1}"`
	bash field.sh "${name}"

	askContinue "Start with first frame?" "Starting with first frame..."
else
	c=0
	for svg in "${FRAMES}"*.svg ; do
		if [[ ${c} -lt ${2} ]]; then
			c=$((c+1))
			continue
		fi
		filename=`basename "${svg}"`
		break
	done
	askContinue "Start with ${filename}" "Continuing with frame ${filename}..."
fi

i=0
#files in dir
for svg in "${FRAMES}"*.svg ; do
	if [[ "${2}" != "" ]] && [[ ${2} -ne 0 ]] && [[ ${i} -lt ${2} ]]; then
		i=$((i+1))
		continue
	fi 
	
	filename=`basename "${svg}"`
	name=`echo "${filename}" | cut -d'.' -f1`
	num=`echo "${name}" | awk -F'_' '{print $(NF)}'`
	echo "Drawing $svg file..."
	bash position.sh set
	ax guides/guide_marks.svg
	number=`mktemp`.svg
	node ./numbers/ -n "${num}" -o "${number}"
	ax "${number}"
	axdraw "${svg}" | bash ./log.sh
	rm -f "${number}"
	bash position.sh reset

	if [[ $END -gt -1 ]] && [[ $END -eq $i ]]; then
		echo "Reached final frame $i, exiting..."
		exit
	fi

	askContinue "Finished frame ${filename}" "Continuing with next frame..."
done