#!/bin/bash

export cpus=$(ls -d /sys/devices/system/cpu/cpu* |egrep [[:digit:]]$ |wc -w)

# perform automatic cognate detection -> .qlc file

for fm in `cat glottologFamilies.txt`; do
    python SCACognateDetection.py -t 0.45 -c hh -f $fm -e paps.nex listss16_recent.txt > /dev/null &
done

wait 

# extract character matrix from qlc file, perform T-Coffee alignment,
# add paup commands and save results in nexus files
# for threshold 0.0 and 0.4

rm -f *paps.nex

for fm in `cat glottologFamilies.txt`; do
    python extractFromQlc.py $fm 0.0 >/dev/null & 
    python qlcTCoffee.py $fm 0.0 >/dev/null &
    python extractFromQlc.py $fm 0.4 >/dev/null &
    python qlcTCoffee.py $fm 0.4 >/dev/null &
    while [ $(jobs | wc -l) -gt $cpus ]; do sleep 1; done
done

wait
mv *nex nexusFiles
mv *tre treeFiles
mv *html htmlFiles
mv *qlc qlcFiles
wait 


# perform phylogenetic inference

for f in *nex; do
    paup4 -n $f >/dev/null &
    while [ $(jobs | wc -l) -gt $cpus ]; do sleep 1; done
done

wait

cd treeFiles


# perform evaluation

echo -e "PMI\\tADH\\tSCA\\tT-Coffee\\tADH+SCA\\tADH+TCoffee\\tADH+filter\\tSCA+filter\\tT-Coffee+filter\\tADH+SCA+filter\\tADH+TCoffee+filter" > ../results.tsv

for fm in `cat ../glottologFamilies.txt`; do
    export lex0=$fm".lexical.0.0.ml.tre"
    export sca0=$fm".phonetic.0.0.ml.tre"
    export tc0=$fm".tCoffeePhonetic.0.0.ml.tre"
    export lex_sca0=$fm".combined.0.0.ml.tre"
    export lex_tc0=$fm".tCoffee.0.0.ml.tre"
    export lex4=$fm".lexical.0.4.ml.tre"
    export sca4=$fm".phonetic.0.4.ml.tre"
    export tc4=$fm".tCoffeePhonetic.0.4.ml.tre"
    export lex_sca4=$fm".combined.0.4.ml.tre"
    export lex_tc4=$fm".tCoffee.0.4.ml.tre"
    if [ -e $lex0 ] && [ -e $sca0 ] && [ -e $tc0 ] && [ -e $lex_sca0 ] && [ -e $lex_tc0 ] && [ -e $lex4 ] && [ -e $sca4 ] && [ -e $tc4 ] && [ -e $lex_sca4 ] && [ -e $lex_tc4 ] ; then
	echo -ne $fm"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $fm"_pmi.tre" $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $lex0 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $sca0 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $tc0 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $lex_sca0 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $lex_tc0 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $lex4 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $sca4 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $tc4 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -ne `python ../ggqd.py $lex_sca4 $fm"_glot.tre"`"\\t" >> ../results.tsv
	echo -e `python ../ggqd.py $lex_tc4 $fm"_glot.tre"`"\\t" >> ../results.tsv

    fi
done

cd ..

wait

R --vanilla --quiet < evaluate.r

wait
