#!/bin/bash
BASE="$1"
BASE="${BASE%/*.img}"

function errout() {
	xmessage "$1"
	exit 1
}

[ "$BASE" == "$1" ] && {
	errout "Kann Basisverzeichnis nicht finden."
}


function plotone() {
  {
	echo "set terminal png size 640,1024 giant x888888 x000000 x222222 xaa0000 x000000 xffff00 xffffff"
	echo "set output '$1.png'"
	echo "set title \"${1##*/}\""	
	echo "set ylabel \"MTT/Tmax\""
	echo "set yrange [0:50]"
	echo "set ytics 10"
	echo "set y2label \"rCBV/F\""
	echo "set y2range [0:350]"
	echo "set y2tics 50"
	echo "set bmargin 4"
	echo "set xtics 1"
	echo "set grid ytics"
	echo -n "plot "
	echo -n      "'$1.tsv' using 1:2 w l lw 5 title \"MTT\" ,"
	echo -n      "'$1.tsv' using 1:3 w l lw 5 title \"Tmax\" ,"
	echo -n      "'$1.tsv' using 1:4 w l lw 5 title \"rCBF\" axes x1y2,"
	echo -n      "'$1.tsv' using 1:5 w l lw 5 title \"rCBV\" axes x1y2"
	echo
  } | gnuplot
}

BASE="${BASE%[0-9]}"
TARGET="${BASE}-time-right.tsv"
:> "${TARGET}"
for a in "$BASE"?; do
	MYTSV=$(echo "$a"/*.tsv)
	[ -e "$MYTSV" ] || {
		errout "Kann .tsv im Verzeichnis $a nicht finden."
	}
	NUMBER=$(echo -n "$a" |tail -c1)
	echo -n "$NUMBER" >>"${TARGET}"
	for b in 2 3 4 5; do 
		echo -n "	" >>"${TARGET}"
		{ echo "scale=2"
		  echo -n "("
		  cat "$MYTSV" | sed -ne '/^0\.0/,/^178\.0/p' | \
		  	cut -f $b -d "	" | tr "
" "+"
		  echo "0)/90.0" ; } | bc | tr -d "
" >>"${TARGET}"
	done
	echo >>"${TARGET}"
done
plotone "${BASE}-time-right"

TARGET="${BASE}-time-left.tsv"
:> "${TARGET}"
for a in "$BASE"?; do
	MYTSV=$(echo "$a"/*.tsv)
	[ -e "$MYTSV" ] || {
		errout "Kann .tsv im Verzeichnis $a nicht finden."
	}
	NUMBER=$(echo -n "$a" |tail -c1)
	echo -n "$NUMBER" >>"${TARGET}"
	for b in 2 3 4 5; do 
		echo -n "	" >>"${TARGET}"
		{ echo "scale=2"
		  echo -n "("
		  cat "$MYTSV" | sed -ne '/^180\.0/,/^358\.0/p' | \
		  	cut -f $b -d "	" | tr "
" "+"
		  echo "0)/90.0" ; } | bc | tr -d "
" >>"${TARGET}"
	done
	echo >>"${TARGET}"
done
plotone "${BASE}-time-left"
