#! /bin/sh

# WRAP AROUND A MARKOV CHAIN SIMULATION.  Linked to under names
# like dist-wrap, net-wrap, etc. to get versions for each module.

# Copyright (c) 1995-2004 by Radford M. Neal 
#
# Permission is granted for anyone to copy, use, modify, or distribute this
# program and accompanying programs and documents for any purpose, provided 
# this copyright notice is retained and prominently displayed, along with
# a note saying that the original programs are available from Radford Neal's
# web page, and note is made of any changes made to the programs.  The
# programs and documents are distributed without any warranty, express or
# implied.  As the programs were written for research purposes only, they have
# not been tested to the degree that would be advisable in any important
# application.  All use of these programs is entirely at the user's own risk.

set -e  # Exit on error.  Note that the let commands below end with an argument
        # of 1 to avoid a zero value causing an error exit.

# Check arguments.

prog=`echo $0 | sed "s/.*\///"`
module=`echo $prog | sed "s/-.*//"`

if [ $# != 2 -a $# != 3 ]; then
  echo >&2 "Usage: $prog old-log-file new-log-file [ start-index ]"
  exit 1
fi

olf=$1
nlf=$2
startix=$3

if [ ${olf} = ${nlf} ]; then
  echo >&2 "New log file must not be same as old log file"
  exit 1
fi

# Find the number of the last iteration in the old log file.

lastix=`log-last ${olf} | sed "s/.* //"`

if [ ${startix:=1} -gt ${lastix} ]; then
  echo >&2 "Start index given is past the end"
  exit 1
fi

# Copy appropriate bits of the old log file to the new.  The last iteration
# becomes the state at startix, but the random number seed is kept the same
# as it was at startix before.

log-copy ${olf} 0 ${nlf}
log-append ${olf} ${startix:=1} ${nlf} ${startix:=1}
log-append -r ${olf} ${lastix} ${nlf} ${startix:=1}

# Do the wrapped-around iterations until coalescence (or the end).

${module}-mc -c ${olf} ${nlf} ${lastix}

# See if coalescence occurred.

if log-equal -rio ${nlf} ${lastix} ${olf} ${lastix}; then
  let itersdone="-1+`${module}-tbl k ${nlf} ${startix:=1}: \
                  | grep -v '^ *-' | wc -l`" 1
  echo >&2 "Wrapped-around chain coalesced in ${itersdone} iterations"
  exit 0
else
  echo >&2 "Wrapped-around chain did not coalesce with old chain"
  exit 1
fi
