#!/bin/bash
set -e


GAME_LIST=$1
METHOD_LIST=$2
AGG_SCRIPT=/home/jan/research/security_games/petrus/aggregate_gtopt_results.sh
ADD_SCORE_SCRIPT=/home/jan/research/security_games/petrus/defender_score_bis.R


FULLPREFIX=$(basename $METHOD_LIST)-$(basename $GAME_LIST)
 

TEMPFILE=$(mktemp)

echo game > $FULLPREFIX.csv
cut -f1 -d\  $GAME_LIST >> $FULLPREFIX.csv
cut -f1 -d\  $GAME_LIST >> $FULLPREFIX.milp3.csv


while read method; do
    while read game; do
	$AGG_SCRIPT $game $method 
    done < $GAME_LIST

    MPREFIX=$(basename $GAME_LIST)-$(echo $method |sed 's/ /-/g')
    head -n 1 $(head -n 1 $GAME_LIST |sed 's/ /-/g')-$(echo $method |sed 's/ /-/g').stat.csv > $MPREFIX.stat.csv
    tail -q -n 1 $(sed -e 's/ /-/g' -e 's/$/-'$(echo $method |sed 's/ /-/g')'.stat.csv/' < $GAME_LIST) >> $MPREFIX.stat.csv

    Rscript $ADD_SCORE_SCRIPT $MPREFIX.stat.csv
    csvtool namedcol game,uctDefenderPayoff.mean,uctTimeMs.mean,score $MPREFIX.stat.csv | sed 's/^\(.*\),\(.*\),\([0-9]*\)\.[0-9]*,/\1,\2,\3,/' > $MPREFIX.stat.uct.csv
    csvtool namedcol game,gtoptDefenderPayoff.mean,gurobiTime.mean,randomDefenderPayoff.mean $MPREFIX.stat.csv > $FULLPREFIX.stat.milp.csv
    csvtool namedcol game,scipDefenderPayoff.mean,gtoptTime.mean,randomDefenderPayoff.mean $MPREFIX.stat.csv > $FULLPREFIX.stat.milp3.csv
    CPREFIX=$(echo $MPREFIX | sed 's/-/./g')
    sed -e '1s/,/,'$CPREFIX'./g' -e 's/^[^,]*,//'  $MPREFIX.stat.uct.csv | paste -d,  $FULLPREFIX.csv - > $TEMPFILE
    cp $TEMPFILE $FULLPREFIX.csv
done < $METHOD_LIST

sed  -e 's/^[^,]*,//' $FULLPREFIX.stat.milp.csv  | paste -d,  $FULLPREFIX.csv - > $TEMPFILE
cp $TEMPFILE $FULLPREFIX.csv

sed  -e 's/^[^,]*,//' $FULLPREFIX.stat.milp.csv  | paste -d,  $FULLPREFIX.milp3.csv - > $TEMPFILE
cp $TEMPFILE $FULLPREFIX.milp3.csv

rm $TEMPFILE

cp $FULLPREFIX.csv ../opis/
cp $FULLPREFIX.milp3.csv ../opis/


cols=$(sed -e 's/^.*$/rrr/' $METHOD_LIST | tr "\n" '|')
methods=$(cut -f2 -d\  $METHOD_LIST)
(
    cd ../opis
    echo '\begin{tabular}{r|'$cols'rr|r}' > $FULLPREFIX.tex
    echo '&' >> $FULLPREFIX.tex
    echo $methods | sed -e 's/ /\n/g' | sed -e 's/^/\\multicolumn\{3\}\{c\}\{/' -e 's/$/\}\&/' >> $FULLPREFIX.tex
    echo '\multicolumn{2}{c}{MILP}&U \\' >> $FULLPREFIX.tex
    echo 'game&' >> $FULLPREFIX.tex
    for m in $methods; do
	echo 'R&t&sc&' >> $FULLPREFIX.tex
    done
    echo 'R&t&R\\' >> $FULLPREFIX.tex
    csv2latex --lines 400 --nohead --nohline $FULLPREFIX.csv | tail -n +3 >>  $FULLPREFIX.tex    
)
