#!/bin/csh -f

setenv LANG C

if ($#argv != 2) then
    echo Usage: $0 'timeout matrix-tb.txt < /dev/null >&'  $0'log &'
    echo '    (over)writes matrix-tb_timeout.domin'
    exit $#argv
    endif

set timeout = $1
set inf = $2
set infr = $inf:r
set outf = ${infr}_${timeout}.domin

set width = `head -1 $inf | tr ' ' '\012' | wc -l `
# echo width $width

if (-e $outf) /bin/rm $outf
@ me = 2
while ($me <= $width)
  @ opp = 2
  while ($opp <= $width)
    cat $inf | awk -v meN=$me -v oppN=$opp -v to=$timeout \
      'NR==1{print $1,$meN,$oppN;next;} {me=(tolower($meN)=="inf"||$meN>to)?"Inf":$meN; opp=(tolower($oppN)=="inf"||$oppN>to)?"Inf":$oppN; print $1,me,opp;}' | \
        carefulCompare.awksh | \
        awk 'NR==1{me=$1;opp=$2; next;} NF==2{print me,opp,$1;}' | \
        cat >> $outf
    @ opp = $opp + 1
    end
  @ me = $me + 1
  end

cat $outf | \
  awk '{me=$1;opp=$2;if(ck!=""&&me!=oldme){d=(oldme==oldopp)?0:(s>0)?2:(s<0)?0:1;tot+=d;print tot/2;tot=0;s=0;printf "%s ",me;oldme=me;oldopp=opp;}else if(ck!=""&&opp!=oldopp){d=(oldme==oldopp)?0:(s>0)?2:(s<0)?0:1;tot+=d;s=0;oldopp=opp;} s+=$3;ck+=$3;}END{d=(oldme==oldopp)?0:(s>0)?2:(s<0)?0:1;tot+=d;print tot/2;print "cksum", ck}' | \
  sort -r -n -k2,2

# USE sort -r -n -k2,2  to show high scorers first.
