#!/bin/csh -f

# Find the first number i from the range $1 to $2 (may be increasing
# or decreasing) such that the command $3 $i $argv[4-] exits with
# status 0 (assuming that status is a nonincreasing function of $i).
# (Works by binary search so that $3 gets executed a number of times
# equal to only about log base 2 of the difference between $1 and $2.)
# If there is no such i, this command exits with status 1.

set tempresults = /tmp/binsearch.$$
touch $tempresults

set first = $1
set last = $2

set sign = ""
set sortopt
if ($first > $last) then
  set sign = '-'
  set sortopt = '-r'
endif

set modfirst = `expr $first \* ${sign}1`
set modlast = `expr $last \* ${sign}1`

while ($modfirst <= $modlast)
  set mid = `expr \( $first + $last \) / 2`
  $3 $mid $argv[4-] > /dev/null
  if ($status) then
    echo $mid 1 >> $tempresults
    set first = `expr $mid + ${sign}1`
  else
    echo $mid 0 >> $tempresults
    set last = `expr $mid - ${sign}1`
  endif
  set modfirst = `expr $first \* ${sign}1`
  set modlast = `expr $last \* ${sign}1`
end

set overallres = `grep ' 0' $tempresults | sort -n $sortopt | head -n 1 | cut -d\  -f1`

echo $overallres

rm -f $tempresults

if ("$overallres" == "") exit 1
