#!/bin/bash
#
# Usage:
#   signssm_plot.sh #reps state_file data_file output_file [ {p | f | s} ]
#
#  Copyright (C) 2010
#    Yoshinori Tamada, Rui Yamaguchi, Seiya Imoto, Osamu Hirose, Ryo Yoshida,
#    Masao Nagasaki and Satoru Miyano
#      Laboratory of DNA Information Analysis &
#      Laboratory of Sequence Analysis, Human Genome Center,
#      The Institute of Medical Science, The Unversity of Tokyo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Visit http://sign.hgc.jp/signssm/ for contanct information.
#
# Written by Yoshinori Tamada <tamada at ims.u-tokyo.ac.jp>
#

TMP=".signssm_plot_tmp"
TERMTYPE="pdf"

if [ $# -le 3 ]; then
    echo ERROR: specify \# of reps and three files: state, data, and output file
    exit
fi

REPS="$1"
STATE="$2"
DATA="$3"
OUTPUT="$4"

OFFSET="3"
TYPE="Prediction"

if [ $# -eq 5 ]; then
  case $5 in
      p|prediction)
	  OFFSET="3"
	  TYPE="Prediction"
	  ;;
      f|filter)
	  OFFSET="4"
	  TYPE="Filtering"
	  ;;
      s|smooth)
	  OFFSET="5"
	  TYPE="Smoothing"
	  ;;
      *)
	  echo ERROR specify p, f, or s for the 5-th argument
	  exit
	  ;;
  esac
fi

grep -v '^[@\$]' $DATA | cut -f 1 > $TMP.genes

GENES=`cat $TMP.genes | wc -l`

echo set terminal $TERMTYPE > $TMP
echo set size ratio 0.8 >> $TMP
echo set output \"$OUTPUT\" >> $TMP

COUNT=1
while [ $COUNT -le $GENES ]; do

    POS=`expr $COUNT + 1`
    echo set title \"`sed -n ${COUNT}p $TMP.genes`\" >> $TMP
    L=0

    echo plot \"$STATE\" index  6 using 1:$POS with points ti \"rep 1\",\\ >> $TMP
    J=2
    M=`expr $L + 6`
    while [ $J -le $REPS ]; do
	M=`expr $M + 7`
	echo      \"$STATE\" index $M using 1:$POS with points ti \"rep $J\",\\ >> $TMP
	J=`expr $J + 1`
    done

    J=1
    M=`expr $L + $OFFSET`
    while [ $J -le $REPS ]; do
	if [ $J -eq $REPS ]; then
	    echo      \"$STATE\" index $M using 1:$POS with lines ti \"$TYPE $J\" >> $TMP
	else
	    echo      \"$STATE\" index $M using 1:$POS with lines ti \"$TYPE $J\",\\ >> $TMP
	fi
	M=`expr $M + 7`
	J=`expr $J + 1`
    done
    L=`expr $L + 7`

    COUNT=`expr $COUNT + 1`
done

gnuplot $TMP

rm $TMP
rm $TMP.genes
