#!/bin/sh

if [ -z "$1" ]; then
  # no parameters given; assume -a -last
  FILE="-a"
  FIRST_STEP="-last"
else 
  # first parameter is input file name, second is FIRST_STEP
  FILE=$1
  shift
  FIRST_STEP=$1
  shift
fi

if [ "$FILE" == "-a" ]; then
  # input file is the only filename in current directory - file with .inp;
  # try to get it's name
  FILE=`ls *.inp | head -1`
  echo "Using input file: $FILE"
fi


if [ "$FIRST_STEP" == "-last" ]; then
  # no block numbers given; display all 
  LAST_NUM=`ls -tR | grep block1.dat | head -1 - | sed "s/-/ /g" | awk '{ printf "%d\n", $2 }'`
  FIRST_STEP=$LAST_NUM
  # compose list of 5 numbers, begining with LAST_NUM
  STEP_LIST=`seq -s " " $((LAST_NUM-1)) -1 $((LAST_NUM-4))`
  shift
  echo "Simulaton steps: $FIRST_STEP $STEP_LIST"
else
  # compose string with list of step numbers for which to plot
  STEP_LIST=""

  while [ ! -z "$1" ]; do
    STEP_LIST="$STEP_LIST $1"
    shift
  done
fi


PLOT="gnuplot -persist"
TMPFILE1="block_plot1.tmp"
TMPFILE2="block_plot2.tmp"
TMPFILE3="block_plot3.tmp"
DISPFILE="plot_block1_diff.dat"
SEP=" "

if [ -f $DISPFILE ]; then
  # remove old file
  rm -f $DISPFILE
fi


COMM="set title \"difference between step $FIRST_STEP and other steps\" ; show title ; plot"

# copy 1. and 3. column from frst input block1 file into destination file
NUM=`printf "%06d" $FIRST_STEP`  
cat "${FILE}-${NUM}-block1.dat" | sed "1,1d" | awk '{ print $1 " " $3 }' > $DISPFILE
# move to next file (input file number)
shift	
# current file (and also data column number in final file)
k=2

for i in $STEP_LIST; do
  # process all other numbers (block1 filename numbers) we got as input parameters
  NUM=`printf "%06d" ${i}`  
  cat "${FILE}-${NUM}-block1.dat" | sed "1,1d" | awk '{ print $1 " " $3 }' > $TMPFILE2
  # prepare filenames
  mv $DISPFILE $TMPFILE1
  # join previously generated join file (in TMPFILE1) and new file (from current input file = TMPFILE2)
  # result is stored into DISPFILE
  join $TMPFILE1 $TMPFILE2 > $DISPFILE

  # create also command for plotting data (data will be created later)
  COMM=`echo "${COMM}${SEP} \"${DISPFILE}\" using 1:${k} with lines title \"step ${i}\""`
  SEP=", "

  # to next file (process next filename number in next loop)
  shift
  k=$((k+1))
done

# move current results to temp file
mv $DISPFILE $TMPFILE3
# get number of columns in file
COLS=`head -2 $TMPFILE3 | tail -1 | sed "s/ /\n/g" | wc -l`
# create final file
cat $TMPFILE3 | awk -v MAX=$COLS 'BEGIN{n=MAX}{ printf "%g", $1; val=$2 ; for(i=2;i<n;i++) { printf " %g", val-$(i+1); }; print "" }' > $DISPFILE

echo $COMM
# display results with PLOT program
echo $COMM | $PLOT

echo "Done!"


