#!/bin/bash
set -e


EXFILE=$1
AGG_SCRIPT=/home/jan/research/security_games/petrus/aggregate_gtopt_results.sh
ADD_SCORE_SCRIPT=/home/jan/research/security_games/petrus/defender_score.R
OUT_DIR=/home/jan/research/security_games/opis/
HEADERS_DIR=/home/jan/research/security_games/petrus/tex-headers

PREFIX=$(basename $EXFILE)

xargs -n 3 $AGG_SCRIPT < $EXFILE

head -n 1 $(head -n 1 $EXFILE | sed 's/ /-/g').stat.csv > $PREFIX.stat.csv
tail -q -n 1 $(sed -e 's/ /-/g' -e 's/$/.stat.csv/' < $EXFILE) >> $PREFIX.stat.csv

    csvtool namedcol game,config,uctDefenderPayoff.mean,uctDefenderPayoff.sd,uctAttackerPayoff.mean,uctAttackerPayoff.sd,uctTimeMs.mean,gtoptDefenderPayoff.mean,gtoptAttackerPayoff.mean,gtoptTime.mean  $PREFIX.stat.csv  > $OUT_DIR/$PREFIX.a.results.csv
    (
	cd $OUT_DIR
	cat $HEADERS_DIR/results.attacker.table.header.tex > $PREFIX.a.results.tex
	csv2latex --lines 400 --nohead --nohline $PREFIX.a.results.csv | tail -n +3 >>  $PREFIX.a.results.tex
    )


    csvtool namedcol game,config,uctDefenderPayoff.mean,uctDefenderPayoff.sd,uctTimeMs.mean,randomDefenderPayoff.mean,gtoptDefenderPayoff.mean,gurobiTime.mean  $PREFIX.stat.csv  > $OUT_DIR/$PREFIX.results.csv
    (
	cd $OUT_DIR
	Rscript $ADD_SCORE_SCRIPT $PREFIX.results.csv
	cat $HEADERS_DIR/results.table.header.tex > $PREFIX.results.tex
	csv2latex --lines 400 --nohead --nohline $PREFIX.results.csv | tail -n +3 >>  $PREFIX.results.tex
    )

    csvtool namedcol game,uctDefenderPayoff.mean,uctDefenderPayoff.sd,uctTimeMs.mean,randomDefenderPayoff.mean,gtoptDefenderPayoff.mean,gurobiTime.mean  $PREFIX.stat.csv  > $OUT_DIR/$PREFIX.resultsf.csv
    (
	cd $OUT_DIR
	Rscript $ADD_SCORE_SCRIPT $PREFIX.resultsf.csv
	cat $HEADERS_DIR/resultsf.table.header.tex > $PREFIX.resultsf.tex
	csv2latex --lines 400 --nohead --nohline $PREFIX.resultsf.csv | tail -n +3 >>  $PREFIX.resultsf.tex

	cat <<EOF > sa.$PREFIX.resultsf.tex 
\documentclass[landscape,margin=1cm]{article}

\usepackage{xcolor}
\usepackage{colortbl}

\begin{document}
\section*{$PREFIX}
\noindent
\input{$PREFIX.resultsf}
\end{document}
EOF
	rubber --pdf sa.$PREFIX.resultsf.tex 
    )

