#!/bin/sh

here=`pwd`

nstph=`gawk 'FNR==4 {print $1}' TOREAD`
nprin=`gawk 'FNR==5 {print $1}' TOREAD`
boxes=$1
species=$2
filen=$3

if [ "${filen}" = "" ] ; then
  filen=out
fi

rm .toplot
totspecies=`wc -l ACTIVE_SPECIES | gawk '{print $1}'`
totcol=`wc -l OUTPUT_SPECIES | gawk '{print $1}'`
list_boxes=`echo ${boxes} | sed -e 's/,/ /g'`
list_species=`echo ${species} | sed -e 's/,/ /g'`

todiv=`expr ${nstph} \/ ${nprin}`
todiv=`expr ${todiv} \* 24`

string="(FNR-1)/${todiv}"
count=""
for sp in ${list_species} ; do
  nsp=`gawk '$1=="'${sp}'" {print FNR}' OUTPUT_SPECIES`
  if [ "${nsp}" = "" ] ; then echo "*** SPECIES ${sp} NOT OUTPUT ***"; exit; fi
  for bo in ${list_boxes} ; do
    col=`expr ${bo} - 1`
    col=`expr ${col} \* ${totcol} + ${nsp}`
    string=${string}',$'${col}
    count=${count}" "${sp}"-"BOX":"${bo}
  done
done

gawk '{print '${string}'}' ${filen} > .tmp
index=1
for titre in ${count} ; do
  index=`expr ${index} + 1`
  gawk '{print $1,$'${index}'}' .tmp >> .toplot
  echo '"'${titre} >> .toplot
  echo ' ' >> .toplot
done

xgraph ${here}/.toplot &
