#!/bin/sh
# display phase-pace diagram for given specie and simulation step
# column numbers start with 1
# default values: assume: -a -c 3 -sp 0 -last
FILE=""
FIRST_STEP="-last"
COLUMN="3"
SPECIES=0
COMM="plot"
PLOT="gnuplot -persist"
SEP=" "

if [ "$1" == "-a" ] || [ -z "$1" ]; then
  # auto find input file 
  FILE="-a"
  shift
fi

if [ "$1" == "-c" ]; then
  # we have definition of column to display as parameter
  shift
  COLUMN=$1
  shift
  echo "Displaying column: $COLUMN"
fi

if [ "$1" == "-sp" ]; then
  # we have definition of which species to display 
  shift
  SPECIES=$1
  shift
  echo "Displaying for species: $SPECIES"
fi

if [ "$1" == "-png" ]; then
  # we display output to PNG file; next parameter is file name
  shift

  if [ -z "$1" ]; then
    PNG='plot.png'
  else 
    PNG=$1
    shift
  fi

  COMM="set terminal png; set output \"$PNG\" ; plot"
  echo "Output will go to PNG file \"$PNG\"..."
fi

if [ ! -z "$1" ] && [ -z "$FILE" ]; then
  # no input file is defined; first parameter is input file name, second is FIRST_STEP
  FILE=$1
  shift
else
  # no options left, assume -a -last
  FILE="-a"
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 [ ! -z "$1" ]; then 
  # all other parameters are steps to display
  STEP_LIST=""

  while [ ! -z "$1" ]; do
    # compose string with list of step numbers for which to plot
    STEP_LIST="$STEP_LIST $1"
    shift
  done

else 
  # use last 5 steps
  # no block numbers given; display all 
  LAST_NUM=`ls -tR | grep block1.dat | head -1 - | sed "s/${FILE}-//g" | sed "s/-/ /g" | awk '{ printf "%d\n", $1 }'`
  # 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"
fi

for i in $STEP_LIST; do
  NUM=`printf "%06d" ${i}`  
  SP=`printf "%02d" ${SPECIES}`
  COMM=`echo "${COMM}${SEP} \"${FILE}-sp${SP}-${NUM}-ph_space.dat\" using 2:${COLUMN} with lines"`
  shift
  SEP=", "

done

echo $COMM | $PLOT


