#!/bin/csh -f

setenv LANG C

if ($#argv != 4) then
  echo Usage: $0 'matrix.txt to-range.txt ranks noise_level'
  echo '    (over)writes matrix-range-high-{ranks}-{noise_level}.txt'
  echo '    E.g. app-phase2-matrix.txt app-phase2-matrix-times-gt900.txt 3 60'
  exit $#argv
  endif
set tmat = $1
set range = $2
set ranks = $3
set noise = $4
set tmatr = $tmat:r
set outf = ${tmatr}-range-high-${ranks}-${noise}.txt

set tos = (`cat $range | sort -n -r`)

if (-e $outf) /bin/rm $outf
touch $outf
foreach t ( $tos )
	set tmpmatr = tmpmat-$$-$t
	cat $tmat | \
	    awk -v to=$t 'NR==1{print;next;}{for (i=2;i<=NF;i++){if($i>to){$i="Inf";} print $0;}}' | \
	    cat > ${tmpmatr}.txt
	echo ''
	set cmd = ( pairs-compare.csh ${tmpmatr}.txt $noise)
	/bin/echo $cmd >> $outf
	$cmd
	/bin/echo -n $t TOP_${ranks} >> $outf
	cat ${tmpmatr}-${noise}-ranked1.txt | \
	  egrep MYDOMINS | \
	  awk -v ranks=${ranks} 'NR<=ranks {printf " %s %s", $2, $3;}' | \
          cat >> $outf
	/bin/echo '' >> $outf

	# /bin/rm ${tmpmatr}.txt 
	# /bin/rm ${tmpmatr}-${noise}-ranked1.txt 
	if (! -d TmpDir-$$) mkdir TmpDir-$$
	/bin/mv ${tmpmatr}.txt TmpDir-$$
	/bin/mv ${tmpmatr}-${noise}-ranked1.txt TmpDir-$$

	/bin/rm ${tmpmatr}-${noise}-report.txt 
	/bin/rm ${tmpmatr}-${noise}-scores.txt 
	/bin/rm ${tmpmatr}-${noise}-ranked2.txt 
	end

#   (over)writes matrix-noise_level-report.txt
#   (over)writes matrix-noise_level-scores.txt
#   (over)writes matrix-noise_level-ranked1.txt
#         MYDOMINS precosat_236 30
#   (over)writes matrix-noise_level-ranked2.txt

find-domin-changes.csh $outf

