#!/usr/bin/env bash

[[ $# -ge 1 ]] || { echo "usage: $0 <raw cluster log file/dir>"; exit 0; }


parse_file() {
    local inpf=$1
    [[ -f $inpf ]] || { echo "error: input is not a valid file"; return 255; }
    local bn=$(basename $inpf .og_raw.log)
    local ogfile=${inpf//.log/}
    local tmstr=( $(tail -n 2 $ogfile | grep '#TIME') )
    local node=${tmstr[2]}
    local tmcl=${tmstr[3]}
    echo -n "$node $bn "
    cat $inpf | awk 'BEGIN{Nincl=0;}
                             /Nr of pairs/{Npairs=$7;}
                             /Nr of input clusters/{Nincl=$8;}
                             /Nr of gene ids/{Ngids=$8;}
                             /Nr of species ids/{Nspids=$8;printf "%s %s %s %s ",Npairs,Ngids,Nspids,Nincl; }'

    tail -n 11 $inpf | awk 'BEGIN{Trcl=0;MVrcl=0;MRrcl=0;}
                            /BM:pairdb           read/{Tread=$6;MVread=$8;MRread=$9;}
                            /BM:pairdb           sort/{Tsort=$6;MVsort=$8;MRsort=$9;}
                            /BM:pairdb           index/{Tindex=$6;MVindex=$8;MRindex=$9;}
                            /BM:cluster          read/{Trcl=$6;MVrcl=$8;MRrcl=$9;}
                            /BM:cluster          clustering/{Nclus=$5;Tclus=$6;MVclus=$8;MRclus=$9;}
                            /BM:cluster          total/{Ttot=$6;MVtot=$8;MRtot=$9;}
                            /estimated memory usage clusterize/{Mest=$8;
                              printf "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s",
                                Nclus,Tread,MVread,MRread,Tsort,MVsort,MRsort,Tindex,MVindex,MRindex,Trcl,MVrcl,MRrcl,Tclus,MVclus,MRclus,Ttot,MVtot,MRtot,Mest; }'
    echo " $tmcl"
}

# output result first sorted by nr of input clusters (-k4,4)
# and then by nr of pairs (-k1,1)
echo 'node label Npairs Ngids Nspids Nincl Nclus Tread MVread MRread Tsort MVsort MRsort Tindex MVindex MRindex Trcl MVrcl MRrcl Tclus MVclus MRclus Ttot MVtot MRtot Mest Tcltot'
if [[ $# -eq 1 ]] && [[ -d $1 ]]; then
    cdir=$1
    for x in $cdir/*.og_raw.log; do
        parse_file $x
    done | sort -n -k6,6 -k3,3
else
    for x in $*; do
        parse_file $x
    done | sort -n -k6,6 -k3,3
fi
