#!/bin/sh -x

############################################################
# Computes eigenvalue E = E(x0) for toy-deuteron problem 
# using "shooting" and bisection search. Uses the following 
# empirical facts:
#
#   If E_trial > E then u(xmax) < 0
#   If E_trial < E then u(xmax) > 0
#
# Uses perl scripts
#
#   bsnew
#   bslo
#   bshi
#   bsdone
# 
# which provide rudimentary bisection search facility
#
# An initial bracket [<Elo>,<Ehi>] must be provided, as well
# as a tolerance <Etol> for the bisection search.  Observe
# that due to the previously noted facts, will generally need 
# Elo > Ehi.  Also note that E(x0) < 0 (bound states), and
# at least for a certain range of x0 (e.g. 2.0 <= x0 <= 6.0), 
# a suitable initial bracket is [0.0,-1.0]
# 
# Output accumulated in directories/files
#
#   x0=<x0>/E=<E>
############################################################

P=`basename $0`

usage() {
printf "$P <x0> <Elo> <Ehi> <Etol> <xmax> <dxout>"
printf " <lsoda tol> [<xvstrace>]\n"
exit 1
}

die() {
echo "$P $1"
exit 1
}

case $# in 
7|8) x0=$1; Elo=$2; Ehi=$3; Etol=$4; xmax=$5; dxout=$6;
   lsodatol=$7; xvstrace=${8-false};
   case $xvstrace in
   true|false) ;;
   *) "xvstrace must be 'true' or 'false'";;
   esac;;
*) usage;;
esac

# Set tolerance for binary search
export BSTOL=$Etol

# Make executable if necessary
test -f deut || make deut

# Create results directory if necessary
dir="x0=$x0"
test -d $dir || mkdir $dir

# Initialize the bisection search
bsnew $Elo $Ehi

# Perform the bisection search
while bsnotdone; do
   Ecurr=`bscurr`
   ofile="$dir/E=$Ecurr"
   deut $x0 $Ecurr $xmax $dxout $lsodatol > $ofile
   $xvstrace && nth 1 2 < $ofile | xvn $P $x0
   flag=`tail -1 $ofile | nth 4`
   case $flag in
    1) bshi;;
   -1) bslo;;
    *) echo "$P: Unexpected flag value '$flag'"; exit 1;;
   esac
done

# Save results of final integration  ...
nth 1 2 < $ofile > $dir/solution

# ... and print summary to 'deut-results'
printf "%12s %25s %25s %12s %12s\n" \
   $x0 $Ecurr `bsfrac` $dxout $lsodatol >> deut-results