#!/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
  STEP_LIST="$FIRST_STEP"
  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 }'`
  # compose list of 5 numbers, begining with LAST_NUM
  STEP_LIST=`seq -s " " $LAST_NUM -1 $((LAST_NUM-4))`
  shift
  echo "Simulaton steps: $STEP_LIST"
else
  # compose string with list of step numbers for which to plot
  while [ ! -z "$1" ]; do
    STEP_LIST="$STEP_LIST $1"
    shift
  done
fi

PLOT="gnuplot -persist"
COMM="set terminal png; set output \"plot.png\" ; plot"
SEP=" "

for i in $STEP_LIST; do
  NUM=`printf "%06d" ${i}`  
  COMM=`echo "${COMM}${SEP} \"${FILE}-${NUM}-block1.dat\" using 1:3 with lines"`
  shift
  SEP=", "

done

echo $COMM | $PLOT


