#!/bin/csh -f
#
# UNDUL: The driver script for the undulator modeling code of SHADOW.
#
# Author: Mumit Khan <khan@xraylith.wisc.edu>
#
# Source: src/source/id/undul
#
# ----------------------------------------------
#               SHADOW
#    Center for X-ray Lithography
#  University of Wisconsin-Madison
#  3731 Schneider Dr., Stoughton, WI, 53589
# ------------------------------------------------
#
# Log:	undul
# Revision 1.2  91/04/02  13:42:12  khan
# Added SUN path.
# 
# Revision 1.1  90/07/17  23:33:47  khan
# Initial revision
# 
#
#

#
# This is the undulator driver script. It's called by MAKE_ID.
#

# set debug if it's a debug session.

set debug = 

# First of all, Where are all the programs? Set it to nothing if all the
# programs are in the PATH variable of the SHELL.

if (! $?SHADOW_ROOT) then
    echo "Must have SHADOW_ROOT defined in the environment"
    echo "source .shadowrc before running shadow."
    exit 1
endif

if (! $?SHADOW_PROGDIR) then
    setenv SHADOW_PROGDIR $SHADOW_ROOT/bin
endif

# The VMS version of UNDUL runs a set of 3 programs, and these programs
# communicate with this shell script via LOGICALS. Since Unix processes 
# can't set the environment of parent processes (god knows why), we have 
# to kludge it (sort of like tset does) by writing the environment strings 
# to a file and source'ing the file. So define the SHADOW_ENV_FILE to pick 
# a file. 

if (! $?SHADOW_ENV_FILE) then
    setenv SHADOW_ENV_FILE  "/tmp/shadow-env-${USER}"
endif

# Now set up the undulator parameters by running undul_set. UNDUL_SET 
# sets a environment variable F_EXTERNAL to either 'INTERNAL' or
# 'EXTERNAL' depending on whether we should use the supplied UNDULATOR
# program (UNDUL_PHOT), or run a user specified one.

#if (-e $SHADOW_ENV_FILE) rm -f $SHADOW_ENV_FILE

$debug $SHADOW_PROGDIR/undul_set

source $SHADOW_ENV_FILE
rm -f $SHADOW_ENV_FILE

#
# Set up the label to loop until we are signalled to be done by UNDUL_CDF.
#
ucalc:

switch ($F_EXTERNAL)
    
    case 'INTERNAL':
	$debug $SHADOW_PROGDIR/undul_phot
	breaksw

    case 'EXTERNAL':
	echo -n "Name of External Program ? "; set EXT_PROG = $<
	$EXT_PROG
	breaksw
    
    default:
	echo "Bad environment return from UNDUL_SET: $F_EXTERNAL"
	exit 1
	breaksw

endsw

#
# Compute the CDF and also do the output. This program sets the
# environment variable FINISH to 'YES' if the optimization is done. If
# not, we simply loop back.
#

#if (-e $SHADOW_ENV_FILE) rm -f $SHADOW_ENV_FILE

$debug $SHADOW_PROGDIR/undul_cdf

if (-e $SHADOW_ENV_FILE) then
    source $SHADOW_ENV_FILE
#    rm -f $SHADOW_ENV_FILE
endif


#
# Loop back unless ALL the optimizations are done. The 'done' flag is
# set by UNDUL_CDF. It sets the environment string FINISH to 'YES'. In
# effect, we loop as long as FINISH in NOT defined, since it can take
# only one value.
#
if (! $?FINISH) then
    goto ucalc
else
    unsetenv FINISH
    unsetenv F_EXTERNAL
endif

# all done.

exit 0
