#!/bin/bash
#set -x

clock=455000


testit ()
{
  local n=$1
  local tape=/tmp/big.asc
  local demo=findbig.demo
  echo "algol,_i<" >$tape
  echo "n: $n" >>$tape
  echo "_b_e_g_i_n" >>$tape
  echo "_i_n_t_e_g_e_r i;" >>$tape
  echo "_f_o_r i:=1 _s_t_e_p 1 _u_n_t_i_l 10 _d_o" >>$tape
  echo "_b_e_g_i_n" >>$tape
  for((i=1; i<=n; i++))
  do
    echo "i := i;" >>$tape
  done
  echo "_e_n_d;" >>$tape
  echo "_e_n_d;" >>$tape
  echo "t<" >>$tape
  echo "LOADPUNCH /tmp/bigout.flx" >$demo
  echo "LOADREADER $tape" >>$demo
  echo "WAITINPUT" >>$demo
#   r
  echo "TYPE 41" >>$demo
  echo "WAITINPUT" >>$demo
#   <
  echo "TYPE 17" >>$demo
  echo "WAITINPUT" >>$demo
# run<
  echo "DEBUG 901" >>$demo
  echo "TYPE 41" >>$demo
  echo "WAITINPUT" >>$demo
  echo "TYPE 20" >>$demo
  echo "WAITINPUT" >>$demo
  echo "TYPE 37" >>$demo
  echo "WAITINPUT" >>$demo
  echo "TYPE 17" >>$demo
  echo "WAITINPUT" >>$demo
  echo "FINISHPUNCH" >>$demo
  echo "QUIT" >>$demo
  ../GIER $demo
  flx2a </tmp/bigout.flx|fgrep -q ok
  result=$?
}

#for config in help3demo big1 buffertape disc1 drumtjek drumtjekga4
#for config in drum3bufga4 drum3nobufga4 aarhus drum1bufcarr
#for config in big3 aarhus2
#for config in help3demo big1 buffertape disc1 drumtjek drumtjekga4 drum3bufga4 drum3nobufga4 aarhus drum1bufcarr aarhus2
for config in normseg maxseg
do
  echo config: $config `date`
  outfile=$config
  lo=100
  hi=20000
  lo=10970
  hi=10980
  lastok=0
  declare -A failpass
  while [ $(expr $hi - $lo) -ne 1 ]
  do
    mid=$(expr $lo + '(' $hi - $lo ')' / 2)
    echo $lo $mid $hi
    cp ../configs/$config.gier default.gier
#         select(16) goes to punch, too:
    echo "Select3	00000030" >>default.gier
    echo "kb1_visible	00000000" >>default.gier
    echo "kb2_visible	00000000" >>default.gier
    testit $mid
    flx2a </tmp/bigout.flx
    if [ $result -eq 0 ]
    then
      echo $mid ok
      lastok=$mid
      lo=$mid
    else
      echo $mid bad
      hi=$mid
      lastpass=0
      flx2a </tmp/bigout.flx >/tmp/bigout.asc
      while read l
      do
	c1=${l:0:1}
	c2=${l:1:1}
	if [ "$c2" == "." ]
	then
	  lastpass=$c1
	fi
      done </tmp/bigout.asc
      echo lastpass: $lastpass
      failpass[$mid]=$lastpass
    fi
  done

  outfile=$outfile'_'$lastok
  if [ $lastok -gt 0 ]
  then
    cp ../configs/$config.gier default.gier
#         select(16) goes to punch, too:
#   echo "Select3	00000030" >>default.gier
#                       00000800 execute
#                       00000400 buffer
#                       00000100 drum
#   echo "debug	00000901" >>default.gier
    echo "kb1_visible	00000000" >>default.gier
    echo "kb2_visible	00000000" >>default.gier
    testit $lastok
    mv gier.debug $outfile.debug
  fi
done
