
# backup is a companion script to evolve.  If the -o option has been used
# with evolve so that a complete history of a CA's evolution is recorded
# in a trace file, backup can return the rule file, trace file, and the
# state file to a point in the CA's past, thus enabling evolve to proceed 
# along a (perhaps) different path of evolution.


# echo the usage if incorrect number of arguments are passed

case $# in
0) echo 'Usage: backup trace_file ca_file rule_file' 1>&2; exit 1;;
1) echo 'Usage: backup trace_file ca_file rule_file' 1>&2; exit 1;;
2) echo 'Usage: backup trace_file ca_file rule_file' 1>&2; exit 1;;
4) echo 'Usage: backup trace_file ca_file rule_file' 1>&2; exit 1;;
esac


# otherwise begin

TRACE=$1
STATE=$2
RULES=$3

# backup uses the state annotation in the rule file to determine what state
# it should return to.  The maximum state number in the rule file is
# determined with this little awk program and assigned to T.

T=`awk 'BEGIN		{ max = 0 }
  	$1 == "state"	{ if ($2 > max) max = $2 }
  	END		{ print  max }' $RULES`


# next the trace file is clipped to the appropriate length based on T from 
# above.  a temporary file is used to prevent unexpected behavior from unix.

sed /$T/q $TRACE > temp.$$
mv temp.$$ $TRACE


# now the number of lines contained in one state of the trace file is
# determined with awk and assigned to S.

S=`awk 'BEGIN		{ max = 0; cnt = 0 }
  	$1 != "state"	{ cnt++ } 
  	$1 == "state"	{ if (cnt > max) max = cnt; cnt = 0 } 
  	END		{ print  max }' $TRACE`


# SS is assigned S+1

SS=`echo "$S 1 + p" | dc`


# the last state in the trace file is copied to the state file

tail -$SS $TRACE | head -$S > $STATE
