#! /bin/csh -f
#
echo "Wedger Elves 1.3      Because you have better things to do.(TM)   James Holton 2-5-07"
echo ""
#
# automatic X-ray data wedge processor
# and mosflm script generator
#
# Wedger elves use a wide, flexible range of input information to build a 
# runnable MOSFLM script to process a single wedge of crystallographic 
# X-ray data, and then run it. If left on their own, the elves will go 
# to great lengths to find the informaion they need in the computer's 
# filesystem.  In either case, the elves make a brief presentation for 
# your approval before processing your data.  
# Try it!  Let me know what you think.
#
#   jamesh@ucxray.berkeley.edu
#
if($#argv == 0) cat << EOF-lawyers
Copyright ©1999. The Regents of the University of California (Regents). All Rights Reserved. 

     Permission to use, copy, modify, and distribute this software and its 
     documentation for educational, research, and not-for-profit purposes, 
     without fee and without a signed licensing agreement, is hereby granted, 
     provided that the above copyright notice, this paragraph and the following 
     two paragraphs appear in all copies, modifications, and distributions. 
     Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck 
     Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial 
     licensing opportunities. Created by James Holton, Department of Molecular 
     and Cell Biology, University of California, Berkeley. 
  
     IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, 
     SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, 
     ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF 
     REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  
     REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED 
     TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
     PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED 
     HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
     MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. 

EOF-lawyers
#
#
# For most variables, the precedence of information sources goes something like
# this:
# 1)	Interactive User input (command-line, etc.) in order given
# 2)	Stuff found in files given by user (in order given)
# 2)	Info in files from last Mosflm run 
# 3)	Stuff found in nearby computer files
# 4)	Image File Header
# 5)	Internal Defaults
# 
#
#  EG: If an image file is specified on the command line, that file's name
# will take precedence over any scripts when determining the 
# location and number of frames.
# 
####################################################################################
#
#   Other programs that Wedger's elves need to work:
#   /bin/csh	(tested on IRIX, OSF1, linux)
#   nawk
#   grep
#   egrep
#   ipmosflm	(of course)  tested with v 5.5x and 6.0x
#   CCP4    (mtzdump, sortmtz, scala, truncate, rotaprep)
#
#
####################################################################################
####################################################################################
#  Set up OS-specific fixes (not too many we hope)
set OPERATING_SYSTEM = `uname`
set prefered = gawk
if("$OPERATING_SYSTEM" =~ IRIX*) set prefered = nawk
if("$OPERATING_SYSTEM" == "linux") set prefered = awk

# make sure nawk works
set program = "nawk"
foreach name ( $prefered gawk nawk awk )
    test -x "$program"
    if(! $status) break
    
    set possibilities = `which $name |& grep -v ' not in ' | tail -1`
    foreach file ( $possibilities )
	test -x "$file"
	if(! $status) then
	    # test for desired functionality (change this?)
	    set temp = `echo "1.54" | $file '{printf("%3d", 3147.7 * ( $1 )^(-3.014))}' |& cat`
	    if("$temp" == 856) then
		set program = "$file"
		break
	    endif
	endif
    end
    unset possibilities
end
test -x "$program"
if($status) then
    set program = "awk"
    foreach place ( /bin /usr/bin /usr/local/bin  )
	test -x "$program"
	if(($status)&&(-e $place)) then
	    # keep looking
	    set files = `ls -1L ${place} |& grep "$program" |& sort -4n |& head -20 `
	    foreach file ( $files )
		# test for desired functionality
		set temp = `echo "1.54" | $file '{printf("%3d", 3147.7 * ( $1 )^(-3.014))}' |& cat`
		if("$temp" == 856) then
		    set program = "$file"
		    break
		endif
	    end
	endif
    end
endif

# agressively search for nawk in likely places
test -x "$program"
if($status) then
    echo -n "Looking for $program "
    foreach place ( /bin /usr/bin /usr/local/bin /usr / )
	test -x "$program"
	if(($status)&&(-e $place)) then
	    if("$place" == "/") echo -n "uhh"
	    
	    # use find to get candidate files
	    set files = `find $place -name '*'$program \( -type l -o \( -type f -size +10000c \) \) -perm -1 -print |& egrep -v "^find:" |& head -20`
	    foreach file ( $files )
		# test for desired functionality
		set temp = `echo "1.54" | $file '{printf("%3d", 3147.7 * ( $1 )^(-3.014))}' |& cat`
		if("$temp" == 856) then
		    set program = "$file"
		    break
		endif
	    end
	endif
	
	# entertainment
	echo -n "."
    end
endif

# check that we found the right awk program
set temp = `echo "1.54" | $program '{printf("%3d", 3147.7 * ( $1 )^(-3.014))}' |& cat`
if("$temp" == 856) then
    # set up this awk program as nawk
    set nawk = "$program"
    alias nawk $nawk
else
    echo "Dagnabbit!  We can't find a suitable awk program.  What kind of unix is this? "
    echo "Elves may not be able to work."
    set nawk = /bin/awk
    alias nawk awk
endif

# nice symbols, but may not be portable
set ANG = `echo "" | nawk 'BEGIN{printf "\305"}'`
set DEG = `echo "" | nawk 'BEGIN{printf "\260"}'`
if("$OPERATING_SYSTEM" =~ IRIX*) then
    # this will work for sure
    set ANG = `echo "\0305"`
    set DEG = `echo "\0260"`
endif
# I give up...
set ANG = "A"
set DEG = " deg"

# fix OSF1 csh echo shortcomings
set temp = `echo -n "test"`
if(($#temp == 2)&&(-e /usr/bin/echo)) then
    alias echo /usr/bin/echo
endif

# CCP4 is handled later

# check that current directory is writable
touch ./this$$ >& /dev/null
if($status) then
    # can't write to current directory!
    chmod u+w . >& /dev/null
    touch ./this$$ >& /dev/null
    if($status) then
	# can't chmod current directory either
	echo "ERROR! We can't write to this directory! "
	pwd
	echo "Please cd to the place you want to process your data, and"
	echo "then run $0 again."
	exit 9
    else
	# warn user about what we did
	echo "Had to make current directory writable:"
	echo "chmod u+w ."
    endif
    rm -f ./this$$ >& /dev/null
endif
rm -f ./this$$ >& /dev/null


# fix old Irix od shortcomings
alias ood od
echo "test" >! ./this$$
set test = `od -c -j 2 -N 4 this$$ |& nawk '{print $2}'`
if("$test" != "s") then
    # no -j option supported, compensate:
    # od -x -j offset ... --> od -x ... offset
    #alias ood /bin/od
    alias ood `which od | tail -1 | awk '{print $NF}'`
    alias od 'od \!:1 \!:$ \!:3.'
    set WEAK_od
endif
rm -f ./this$$ >& /dev/null


# character for ringing the terminal bell (alert user)
set BELL = `echo "" | nawk 'BEGIN{printf "\07"}'`
set oldTTYerase = "^H"

# go automatic if user is ignoring us
test -t 1
if($status) then
    echo "output is not a terminal."
    # Q&A would stop Wedger process cold
    echo "Wedger elves will answer their own questions."
    echo ""
    echo "$0 $*"
    echo "on "`hostname -s`" at "`date +"%T %D"`
    echo "in "`pwd`
    set AUTO
else
    # fix annoying TTY ^H characters (but save the current one so we don't mess up emacs)
    set oldTTYerase = `stty -a | nawk '{for(i=1;i<=NF;++i){if($i == "erase"){print substr($(i+2),1,2)}}}'`
    #stty erase ^H
endif

# prevent file overwrite errors? 
#unset noclobber

# no core dumping! 
limit coredumpsize 0
# prevent never-ending mosflm jobs (5 hours)?
#limit cputime 18000

# clean up if Wedger Elves are killed
#onintr Cleanup
onintr
#
# set Wedger prompt
set PROMPT = "W. Elves-> "
#
# English input is command line
set FIRSTIME

####################################################################################
set mosflm_status = 0
set last_mosflm_status = 0
set last_mosflm_status = 0
set last_mosflm_failure = 0
set last_changed = ""
set last_failure = ""
set failure_count = 0
set chronic_failures = 0
set temp
set input
set Delta_orient = 99
set Delta_mosaic = 99
set Delta_distance = 99
set Delta_cell = 99
set shift_orient = 10
set shift_mosaic = 10
set shift_distance = 10
set shift_cell = 10

# program limits
set MAX_Cycles = 50
set Cycle      = 0
set Successes  = 0
# reduce these if you are getting "word to long" errors
set MAXLINE  = 1000
set MAXWORDS = 10
# or if Wedger elves are looking at too many scripts
set MAXSCRIPTS = 5

# list of known image filename patterns
set IMAGE_pattern = 'BEGIN{FS="."} {n=NF-1;if(n<1)n=1} $n~/[0-9][0-9][0-9]$/ || $NF~/[0-9][0-9][0-9]$/{print}'
set not_IMAGE_pattern = '! (/[0-9][0-9][0-9].img$/ || /[0-9][0-9][0-9].osc$/ || /[0-9][0-9][0-9].image$/ || /[0-9][0-9][0-9].mar/ || /[0-9][0-9][0-9][0-9]$/ && ! /^[PCIFHR][1-6]/ || /[0-9][0-9][0-9].corr$/)'

# predefine list of "potentially" useful mosflm cards
set MOSFLM_CARDS = "SITE     SCAN     POLAR    GAIN     DIRE     IDEN     EXT      IMAG     \
		    MATRIX   NEWMAT   WAVE     DISP     DIVE     BEAM     BACKSTOP DISTA    \
		    CELL     SYMM     LATT     MOSAIC   RESO     DSTARMAX TWOT     PROFILE  \
		    ADCO     BACKG    BIAS     BSWA     DISTO    SYNC     THICK    SHIFT    \
		    FIDU     SIZE     LIMIT    PIXEL    NULLP    OVERLOAD SEPA     ADDP     \
		    MAXWIDTH POSTREF  PROCESS  REFI     RAST     REJECT   PRINT    SDMON    \
		    WAIT     PLOT     SPOTS"
set MOSFLM_CARDS = `echo $MOSFLM_CARDS`

# list of mosflm cards used in file search
set SEARCH_CARDS = "^SITE|^SCAN|^LIMIT|^POLAR|^GAIN|^DIRE|^IDEN|^EXT|^IMAG|^MATRIX|^NEWMAT|^WAVE|^DISP|^DIVE|^BEAM|^BACKSTOP|^DISTA|^CELL|^SYMM|^MOSAIC|^RESO|^RASTER"

# list of relevant mosflm cards not handled by Wedger (yet)
set PASSTHRU_CARDS = "^BACKSTOP|^FINDSP|^SPOTS |^LATTICE|^DSTARMAX|^PROFILE|^ADCO|^BACKG|^BIAS|^BSWA|^DISTO|^SYNC|^THICK|^SHIFT|^FIDU|^SIZE|^PIXEL|^NULLP|^NUSPOT OFF|^SEPA|^ADDP|^MAXWIDTH|^RAST|^REJECT|^PRINT|^SDMON|^WAIT|^CAMCON"
#
set PREAMBLE = ""
set EXTRA_REFINE_CARDS = ""
unsetenv MOSFLM_VERSION_NUMBERS
#

# check that directory is writable
touch ./this$$ >& /dev/null
if($status) then
    # can't write to current directory!
    chmod u+w . >& /dev/null
    touch ./this$$ >& /dev/null
    if($status) then
	# can't chmod current directory either
	echo "ERROR! We can't write to this directory! "
	pwd
	echo "Please cd to the place you want to process your data, and"
	echo "then run $0 again."
	exit 9
    else
	# warn user about what we did
	echo "Had to make current directory writable:"
	echo "chmod u+w ."
    endif
endif
rm -f ./this$$ >& /dev/null

# make needed directories
#if( -e temp) then
#    test -d temp >& /dev/null
#    if($status) then
#	echo "WARNING: moving temp to temp.bak"
#	mv temp temp.bak
#    endif
#endif
if( -e logs) then
    test -d logs >& /dev/null
    if($status) then
	echo "WARNING: moving logs to logs.bak"
	mv logs logs.bak
    endif
endif
#if(! -e temp) mkdir temp
if(! -e logs) mkdir logs

####################################################################################
####################################################################################
####################################################################################
# process "dash" options immediately
set command_line_argv = $0
set i = 1
while( $i <= $#argv )
    set arg = $argv[$i]

    if("$arg" =~ -norun)	set NORUN
    if("$arg" == -1)		set ONCEONLY
    if("$arg" == -1)		set AUTO
    if("$arg" == -auto)		set AUTO
    if("$arg" == -new) 		set NEW 
    if("$arg" == new) 		set NEW 
    if("$arg" =~ *index) 	set NEW 
    if("$arg" =~ *index) 	set autoindexing
    if("$arg" =~ "-"nosear*)	set NEW
    if("$arg" =~ nosear*)	set NEW
    if((("$arg" == no)||("$arg" == "-no"))&&($i < $#argv)) then
	@ i = ( $i + 1 )
	if("$argv[$i]" =~ sear*) set NEW
    endif
    if(("$arg" == "-burst")||("$arg" == "hurry")) then
	set HURRY
	set BURSTMODE = 3
	if($i < $#argv) then
	    # look for a user-specified burst count
	    @ i = ( $i + 1 )
	    set temp = `echo $argv[$i] | nawk '{printf "%d", $0+0}'`
	    if($temp != 0) then
		set BURSTMODE = $temp
		# don't confuse this with image count
		set argv[$i] = ""
	    endif
	endif
    endif

    if("$arg" =~ -h*)		set help
    
    @ i = ( $i + 1 )
end

if(($?help)||($#argv == 0)) then
    cat << EOF
usage: $0 [/dir/[image_001.img]] [script.com] [num] [SG] [[fix]cell a b c A B G]

                (items in braces [] are optional.)

/dir          :  location of frames to process
image_001.img :  name of first image to process
num           :  number of images to process
SG            :  space group
script.com    :  name of file containing beamline-specific mosflm cards
                 (like an old script)

refinement options:
(no)refine    :  (don't) refine cell on a subset of frames
(no)integrate :  (don't) integrate spots on all frames
(no)fixcell   :  (don't) fix the cell during refinement
(no)fixyscale :  (don't) fix the Y scale during refinement

program options:
-norun        :  create the mosflm script, but don't run it.
-1            :  single-shot     (exit after one mosflm run)
-semi         :  semi- automatic (default) prompts user for go-ahead.
-burst [n]    :  n-round burst (default: 3 refinement runs, and integrate once)
-auto         :  fully automatic (run a standard processing regimen)

-new          :  ignore old files and start mosflm refinement fresh
-nice         :  tell Wedger elves to nice their jobs
-h            :  display this message

EOF
# (no)usebeam   :  (don't) use refined mosaicity, distance, etc. in integration (default)
endif
if($?help) exit


####################################################################################
#  Internal Defaults
#
#	Easily overridden by pevious script, image file, or questionaire.
####################################################################################
#
# Input files
set best_matrix		= best.mat
set inmatrix		= ""
set inframes		= ""
set oldscripts 		= ""
set user_sources	= ""
set matrixfiles		= ""
set badmatrix		= ""
set bad_frames		= ""
#
# Output files
set scriptname		= mosflm.com
set outmatrix		= postref.mat
set missets		= "0 0 0"
set mtzout		= raw.mtz
set mergefile		= merged.mtz
set logfile		= logs/
set lastlog		= ""
set mergescript		= merge.com
#
set tempfile		= Wedger_temp
#
# program location
set MOSFLM		= ipmosflm
set MosflmVersion	= ""
set Interactive		= "#PLOT"
#
# crystal/protein parameters
set xtal                = `whoami`	
set SG                  = unknown
set SG_number		= 0
set wrongSGs            = ""
set CELL                = unknown
set res_choice          = auto
set SG_choice           = auto
set hires               = ""
set merge_res           = ""
set VRSET               = "#"
set detector_res_limit  = ""
set mtz_res             = ""
#set MolWt		= 4000
set mosaic		= auto

# filesystem/collection parameters
set framedir 		= /data/`whoami`/${xtal}
set frameprefix		= ""
set ext			= "img"
set template		= ""
set FirstImage		= ""
set phi0                = 0.0
set osc                 = 1
set first		= 1
set last		= ""
set add			= 0
set ident		= "frame"
set swap                = ""

# Alignment/centering parameters
set wavelength		= "1.5418"
set distance		= "100"
set beam_center		= ""
set two_theta		= 0
#
# default Detector/beam parameters (Quantum-4)
set Site		= ""
set SCANNER		= "SITE SSRL"
set SCANNER		= "SCANNER omega 90 ROTATION horiz ANTI FAST horiz ORIGIN UR RECTANG TYPE ADSC"
set LIMITS		= "LIMITS RMAX 188 YMAX 188 XMAX 188 xscan 188 yscan 188"
set GAIN		= 1
set DISPERSION		= 0.0025
set DIVERGENCE		= "0 0"
set POLARISATION	= "SYNCHROTRON 0.9"
set OVERLOAD		= default
set PIXEL		= 0.1
set Width		= ""
#
# default SDcorr card for scala
set DEFAULT_SDCORR
set SDCORR		= "1.3 0 0.03"
#
# automatic postrefine parameters
set mosflm_postref_segs = "auto"
set frames_per_segment  = "auto"
set ESTIMATING = ""
set SAVE_hires = ""
#
# fancy mosflm options
set integrate		= no
set postref		= yes
set strategize		= yes

#set usebeam		= no
set fixmosaicity        = no
set fixcell		= no
set fixyscale		= no
set true_cell		= unk
set reinput_missets	= no
#
set check_frames	= yes
set number_of_frames 	= ""
set autoindexing_frames = 4
set autoindexing_cutoff = 0.2
set wedge_width		= 0

####################################################################################
#
#
#  Collect information about this project
#
#
####################################################################################
#
# Remember explicit command-line arguments that are existing files
foreach arg ( $* )
    if(-e "$arg") then
	set temp = `ls -lnd $arg |& nawk '! /^d/ {print $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	if(-e "$temp") set user_sources = `echo $user_sources $arg`
    endif
end
#
####################################################################################

 ######     #    #    #  #####        ####    ####   #####      #    #####    #####   ####
 #          #    ##   #  #    #      #       #    #  #    #     #    #    #     #    #
 #####      #    # #  #  #    #       ####   #       #    #     #    #    #     #     ####
 #          #    #  # #  #    #           #  #       #####      #    #####      #         #
 #          #    #   ##  #    #      #    #  #    #  #   #      #    #          #    #    #
 #          #    #    #  #####        ####    ####   #    #     #    #          #     ####

####################################################################################
#
#   Criteria:
#	1)  must contain lines resembling mosflm commands
#	2)  Files with extensions .mat .log are ignored
#	3)  Files matching $IMAGE_pattern are also ignored
#
#   Precedence:
#	1)  files listed on command line
#	2)  files in directories listed on command line
#	3)  file matching last Wedger run
#	4)  files containing mosflm commands found in the filesystem
#
#
#   Produces: $oldscripts,  a precedence-ordered list of files
#
# search through command-line arguments for files containing mosflm keywords
set i = 0
while ( $i < $#argv )
    @ i = ( $i + 1 )
    set arg = "$argv[$i]"
    
    # check for things we know aren't scripts
    if("$arg" =~ -*) continue
    if("$arg" =~ *.log) continue
    if("$arg" =~ *.mat) continue
    set test = `ls -lnL $arg |& nawk '$5+0>1000000{print $NF}' |& nawk "$IMAGE_pattern" | wc -l`
    if($test != 0) continue
    
    # check for command-line args that LOOK like scripts, but don't exist as a file
    if(! -e "$arg") then
	if("$arg" =~ */*) then
	    # could be a template
	    set dir = `dirname $arg`
	    set prefix = `basename $arg`
	    ls -1L $dir |& egrep "^$prefix" >& /dev/null
	    if($status) echo "WARNING: the file $arg does not exist."
	endif
	if(("$arg" =~ *.com)||("$arg" =~ *.sh)||("$arg" =~ *.csh)) echo "WARNING: the file $arg does not exist."
	continue
    endif
    
    # see if arg is a directory (containing files containing mosflm keywords)
    set dir = `ls -lnLd $arg |& nawk '/^d/{print $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
    if("$dir" != "") then
	# look for scripts in this directory (small ones) that contain mosflm cards
	set files = `ls -lnLt $dir |& nawk -v path=$dir '/^-/ && $5 < 500000 {print path $NF}' |& head -$MAXSCRIPTS |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`

	# filter these files for ones containing interesting words
	set scriptfiles = ""
	foreach file ( $files )
	    set safehead = `ood -cv $file | nawk '{for(i=2;i<=NF;++i) print $i}' | nawk '/\\n/{++n;c=0} {++c} c>1000{exit} END{print n+0}'`
	    head -$safehead $file | egrep -li "$SEARCH_CARDS" >& /dev/null
	    if(! $status) then
		set scriptfiles = ( $scriptfiles $file )
	    endif
	end
	set files = ( $scriptfiles )
	
	# make sure this list doesn't get too long (csh can't handle long lines)
	if((-e "$files[$#files]")&&($#oldscripts < $MAXSCRIPTS)) then
	    set oldscripts = `echo $oldscripts $files |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	endif
	continue
    endif
    # $arg is a file that exists
    
    # could this be a mosflm executable? 
    file $arg |& grep "executable" |& grep -v "text" >& /dev/null
    if(! $status) then
	# this is an executable binary!  Don't try to read keywords from it
	continue
    endif
    
    # filter command-line-provided files for cards
    set safehead = `ood -cv $arg | nawk '{for(i=2;i<=NF;++i) print $i}' | nawk '/\\n/{++n;c=0} {++c} c>1000{exit} END{print n+0}'`
    head -$safehead $arg | egrep -li "$SEARCH_CARDS" >& /dev/null
    if(! $status) then
	set oldscripts = `echo $oldscripts $arg `
    else
	set size = `ls -lnLd "$arg" |& nawk '{print $5+0; exit}'`
	if(($safehead > 0)&&("$size" < 1000000)) then
	    echo "WARNING: $arg does not contain mosflm commands. ... ignoring it."
	endif 
    endif
end

set oldscripts = `echo $oldscripts |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`

# look for old Wedger-generated script next
if(("$oldscripts" == "")&&(-e "$scriptname")&&(! $?NEW)) then
    # make sure there are actually keyword cards in there
    set temp = `egrep -li "$SEARCH_CARDS" $scriptname`
    if("$temp" != "") then
	 set oldscripts = "$scriptname"
    endif
endif

# report on files that were deemed useful
if("$oldscripts" != "") then
    echo -n "found: "
    set temp = `echo $oldscripts |& nawk '{print length($0)}'`
    if("$temp" < 80) then
	echo $oldscripts
    else
	echo ""
	ls -1d $oldscripts 
    endif
    echo ""
endif


# agressive search may be annoying for first-time users
if( ("$oldscripts" == "")&&(! $?NEW) &&(! $?autoindexing) ) set SEARCH_HARD
# if a lot was said, don't second-guess user
if("$2" == "") unset SEARCH_HARD

# if no information found yet, perform an agressive search around immediate directories 
# for critical mosflm cards
if( $?SEARCH_HARD ) then
    echo -n "Looking around for crystal info ... "
    if(! $?AUTO) then
	onintr SkipScriptSearch
	echo -n "(Ctrl-C to skip) "
    endif
    set temp = ""
    
    # in order of precedence:
    #              old    other wedge    other wl         ALS             SSRL has good image headers 
    foreach place ( ./ ../ ../*/ ../../ ../../*/*/ ~/ ~/mosflm_scripts/ )

	# filter out repeated searches
	set temp = `pwd`
	if(`basename $place` == `basename $temp`) set place = ""

	if((-e "$place")&&($#oldscripts < $MAXSCRIPTS)) then

	    # get $MAXSCRIPTS most recent non-log files of reasonable size from each $place
	    set files = `ls -lnLt ${place} |& nawk -v dir=$place '/^-/ && $5 < 500000 {print dir $NF}' |& nawk "$not_IMAGE_pattern" |& grep -v "$0" |& egrep -v '\.mat|\.log' |& head -$MAXSCRIPTS |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`

	    # remember files containing important mosflm keywords in reverse precedence order
	    if(-e "$files[$#files]") set files = `egrep -li "$SEARCH_CARDS" $files`
	    if(-e "$files[$#files]") then
		# any file that survived is potentially useful
		set oldscripts = `echo $oldscripts $files`

		# print out files of interest
		echo -n "$files "
	    endif
	endif

	# stop at current directory if something is found
#	if(("$place" == "./")&&("$oldscripts" != "")) goto SkipScriptSearch
    end
    SkipScriptSearch:
    onintr
    
    # print out results of script data search
    set oldscripts = `echo $oldscripts`
    if($#oldscripts != 0) then
	echo ""
    else
	echo "didn't find anything."
	set oldscripts = ""
    endif

    echo "To prevent this search in the future, use:"
    echo "$0 $argv -new"
    echo ""
endif

####################################################################################

 ######     #    #    #  #####          ####   #       #####         #        ####    ####
 #          #    ##   #  #    #        #    #  #       #    #        #       #    #  #    #
 #####      #    # #  #  #    #        #    #  #       #    #        #       #    #  #
 #          #    #  # #  #    #        #    #  #       #    #        #       #    #  #  ###
 #          #    #   ##  #    #        #    #  #       #    #        #       #    #  #    #
 #          #    #    #  #####          ####   ######  #####         ######   ####    ####

####################################################################################
#   Criteria:
#	1)  must have .log or .lp extension
#	2)  must contain "Processing Image" mosflm output
#
#   Precedence:
#	1)  log files listed on command line
#	2)  logfile produced by last Wedger run
#	3)  logfiles found in ./ ./logs or ./log
#
# search command line for log files
foreach arg ( $user_sources )
    # screen for files with .log extension
    if(("$arg" =~ *.log)||("$arg" =~ *.lp)) then
	set lastlog = "$arg"
    endif
end

if(! $?NEW) then
    # look for most recent logfile
    if(-e "${logfile}mosflm.log") then
	set lastlog = ${logfile}mosflm.log
    else
	set lastlog = ""
    endif

    if(! -e "$lastlog") then
	# look for mosflm log files
	foreach place ( logs/ log/ ./ )
	    if(! -e "$lastlog") then
		# get list of promising files (not too long)
		set logs = `ls -lnrt ${place} |& grep -v "$0" |& egrep "log|lp" |& nawk -v dir=$place ' /^-/ {print dir $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
		
		# search these files for telltale text
		if(-e "$logs[$#logs]") then
		    set logs = `egrep -li "Processing Image|Integrating Image" $logs[$#logs]`
		endif
		if(-e "$logs[$#logs]") then
		    set logs = `egrep -li "XTOFD|Real cell parameters" $logs[$#logs] | tail -1`
		endif
		
		if("$logs" != "") set lastlog = "$logs"
	    endif
	end
    endif
endif

# set up default frame list
set i = 0
while ($i < $#argv )
    @ i = ( $i + 1 )
    set inframes = `echo $inframes $argv[$i] |& nawk -v L=$MAXLINE 'BEGIN{RS=" "} {l+=length($0)} l<L{print}'`
end

PickFirstImage:
####################################################################################

 #####    #    #    #  #####          #    #    #    ##     ####   ######   ####
 #        #    ##   #  #    #         #    ##  ##   #  #   #    #  #       #
 #####    #    # #  #  #    #         #    # ## #  #    #  #       #####    ####
 #        #    #  # #  #    #         #    #    #  ######  #  ###  #            #
 #        #    #   ##  #    #         #    #    #  #    #  #    #  #       #    #
 #        #    #    #  #####          #    #    #  #    #   ####   ######   ####

####################################################################################
#
#   Criteria:
#	1)  must have recognized naming convention ( in $IMAGE_pattern )
#	2)  must have ###.blah pattern (underscore may be added on-the-fly)
#	3)  must be > 1Mb
#	4)  must be a regular file (or link)
#	
#   Precedence:
#	1)  complete image filenames on command line
#	2)  incomplete image filenames on command line ("templates")
#	3)  images found in directories given on command line
#	4)  images indicated in scripts listed on command line
#	5)  images inspired by scripts listed on command line
#	6)  images found in directories indicated in scripts on command line
#	7)  images found in directories indicated in scripts found in filesystem
#	8)  images found in filesystem
#
####################################################################################
#
foreach arg ( $inframes )
    # squash -dash options
    if("$arg" =~ -*) continue
    
    # squash frames we know are unwanted
    foreach baddie ( $bad_frames )
	if("$arg" =~ "$baddie"*) set arg = ""
    end
    if("$arg" == "") continue

    # filter arguments for proper image extension and file name pattern
    set img = `echo "$arg" |& nawk "$IMAGE_pattern" `
    
    if("$img" != "") then
	# explicit image name was given
	set framedir = `dirname $arg`
	set ext = `basename $arg |& nawk 'BEGIN{FS="."} {print $NF}'`
	
	# see if the file exists, and is the right size
	set img = `ls -lnLd $img |& nawk '/^\-/ && $5+0 > 800000 {print $NF}'`
	
	test -r "$img"
	if(! $status) then
	    # valid first image found! 
	    set ext = `basename $arg |& nawk 'BEGIN{FS="."} {print $NF}'`
	    set temp = `basename $arg $ext`
	    
	    set FirstImage = "$arg"
	    break
	endif
    endif
    
    # no need to continue if we have an image
    if(-e "$FirstImage") break
    
    # see if $arg is a frame template ... 
    # chop off file extension (if there is one)
    set test_framedir = `dirname $arg`
    set test_frameprefix = `basename $arg |& nawk 'BEGIN{FS="."} {printf $1; for(i=2;i<NF;++i){printf "." $i}}'`
    
    if(("$test_frameprefix" != "")&&("$test_framedir" != ".")) then
	# look for frames matching this prefix
	set img = `ls -lnL ${test_framedir}/ |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& grep "$test_frameprefix" |& nawk "$IMAGE_pattern" |& head -1`
	set img = `ls -lnLd ${test_framedir}/$img |& nawk '! /^d/ {print $NF}' |& head -1`
	set img = `echo $img |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`

	# squash frames we know are unwanted
	foreach baddie ( $bad_frames )
	    if("$img" =~ "$baddie"*) set img = ""
	end
	
	test -r "$img"
	if(! $status) then
	    # good frame has been found!
	    set FirstImage = "$img"
	    break
	    
#	    echo "Extrapolated $FirstImage from $arg"
	endif
    endif

    # at this point, warn about things that look like image filenames, but aren't
    set test = `basename "$arg" | nawk "$not_IMAGE_pattern" `
    if("$test" == "") then
	# this word looked like an x-ray image
	if(-e "$arg") then
	    echo "WARNING: the file $arg does not look like an x-ray image file... ignoring it."
	else
	    echo "WARNING: image file $arg doesn't exist."
	endif
    endif
    
    # see if $arg is a directory containing frames
    if(-e "$arg") then
	set dir = `ls -lnd $arg |& nawk '/^d/ {print $NF}'`
	# look for frames in this directory
	set img = `ls -lnL $dir |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& nawk "$IMAGE_pattern" |& head -1`
	set img = `ls -lnLd ${dir}/$img |& nawk '! /^d/ {print $NF}' |& head -1`
	set img = `echo $img |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`
	
	# squash frames we know are unwanted
	foreach baddie ( $bad_frames )
	    if("$img" =~ "$baddie"*) set img = ""
	end
	
	test -r "$img"
	if(! $status) then
	    # good frame has been found!
	    set FirstImage = "$img"
	    break
	else
	    set img = ""
	endif
    endif
end

if(-e "$FirstImage") goto FirstImageFound

if($?searched_scripts) then
    # this variable set means we have alerady done "GetFramesFromScripts", so skip ahead
    goto FrameSearch
endif

# no good images found, reset search list
#set inframes = ""

GetFramesFromScripts:
###############################################################################
#
#   Look for image info provided in older mosflm script(s)
#
###############################################################################
# examine meaningful files only
set temp = `echo $oldscripts`
if("$temp" != "") then
    set temp = `egrep -li "^EXT|^DIRE|^IDEN|^IMAGE|^RAW" $temp`
endif

# collect a precedence-sorted list in $inframes (evaluate it later)
foreach oldscript ( $temp ) 

    # preprocess script for stable nawk-ing (no blank lines, no comments, 
    # no shell variables or unexpected characters )
    cat $oldscript |\
    nawk '(NF > 0) && ($1 !~ /^#/){for(i=1;i<=NF;++i){if($i !~ /[\$,]/) printf "%s", $i " "}; print ""}' |\
    nawk '{for(i=1;i<=length;++i){c=substr($0,i,1); \
	if(c ~ /[ ,\t,\",\!,\047,\140]/){ c = " " }; \
	if((c ~ /[ ,a-z,A-Z,0-9,.,_,=\/#]/)||(c == "-")){printf c }else{break}}print ""}' |\
    cat >! $tempfile

    # extract frame name and location information
    set temp = `egrep -i "^EXT" $tempfile |& nawk 'NF>1 {print $2}'`
    if($#temp >= 1) set ext		= "$temp[$#temp]"
    set temp = `egrep -i "^DIRE" $tempfile |& nawk 'NF>1 {print $2}'`
    if($#temp >= 1) set framedir	= "$temp[$#temp]"
    set temp = `egrep -i "^IDEN" $tempfile |& nawk 'NF>1 {print $2}'`
    if($#temp >= 1) set frameprefix	= "$temp[$#temp]"
    set temp = `egrep -i "^TEMPLATE" $tempfile |& nawk 'NF>1 {print $2}'`
    if($#temp >= 1) set template	= "$temp[$#temp]"
    set temp = `egrep -i "^IMAGE" $tempfile |& nawk 'NF>1 {print $2}'`
    if($#temp >= 1) set inframes	= `echo $inframes $temp[$#temp] |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
    set temp = `egrep -i "^RAW DATA FILE" $tempfile |& nawk 'NF>3 {print $4}'`
    if($#temp >= 1) set inframes	= `echo $inframes $temp[$#temp] |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`

    # Look for processing commands to get starting frame number
    set temp = `egrep -i "^PROC" $tempfile |& nawk '$2 !~ /[a-z,A-Z]/{print $2+0}' |& head -1`
    if("$temp" != "") set first = "$temp"
    # now $first is from first PROC card of this oldscript
    rm -f $tempfile >& /dev/null
    
    # add this suggestion of first frame to master list
    if(-e "$framedir") then
	set temp = `echo "$first" | nawk '{printf "%03d", $1}'`
	set file = "$framedir/${frameprefix}_${temp}.$ext"
	
	# support TEMPLATE keyword too
	if("$template" != "") then
	    set file = "$framedir/"`echo "$template $first" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
	endif
	
	set inframes = `echo $inframes $file |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	# existence, etc will be handled in the frame check
    endif
    
end

# remember passing this point
set searched_scripts

set inframes = `echo $inframes |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`


###############################################################################
#
#   Now, we have a new list of frame name suggestions from the scripts.
#   Will go back and evaluate this list same as command line
#
###############################################################################
# repeat search only if we have something to search
if(("$inframes" != "")&&(! -e "$FirstImage")) then
    goto PickFirstImage
endif


FrameSearch:
###############################################################################
#
#   Now, we have exhausted the command line, and all the scripts collected
#   from the command line as sources of information about x-ray images
#
#   But, we will not give up!    
#
#   (even if -new specified, there is nothing to do without frames)
#
###############################################################################

#check and see if ADXV has some idea
if($?XFORMSTATUSFILE) then
    if(-e $XFORMSTATUSFILE) then
	set temp = `nawk '{print $NF}' $XFORMSTATUSFILE`
	if(-e "$temp") then
	    set FirstImage = "$temp"
	    if($temp !~ *_0_*) then
		# this is probably a full data set
		set temp = `echo $FirstImage | nawk '{gsub("_[0-9][0-9][0-9]\.img","_001.img"); print}'`
		if(-e "$temp") then
		    set FirstImage = "$temp"
		endif
	    endif
	    goto FirstImageFound
	endif
    endif
endif

# collect list of promising directories, starting with subdirectories of user-indicated dirs
foreach arg ( $* $inframes )

    # squash frames we know are unwanted
#    foreach baddie ( $bad_frames )
#	if("$arg" =~ "$baddie"*) set arg = "-nothing"
#   end

    if((! -e "$FirstImage")&&("$arg" !~ -*)&&(! $?FASTsearch)) then
	# see if arg was a directory
	set dir = `ls -lnd $arg |& nawk '/^d/{print $NF}'`
	# use directory name of the arg
	if(! -e "$dir") then
	    set dir = `dirname $arg |& nawk '$0 != "."'`
	endif
	if(-e "$dir") then
	    # we have a directory to search!
	    set subdirs = `ls -lnrtp $dir |& nawk -v parent=$dir '/^d/{print parent "/" $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	    
	    foreach dir ( $subdirs )
		set img = `ls -lnL $dir |& nawk '(/^\-/ || /^l/) && $5+0 > 800000 {print $NF}' |& nawk "$IMAGE_pattern" |& head -1`
		set img = `ls -lnLd ${dir}/$img |& nawk '! /^d/ {print $NF}' |& head -1`
		set img = `echo $img |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`
		
		# squash frames we know are unwanted
		foreach baddie ( $bad_frames )
		    if("$img" =~ "$baddie"*) set img = ""
		end
		
		# check if valid image was found here
		test -r "$img"
		if((! $status)&&(! -e "$FirstImage")) then
		    # good image found!
		    set FirstImage = "$img"
		endif
	    end
	endif
    endif
end

if(-e "$FirstImage") goto FirstImageFound

if($?AUTO) goto End_of_FrameSearch
echo -n "Looking for frames "
onintr End_of_FrameSearch

# 2nd pass: look in PARENT directory of listed arguments
foreach arg ( $* $inframes )
    if((! -e "$FirstImage")&&("$arg" !~ -*)&&(! $?FASTsearch)) then
	# still not assigned, try searching same directory
	set dir = `dirname $arg`
	set img = `ls -lnL $dir |& nawk '(/^\-/ || /^l/) && $5+0 > 800000 {print $NF}' |& nawk "$IMAGE_pattern" |& head -1`
	set img = `ls -lnLd ${dir}/$img |& nawk '! /^d/ {print $NF}' |& head -1`
	set img = `echo $img |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`
	
	# squash frames we know are unwanted
	foreach baddie ( $bad_frames )
	    if("$img" =~ "$baddie"*) set img = ""
	end
		
	test -r "$img"
	if(! $status) then
	    # good image found
	    set FirstImage = "$img" 
	else
	    set img = ""
	endif
    endif
end


# More agressive search if still no frames found
if((! -e "$FirstImage")&&(! $?FASTsearch)) then
    # frame list is no good
    set inframes = ""
    set img = ""

    # look around for a frame
    foreach root ( ./ /expdata/ /data/ /*/ )
	if(-e "$root") then
	    foreach subdir ( "" `whoami` `whoami`/frames frames ../frames data ../data )
		if((-e "${root}/${subdir}")&&(! -e "$img")) then
		    # look in this directory for frames
		    set place = `echo "${root}/${subdir}" |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`

		    if((! -e "$FirstImage")&&(-e "$place")) then
			# look for first file that matches the pattern
			set img = `ls -lnL $place |& nawk '(/^\-/ || /^l/) && $5+0 > 800000 {print $NF}' |& nawk "$IMAGE_pattern" |& head -1`
			set img = `ls -lnLd ${place}/$img |& nawk '! /^d/ {print $NF}' |& head -1`
			set img = `echo $img |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`

			# squash frames we know are unwanted
			foreach baddie ( $bad_frames )
			    if("$img" =~ "$baddie"*) set img = ""
			end
		
			test -r "$img"
			if((! $status)&&(! -e "$FirstImage")) then
			    set FirstImage = "$img"
			endif

			# for entertainment
			echo -n "."
		    endif
		endif
	    end
	endif
    end

    # Really aggressive search
    if(! -e "$img") then
	echo -n " looking harder "
	foreach subdir ( `whoami`/frames `whoami` frames data "" )
	    foreach root ( ./ /expdata/ /data/ /*/ )
		# look in these directories for frames
		if(("$img" == "")&&(-e "${root}${subdir}")) then

		    # for entertainment
		    echo -n "."

		    set place = `echo "${root}${subdir}" |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`

		    # look for first file that matches the pattern
		    set img = `find $place -name '*[\-_][0-9][0-9][0-9].*' -print |& nawk 'NF==1' |& nawk ' ! /^find:/' |& nawk "$IMAGE_pattern" |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
		    set img = `ls -lnLd $img |& nawk '! /^d/ && $5+0 > 800000 {print $NF}' |& head -1`
		    set img = `echo $img |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`

		    # squash frames we know are unwanted
		    foreach baddie ( $bad_frames )
			if("$img" =~ "$baddie"*) set img = ""
		    end
		
		    test -r "$img"
		    if((! $status)&&(! -e "$FirstImage")) then
			set FirstImage = "$img"
		    endif
		endif
	    end
	end
    endif

    
    # final report
    if( -e "$FirstImage") then
	echo "found $FirstImage"
    else
	echo "didn't find any."
    endif
endif

End_of_FrameSearch:
onintr
echo ""

if(! -e "$FirstImage") then
    if(! $?AUTO) then
	set temp = "I don't know"
	echo "Where are the frames you want to process? [$temp] $BELL"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
	set inframes = "$temp"

	if("$inframes" == "I don't know") then
	    echo "Well ... We don't know either."
	    echo "Bye! "
	    set mosflm_status = 100
	    set NORUN
	    goto Cleanup
	endif
	
	set FASTsearch
	goto PickFirstImage
    else
	echo "Sorry, we can't find any x-ray image files."
	echo "Agressive image search will not be done in automatic mode."
	echo ""
	echo "please run: $0 directory/name_001.$ext"
	echo "where directory/name_001.$ext is your first x-ray image."
	echo "Later! "
	set mosflm_status = 100
	goto Cleanup
    endif
endif

FirstImageFound:
# reaching here means we have found a usable frame!

# design an image template (in case we need it)
set framedir    = `dirname $FirstImage`
set ext         = `echo $FirstImage |& nawk 'BEGIN{FS="."} $NF~/^[a-z]/{print "."$NF}'`
set FirstImage  = `basename $FirstImage`
set frameprefix = `basename $FirstImage $ext`

# make a template for recognizing filenames like this
set template = `echo ${frameprefix} $ext | nawk '{while($1~/[0-9]$/){patt=patt "\043"; $1=substr($1,1,length($1)-1)}} {print $1 patt $2}'`

# see if these filenames are back-compatible to old versions of mosflm
set compatible = `echo "$template" | nawk '/[_-]\043\043\043[.]/{print "yes"}'`

# scan for the last possible file in the wedge
ls -lnL ${framedir} |&\
nawk -v first=$FirstImage '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
cat >! ${tempfile}
set LastImage = `nawk '{print; exit}' ${tempfile}`
rm -f ${tempfile} >& /dev/null

# constrain template based on available filenames
ls -1 $framedir |\
nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print}' |\
nawk -v first=$FirstImage -v last=$LastImage '\
    $1==first{p=1} p{print} $1==last{p=0}' |\
nawk '{if(length($0)>maxlen) maxlen=length($0);\
    for(col=1;col<=maxlen;++col){c=substr($0,col,1);\
    if(tpl[col]!=c){tpl[col]=tpl[col] c}}} \
    END{for(col=1;col<=maxlen;++col){\
	if(length(tpl[col])!=1) tpl[col]="\043";\
	printf "%s", tpl[col]}; print ""}' |\
cat >! ${tempfile}
set temp = `nawk 'BEGIN{FS="\043"} {print NF}' ${tempfile}`
if("$temp" > 3) then
    set template = `cat ${tempfile}`
endif
rm -f ${tempfile}
# now we have template in "prefix###.img format"
    
# make an RE pattern for recognizing new images
set noglob
set framepattern = `echo "$template" | nawk '{gsub("[.]","[.]",$0); gsub("[+]","\\+",$0); gsub("\043","[0-9]",$0); print "^" $0 "$"}'`
unset noglob

set first = `echo "$FirstImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
set last  = `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
set FirstImage = `echo "$framedir/$template $first" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
set LastImage  = `echo "$framedir/$template $last" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`

# check for backward-compatibility
if("$compatible" != "") then
    # template has the form prefix[-_]###.ext
    # so, safe to use "old" image file breakdown
    set ext         = `echo $FirstImage |& nawk 'BEGIN{FS="."} {print $NF}'`
    set frameprefix = `basename $FirstImage .$ext | nawk '{print substr($1, 1, length($1)-4)}'`
    set TEMPLATE = ""
else
    # we will have to use the mosflm v5.4+ TEMPLATE keyword
    set TEMPLATE = "TEMPLATE $template"
    set frameprefix = `echo "$template" | nawk 'BEGIN{FS="\043"} {print $1}'`
endif


# remember rest of suggestion list (in case we come back)
set inframes = `echo $inframes |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`


#  At this point, the first frame filename is locked in.  All that remains is
#  to decide between it, the last script, logfiles, and internal defaults as
#  the source of the other parameters for mosflm.





FindMATRIX:
####################################################################################

 ######   #    #    #  #####       #    #    ##     #####  #####      #    #    #
 #        #    ##   #  #    #      ##  ##   #  #      #    #    #     #     #  #
 #####    #    # #  #  #    #      # ## #  #    #     #    #    #     #      ##
 #        #    #  # #  #    #      #    #  ######     #    #####      #      ##
 #        #    #   ##  #    #      #    #  #    #     #    #   #      #     #  #
 #        #    #    #  #####       #    #  #    #     #    #    #     #    #    #

####################################################################################
#
#   Criteria:
#	1)  must have .mat extension
#	2)  must contain a unitary U matrix
#	3)  must contain a valid unit cell
#	
#   Precedence:
#	1)  matrix file on command line
#	2)  matrix files found in directories given on command line
#	3)  "best.mat"
#	4)  matrix indicated in scripts listed on command line
#	5)  matrix found in directories indicated in scripts on command line
#	6)  matrix found in directories indicated in scripts found in filesystem
#	7)  matrix found in filesystem
#	8)  matrix extracted from denzo ".x" files
#
####################################################################################

# look at command line (and defaults) for matrix files
foreach arg ( $* )

    # ignore matricies known to be bad
    if("$arg" =~ -*) set arg = ""
    foreach bad ( $badmatrix )
	if("$arg" == "$bad") set arg = ""
    end

    # collect promising filenames
    if(("$arg" =~ *.mat)&&(-e "$arg")) then
	# add candidate matrix
	set matrixfiles = "$matrixfiles $arg"
    endif

    if("$arg" != "") then
	# see if arg was a directory
	set dir = `ls -lnLd $arg |& nawk '/^d/{print $NF}'`
	if((-e "$dir")&&(! $?NEW)) then
	    # we have a directory to search!
	    set temp = `ls -lnLtp $dir |& egrep '\.mat$' |& nawk -v dir=$dir '/^\-/ && $5+0 > 300 && $5+0 < 400 {print dir "/" $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	    foreach mat ( $temp )
		if(-e "$mat") then
		    set mat = `echo $mat |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`
		    set matrixfiles = "$matrixfiles $mat"
		endif
	    end
	endif
    endif
end

# now collect a list of potential matricies from script files found
foreach file ( $oldscripts  )

    if(-e "$file") then
	# get matrix file name from script
	set temp = `egrep "^MATR" $file |& nawk '{print $2}' |& tail -1`
	if($#temp == 1) then
	    if(-e "$temp") set matrixfiles = "$matrixfiles $temp"
	endif
	
	# extract mosflm matrix from denzo files
	# (check determinant first)
	head -5 $file |& nawk 'NR>1 && NF == 6{printf "%12.8f%12.8f%12.8f\n", $4, $5, $6}' |& \
	nawk 'NR < 4{i=NR; for(j=1;j<4;++j){mat[i,j]=$j+0}}     \
	END{det += mat[1,1]*((mat[2,2]*mat[3,3])-(mat[2,3]*mat[3,2]))  \
	    det -= mat[1,2]*((mat[2,1]*mat[3,3])-(mat[2,3]*mat[3,1]))  \
	    det += mat[1,3]*((mat[2,1]*mat[3,2])-(mat[2,2]*mat[3,1]))  \
	    printf "%.4f", det}' >&! ${tempfile}.determinant
	set temp = `cat ${tempfile}.determinant`
	rm -f ${tempfile}.determinant >& /dev/null

	# if determinant is unitary, then we almost certainly have an orientation matrix
	if( "$temp" == "1.0000" ) then
	    # store the .x file name in precedence list
	    set set matrixfiles = "$matrixfiles $file"
	endif
    endif
end

# more agressive command-line search
foreach arg ( $* )
    # see if arg contained a directory
    set dir = `dirname $arg |& nawk '$0 != "."'`
    # use directory name of the arg
    if((-e "$dir")&&(! $?NEW)) then
	# we have a directory to search!
	set temp = `ls -lnLtp $dir |& egrep '\.mat$' |& nawk -v dir=$dir '/^\-/ && $5+0 > 300 && $5+0 < 400 {print dir "/" $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	foreach mat ( $temp )
	    if(-e "$mat") then
		set mat = `echo $mat |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`
		set matrixfiles = "$matrixfiles $mat"
	    endif
	end
    endif
end

# add default to the list (if appropriate)
if((-e "$best_matrix")&&(! $?NEW)) set  matrixfiles = "$matrixfiles $best_matrix"

CheckMATRIX:
# now check the precedence-sorted list for REAL matricies
foreach mat ( $matrixfiles )
    if(( -e "$mat")&&(! -e "$inmatrix")&&("$mat" !~ *.mat)) then
	# must have been a script file
	set file = "$mat"

	# redefine new matrix file name
	set temp = `basename $file .x`
	set mat = "${temp}.mat"
	if(-e "$mat") mv $mat ${mat}.old
	    
	# extract the unitary matrix
#	head -5 $file |& nawk 'NR>1 && NF == 6{printf "%12.8f%12.8f%12.8f\n", $4, $5, $6}' >! ${temp}.umat

	# convert denzo to york (if need be)
	cp $file ${tempfile}.x
	grep HEADER $file >& /dev/null
	if($status) then
	    echo "HEADER     1" >! ${tempfile}.x
	    head -10 $file >> ${tempfile}.x
	endif
	
	# use rotaprep logfile output to get mosflm matrix
	echo "" | nawk '{print "INPUT DENZO"; print "SYMM 1"; print "RESO 9"; print "END"}' |\
	rotaprep HKLIN ${tempfile}.x HKLOUT /dev/null |&\
	nawk '/Mosflm umat matrix/{getline; getline; getline; getline;\
	    getline; printf "%12.8f%12.8f%12.8f\n", $1, $2, $3; \
	    getline; printf "%12.8f%12.8f%12.8f\n", $1, $2, $3; \
	    getline; printf "%12.8f%12.8f%12.8f\n", $1, $2, $3}'|\
	cat >&! ${tempfile}.umat
	rm -f ${tempfile}.x >& /dev/null
	
	# quick check for validity
	set temp = `cat ${tempfile}.umat | nawk '$1+$2+$3 != 0' | wc -l`
	if("$temp" != 3) then
	    echo "bad matrix in $file"
	else
	    # using the U matrix here doesn't seem to hurt preds
	    cat ${tempfile}.umat 					    >! $mat
	    # missetting angles are zero
	    nawk 'BEGIN{printf "%12.3f%12.3f%12.3f\n", 0, 0, 0}'	    >> $mat
	    # U matrix goes here
	    cat ${tempfile}.umat					    >> $mat
	    # put the cell here...
	    nawk 'toupper($0) ~ /CELL/{for(i=1;i<=NF;++i){if($i ~ /[0-9]/)\
	       printf "%12.4f",$i}} END{print ""}'		     $file  >> $mat
	    # missetting angles are zero
	    nawk 'BEGIN{printf "%12.4f%12.4f%12.4f\n", 0, 0, 0}'	    >> $mat
	    
	    # inform user we created a new file
	    echo "extracted $mat from $file "

	endif
	rm -f ${tempfile}.umat >& /dev/null
	
	# now go on and check this new matrix in the usual way ...
    endif
    
    if(( -e "$mat")&&(! -e "$inmatrix")) then
	# compute determinant of U matrix (mosflm is sensitive to this)
	cat "$mat" |\
	nawk 'NR==5,NR==7{i=NR-4; for(j=1;j<4;++j){mat[i,j]=$j+0}}     \
	END{det += mat[1,1]*((mat[2,2]*mat[3,3])-(mat[2,3]*mat[3,2]))  \
	    det -= mat[1,2]*((mat[2,1]*mat[3,3])-(mat[2,3]*mat[3,1]))  \
	    det += mat[1,3]*((mat[2,1]*mat[3,2])-(mat[2,2]*mat[3,1]))  \
	    printf "%.4f", det}' >&! $tempfile
	set det = `cat $tempfile`
	rm -f $tempfile >& /dev/null
	
	# make sure matrix has a unit cell
	set cell = `nawk 'NF==6' $mat`
	
	if(($#cell == 6)&&("$det" == "1.0000")) then
	    set inmatrix = "$mat"
	else
	    echo "WARNING: $mat is not a valid matrix ... ignoring it."
	    set badmatrix = `echo $badmatrix $mat`
	    set inmatrix = ""
	endif
    endif
end

if(-e "$inmatrix") then
    # stop screwing around, and skip ahead
    goto MatrixFound
else
    # no luck with these
    set badmatrix = `echo $badmatrix $matrixfiles`
    set matrixfiles = ""
endif

if(($?NEW)||(! $?SEARCH_HARD)) goto Initialize

# if we still don't have a "good" matrix, look around for one
echo -n "Looking for an orientation matrix "
if(! $?AUTO) then
    echo -n "(Ctrl-C to skip) "
    onintr SkipMatrixSearch
endif

# look down a list of standard places for matricies
set places = `ls -1dt ../*/ ../../*/*/ `
foreach place ( ./ ../ ../../ $places )

    if((-e $place)&&(! -e "$inmatrix")) then
	# first, look for matrix files of predefined name
	set temp = `ls -1t ${place}$best_matrix |& nawk 'NF==1'`
	# and then look for just any matrix file
	set temp = "$temp "`ls -1t ${place} |& nawk -v dir=$place 'NF==1 && /.mat$/ {print dir $0}' |& grep -v $best_matrix |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`

	foreach mat ( $temp )
	    # ignore matricies known to be bad
	    foreach bad ( $badmatrix )
		if("$mat" == "$bad") set mat = ""
	    end

	    if(($#mat == 1)&&(-e "$mat")&&(! -e "$inmatrix")) then
		# compute determinant of U matrix (mosflm is sensitive to this)
		cat "$mat" |\
		nawk 'NR==5,NR==7{i=NR-4; for(j=1;j<4;++j){mat[i,j]=$j+0}}     \
		END{det += mat[1,1]*((mat[2,2]*mat[3,3])-(mat[2,3]*mat[3,2]))  \
		    det -= mat[1,2]*((mat[2,1]*mat[3,3])-(mat[2,3]*mat[3,1]))  \
		    det += mat[1,3]*((mat[2,1]*mat[3,2])-(mat[2,2]*mat[3,1]))  \
		    printf "%.4f", det}' >&! $tempfile
		set det = `cat $tempfile`
		rm -f $tempfile >& /dev/null
	
		# make sure matrix has a unit cell
		set cell = `nawk 'NF==6' $mat`
	
		if(($#cell == 6)&&("$det" == "1.0000")) then
		    set inmatrix = "$mat"
		else
		    set badmatrix = `echo $badmatrix $mat`
		endif
	    endif
	end
	
	# keep user entertained
	echo -n "."
    endif
end
SkipMatrixSearch:
onintr

if(-e "$inmatrix") then
    echo " found $inmatrix"
else
    echo " none found."
    set inmatrix = "$best_matrix"
endif

MatrixFound:


################################################################################################################
#
#   First pass through filesystem complete.
#
#	All data files should now be located,  and we need to use 
#	them to initialize program variables.
#
################################################################################################################




Initialize:
###########################################################################

    #    #    #     #   #####   #      ##    #        #    ######  ######
    #    ##   #     #     #     #     #  #   #        #        #   #
    #    # #  #     #     #     #    #    #  #        #       #    #####
    #    #  # #     #     #     #    ######  #        #      #     #
    #    #   ##     #     #     #    #    #  #        #     #      #
    #    #    #     #     #     #    #    #  ######   #    ######  ######

###########################################################################
#
#   Initialize variable values from old scripts. logs, frames, and the matrix, 
#   in order of precedence/age
#
###########################################################################
#
#
# check oldscripts, just to be sure all files exist
set oldscripts = `echo $oldscripts`
#if(("$oldscripts" != "")&&(! $?NEW)) then
if("$oldscripts" != "") then
    set temp = ""
    foreach file ( $oldscripts )
	head -1 $file >> /dev/null
	if(! $status) set temp = "$temp $file"
#	if(-e $file) set temp = "$temp $file"
    end
    set oldscripts = `echo "$temp"`

    # pick a representative oldscript from the bunch
    set oldscript = `ls -1t $oldscripts |& head -1`
else
    set oldscript = ""
endif

set sources = ""

#check that all source files exist, and are readable
foreach file ( $FirstImage $inmatrix $oldscript $lastlog )
    head -1 $file >& /dev/null
    if(! $status) set sources = "$sources $file"
end

# sort source files by date
set sources = `echo $sources`
if("$sources" != "") then
    set sources = `ls -1dt $sources`
endif

# now replace representative oldscript with entire list of oldscripts
set temp = ""
foreach file ( $sources )
    if("$file" == "$oldscript") then
	set temp = "$temp $oldscripts"
    else
	set temp = "$temp $file"
    endif
end
set sources = "$temp"

# if -new was specified, ignore the old scripts (above)
#if($?NEW) then
#    set sources = "$user_sources $FirstImage $inmatrix"
#endif

# now move command-line args to the "top" of the list
echo "$sources" | nawk 'BEGIN{RS=" "} {print}' >! ${tempfile}.sources
echo "" >! ${tempfile}.args
echo "" >! ${tempfile}
foreach arg ( $* )
    egrep "^$arg" ${tempfile}.sources >> ${tempfile}.args
    egrep -v "^$arg" ${tempfile}.sources >> ${tempfile}
    mv ${tempfile} ${tempfile}.sources
end
set sources = `cat ${tempfile}.args ${tempfile}.sources`
rm -f ${tempfile}.args ${tempfile}.sources >& /dev/null

echo ""
goto GetParamsFromSources
# See end of this file for source code
ReturnGetParamsFromSources:
echo ""


CommandLine:
###############################################################################
#
#   Take other (refinement) options given on command line   (highest precedence)
#
###############################################################################
# look for valid unit cell on command line
set i = 1
set j = 1
set newCELL = ""
while ( $i <= $#argv )
    # look for any words containing "cell"
    if("$argv[$i]" =~ *[Cc][Ee][Ll][Ll]*) then
	# see if there is a valid cell after this word
	set k = 1
	while(( $k <= 6 )&&( $j <= $#argv))
	    @ j = ( $i + $k )
	    
	    # safety catch
	    if($j > $#argv) break
	    
	    # check for number > 10
	    set temp = `echo "$argv[$j]" | nawk '$1+0 > 10{print $1+0}'`
	    if("$temp" == "") then
		# all bets are off
		set newCELL = ""
		set k = 10
	    else
		# add this parameter to the cell
		set newCELL = "$newCELL $temp"
	    endif
	    
	    # increment offset from "cell" word
	    @ k = ( $k + 1 )
	end
	
	# see if we got all six
	set newCELL = `echo $newCELL`
	if($#newCELL == 6) then
	    # this cell was valid
	    set CELL = `echo $newCELL`
	    # erase the arguments (as not to confuse them with frame counts)
	    set k = 1
	    while(( $k <= 6 )&&( $j <= $#argv))
		@ j = ( $i + $k )
		set argv[$j] = ""
		@ k = ( $k + 1 )
	    end
	endif
    endif
    @ i = ( $i + 1 )
end

# now look for other (less complex) options
set i = 0
while( $i < $#argv )
    @ i = ( $i + 1 )
    @ nexti = ( $i + 1 )
    @ lasti = ( $i - 1 )
    if($nexti > $#argv) set nexti = $#argv
    if($lasti < 1) set lasti = 1
    set arg = "$argv[$i]"
    set ARG = `echo "$arg" | nawk '{print toupper($1)}'`
    
    if("$ARG" =~ [PCIFHR][1-6]*) then
	set SG = "$ARG"
	set SG_choice = user
    endif
#    if("$arg" == "usebeam")	set usebeam   = yes
#    if("$arg" == "nousebeam")	set usebeam   = no
    if("$arg" =~ fixmo*)        set fixmosaicity = yes
    if("$arg" =~ nofixmo*)      set fixmosaicity = no
    if("$arg" =~ fixc*)		set fixcell   = yes
    if("$arg" =~ nofixc*)	set fixcell   = no
    if("$arg" =~ fixc*)		set true_cell = yes
    if("$arg" =~ nofixc*)	set true_cell = no
    if("$arg" =~ fixy*)		set fixyscale = yes
    if("$arg" =~ nofixy*)	set fixyscale = no
    if("$arg" =~ fixx*)		set fixyscale = yes
    if("$arg" =~ nofixx*)	set fixyscale = no
    if("$arg" =~ postre*)	set postref   = yes
    if("$arg" =~ nopostre*)	set postref   = no
    if("$arg" =~ refi*)		set postref   = yes
    if("$arg" =~ norefi*)	set postref   = no
    if("$arg" =~ integ*)	set integrate = yes
    if("$arg" =~ nointeg*)	set integrate = no
    if("$arg" =~ nostrat*)	set strategize = no
    if("$arg" =~ nomerge*)	set NOSCALE
    if("$arg" =~ nosear*)	set NEW

#    if("$arg" == "-usebeam")	set usebeam   = yes
#    if("$arg" == "-nousebeam")	set usebeam   = no
    if("$arg" =~ "-"fixmo*)     set fixmosaicity = yes
    if("$arg" =~ "-"nofixmo*)   set fixmosaicity = no
    if("$arg" =~ "-"fixc*)	set fixcell   = yes
    if("$arg" =~ "-"nofixc*)	set fixcell   = no
    if("$arg" =~ "-"fixc*)	set true_cell = yes
    if("$arg" =~ "-"nofixc*)	set true_cell = no
    if("$arg" =~ "-"fixy*)	set fixyscale = yes
    if("$arg" =~ "-"nofixy*)	set fixyscale = no
    if("$arg" =~ "-"fixx*)	set fixyscale = yes
    if("$arg" =~ "-"nofixx*)	set fixyscale = no
    if("$arg" =~ "-"postre*)	set postref   = yes
    if("$arg" =~ "-"nopostre*)	set postref   = no
    if("$arg" =~ "-"refi*)	set postref   = yes
    if("$arg" =~ "-"norefi*)	set postref   = no
    if("$arg" =~ "-"integ*)	set integrate = yes
    if("$arg" =~ "-"nointeg*)	set integrate = no
    if("$arg" =~ "-"nostrat*)	set strategize = no
    if("$arg" =~ "-"nomerge*)	set NOSCALE
    if("$arg" =~ "-"nosear*)	set NEW

    if("$arg" == "-nice") then
	renice 40 $$ >& /dev/null
	if($status) renice -n 40 $$ >& /dev/null
	continue
    endif
    if(("$arg" == "-add")&&( $i < $#argv )) then
	set add = $argv[$nexti]
	@ i = ($i + 1)
	continue
    endif

    # look for "no" preceding an option (opposite meaning)
    if($?NO) then
#	if("$arg" == "usebeam")	set usebeam   = no
        if("$arg" =~ fixmo*)    set fixmosaicity = no
	if("$arg" =~ fixc*)	set fixcell   = no
	if("$arg" =~ fixc*)	set true_cell = no
	if("$arg" =~ fixy*)	set fixyscale = no
	if("$arg" =~ fixx*)	set fixyscale = no
	if("$arg" =~ postre*)	set postref   = no
	if("$arg" =~ integ*)	set integrate = no
	if("$arg" =~ strat*)	set strategize = no
	if("$arg" =~ sear*)	set NEW
	unset NO
	continue
    endif

    # assume args begginning with numbers are numbers
    if("$arg" =~ [0-9]*) then
	# we have a number
	if(("$arg" =~ *A)||("$argv[$nexti]" == "A")) then
	    # user-preferred resolution limits
	    set temp = `echo "$arg" | nawk 'BEGIN{FS="-"} $1+0 > 0.1{print $1+0} $2+0 > 0.1{print $2+0}'`
	    if($#temp != 1) then
		set temp = `echo $temp | nawk '$1>$2{print $1, $2} $2>$1{print $2, $1}'`
		if($#temp == 2) then
		    # a range 3-10A is a resolution
		    set hires = `echo "$temp[2]" | nawk '{print $1+0}'`
		    set lores = `echo "$temp[1]" | nawk '{print $1+0}'`
		    set res_choice = user
		    continue
		endif
	    else
		# single 1.8A is just high resolution
		set hires = `echo "$arg" | nawk '{print $1+0}'`
		set res_choice = user
		continue
	    endif
	endif
	
	if(("$arg" =~ [1-9][0-9]*aa)&&("$arg" !~ *[b-z,A-Z]*)) then
	    # this is probably a number of amino acids
	    set Chain = `echo $arg | nawk '{print $1+0}'`
	endif
	# interpret free integers as number of frames?
	set int = `echo "$arg" | nawk '{printf "%d", $1+0}'`
	if(("$arg" == "$int")&&(("$argv[$nexti]" == "frame")||("$argv[$nexti]" == "frames"))) then
	    set number_of_frames = "$arg"
	    set USER_WEDGE_SIZE = "$arg"
	endif
    endif
    
    unset NO
    if("$ARG" == NO) set NO
    if("$ARG" == NOT) set NO
end

# if this is, indeed the first time through, we probably just 
# want to postrefine
if($?NEW) set postref = yes

# don't integrate in the first round of burstmode, or it will be the last! 
if(($?BURSTMODE)&&(! $?LAST_RUN)&&(! $?Convergeing)) set integrate = no









# process command-line through the Questionaire

#set input = "$*"
#if("$input" != "") goto Questionaire
# Questionaire should return to ProcessInput

ProcessInput:
###############################################################################

  ####   #    #  ######   ####   #    #            ##    #       #
 #    #  #    #  #       #    #  #   #            #  #   #       #
 #       ######  #####   #       ####            #    #  #       #
 #       #    #  #       #       #  #            ######  #       #
 #    #  #    #  #       #    #  #   #           #    #  #       #
  ####   #    #  ######   ####   #    #          #    #  ######  ######

###############################################################################
#
#   At this point, all variable values have been read in.
#
#   Input Numbers are not, necesarrily valid or in the right form.  Check each 
#   one, and convert it to something useful to Wedger Elves.
#
###############################################################################

# if you're not integrating, you're postrefining
if($?NEW) set integrate = no
if($integrate == no) set postref = yes
# see if we don't want postrefinement during integration
set test = `echo "$PREAMBLE" | nawk 'BEGIN{RS="n"} {print}' | grep "POSTREF OFF"`
if("$test" != "" && $integrate == yes) then
    set postref = no
endif

# output script should be in local directory
set scriptname = `basename $scriptname`


# oblige user-specified number of frames (check it later)
if($number_of_frames != "") @ last = ($first + $number_of_frames - 1 )


# decide on a unique "add" value to differentiate this wedge from others
if($add == "auto") then

    # reduce starting phi to range [0, 360]
    set temp = `echo $phi0 | nawk '{print ($1 + 360*int(1+ sqrt($1*$1)/360)) % 360}' | nawk '{print int($1)}'`

    # assume phi values > 180 are inverse beam wedges
    if($temp >= 180) then
	# see if we can fit two wedges in three digits
	if((2 * ($last + 1)) / 1000) then
	    set add = 1000
	else
	    # can squeeze two I.B. wedges in same 3-digit space
	    set add = 500
	endif
    else
	# not inverse beam, so no offset
	set add = 0
    endif

    # now add 1000 * ( run number - 1)

    # filter last whole number out of filename prefix
    set temp = `echo $frameprefix | nawk '{for(i=1;i<=length($1);++i){c=substr($1,i,1); if(c ~ /[0-9]/){printf c}else{printf " "}}}'`
    set temp = $temp[$#temp]

    # if run number is given, use it as a guide
    if($temp != "") then
	
	# remove all but last digit (because batch numbers > 9999 interfere with scala)
	@ temp = ( $temp % 10 )
	
	# add "additional" offset to batch numbers
	@ add = ( $add + (($temp - 1) * 1000))
    endif
endif

#
# convert beam center from foreign formats
set beam_center = ( $beam_center )
if($#beam_center != 2) then
    # beam center should ALWAYS be there! but just in case
    set beam_center = "97.2 97.2"
    echo "WARNING: Beam center arbitrarily set to: $beam_center ! "
    echo "         This is probably completely wrong."

    # mosflm X is ( frame width) - (ADXV's Y)
#    set beam_center = `echo "188 - $temp[2]" | bc`
    # mosflm Y is ADXV's X
#    set beam_center = `echo $beam_center $temp[1]`
endif

#
###############################################################################
# make sure CCP4, etc. is set up
#
###############################################################################

if((! $?CLIBD)||(! $?CCP4_SCR)||(! $?CINCL)) then
    onintr Skip_CCP4_search

    echo -n "Trying to set up CCP4 ." 

    set ccp4setup = ""
    foreach place ( /programs/xtal/ccp4_3.4/ /usr/xtal/CCP4_v3.4/ /programs/xtal /sw/ /programs/ /usr/xtal /usr/local /usr/ )
	if((! -e "$ccp4setup")&&(-e $place)) then
	    echo -n "."
	    # look for setup scripts here
	    set ccp4setup = `find ${place} -name ccp4.setup -print |& nawk '/ccp4.setup$/{print $NF}' | tail -1`
	endif
        if((-e "$ccp4setup")&&((! $?CLIBD)||(! $?CCP4_SCR)||(! $?CINCL))) then
            source $ccp4setup
            setenv CCP4_SCR    .
            setenv BINSORT_SCR .
	    setenv CCP4_OPEN UNKNOWN
            echo "using $ccp4setup"
        endif
    end
endif

Skip_CCP4_search:
onintr
echo ""
if((! $?CLIBD)||(! $?CCP4_SCR)||(! $?CINCL)) then
    set NO_CCP4

    cat << EOF
failed.
Wedger Elves (and mosflm) need CCP4 to run properly.
Please ask your sysadmin how to set up CCP4, or go to

netscape ftp://ccp4a.dl.ac.uk/pub/ccp4/

to get yourself a copy.  Unfortunately, you'll have to compile it. 

If, however, you have Red Hat linux, you can get an RPM from the O people at:
netscape http://origo.imsb.au.dk/~mok/linux/dist/

In the meantime, Wedger Elves can limp along without CCP4, 
but they won't be able to scale and merge your data.

EOF

    set NOSCALE
    # do half-assed setup
    setenv CCP4_SCR .
    setenv BINSORT_SCR .
    setenv CLIBD    .
    setenv CINCL    .
    
    # make some band-aid files
    goto DumpSymopLib
    # create ${CLIBD}/symop.lib
    # create ${CINCL}/environ.def
    # create ${CINCL}/default.def
    ReturnFrom_DumpSymopLib:

endif
setenv CCP4_OPEN UNKNOWN

# chech that we can actually write to scratch directories
touch ${CCP4_SCR}/.this$$ >& /dev/null
if($status) then
    echo "WARNING: "'$'"CCP4_SCR=$CCP4_SCR is not accessible.  using cwd instead."
    setenv CCP4_SCR .
endif
rm -f ${CCP4_SCR}/.this$$ >& /dev/null
touch ${BINSORT_SCR}/.this$$ >& /dev/null
if($status) then
    echo "WARNING: "'$'"BINSORT_SCR=$BINSORT_SCR is not accessible.  using cwd instead."
    setenv BINSORT_SCR .
endif
rm -f ${BINSORT_SCR}/.this$$ >& /dev/null


# check free disk space
set freespace = `df -k $CCP4_SCR |& nawk 'NR>=2&&NF>2{avl=NF-2;print $avl/1024}'`
set test = `echo $freespace 100 | nawk '{print ($1<$2)}'`
if($test) echo "WARNING: "'$'"CCP4_SCR is getting full!  ${freespace}MB left. "
set freespace = `df -k $BINSORT_SCR |& nawk 'NR>=2&&NF>2{avl=NF-2;print $avl/1024}'`
set test = `echo $freespace 100 | nawk '{print ($1<$2)}'`
if($test) echo "WARNING: "'$'"BINSORT_SCR is getting full!  ${freespace}MB left."
set freespace = `df -k . |& nawk 'NR>=2&&NF>2{avl=NF-2;print $avl/1024}'`
set test = `echo $freespace 100 | nawk '{print ($1<$2)}'`
if($test) echo "WARNING: disk space is getting low! ${freespace}MB left. "


###############################################################################
# now look for ipmosflm executable
#
###############################################################################
#if((! -e "$MOSFLM")&&(! $?NORUN)) then
#if(! $?NORUN) then
#if(! -e "$MOSFLM") then
if("$MosflmVersion" == "") then
    # set minor variable to see if executable comes back different
    set mosflm = $MOSFLM
    goto FindMOSFLM
endif

ReturnFindMOSFLM:
# a working executable should be in $mosflm, or a blank
if("$MosflmVersion" =~ [1-9]*) then
    if((-e "$mosflm")&&("$mosflm" != "$MOSFLM")) then
        echo "found $mosflm" 
        set MOSFLM = $mosflm
    endif
else
    # no mosflm found
    set NOMOSFLM
    set NORUN
endif
#
#
###############################################################################
# Check preamble cards
#
###############################################################################
# can't really check cards if there is no mosflm to chech them with
if((! $?NOMOSFLM)&&("$PREAMBLE" != "")) then

    set safety = 0
    echo "$PREAMBLE" | nawk 'BEGIN{RS="n"} {print}' >! ${tempfile}.preamble
    CheckPREAMBLE:
    # safety catch, in case bad cards can't be removed
    @ safety = ( $safety + 1 )
    if($safety == 20) goto BAD_PREAMBLE

    # run mosflm with these cards
    cat ${tempfile}.preamble | $MOSFLM SUMMARY /dev/null |& head -300 >&! $tempfile

    tail -1 $tempfile |& grep "END OF PROCESSING" >& /dev/null
    if($status) then
	# mosflm choked on a card
	set bad_card = `tail -2 $tempfile | nawk '/ ===> /{print substr($0,7)}'`

	# remove this card from the preamble
	nawk -v bad="$bad_card" 'bad != $0' ${tempfile}.preamble >! $tempfile
	# catch failure to remove a card
	set temp = `diff $tempfile ${tempfile}.preamble | wc -l`

	if("$temp" == 0) goto BAD_PREAMBLE
	
	# check again

	mv ${tempfile} ${tempfile}.preamble
	goto CheckPREAMBLE
    else
	rm -f ${tempfile} >& /dev/null
	goto GOOD_PREAMBLE
    endif
    
BAD_PREAMBLE:
    # just comment everything out
    echo "WARNING: one or more of these keywords is making Mosflm unhappy:"
    cat ${tempfile}.preamble
    echo "They will all be commented out in $scriptname $BELL "
    nawk 'BEGIN{RS="n"} {print "#", $0}' ${tempfile}.preamble >! ${tempfile}
    mv ${tempfile} ${tempfile}.preamble
    
GOOD_PREAMBLE:
    # reimport preamble file into a variable (check it later)
    set PREAMBLE = `nawk 'BEGIN{ORS="n"} NF != 0' ${tempfile}.preamble`
    rm -f ${tempfile}.preamble
endif


###############################################################################
# forgot to update matrix file? 
#
###############################################################################
#if((-e "$outmatrix")&&($?AUTO || $?Convergeing)&&($last_changed != failure)) then
if((-e "$outmatrix")&&(! $?NEW)&&("$inmatrix" != "")&&("$last_changed" != "failure")) then
    # maybe forgot to do this earlier? 
    set temp = "Yes"
    echo "$outmatrix found.  Move it to ${best_matrix}? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo $temp
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	# go ahead and update matrix
	mv $best_matrix ${best_matrix}.old >& /dev/null
	mv $outmatrix $best_matrix
	set inmatrix = $best_matrix
    endif
    if(-e "$outmatrix") then
	# didn't move new matrix, get rid of it? 
	set temp = "Yes"
	echo "remove ${outmatrix}? [$temp]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $temp
	else
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	endif
	if("$temp" =~ [Yy]*) then
	    # don't ask next time
	    rm -f $outmatrix
	endif
    endif
endif

# have new frames appeared?
#if(($?Convergeing)&&(! $?NO_EXTEND)) then
if((! $?NO_EXTEND)&&(-e "$scriptname")) then

    # look for frames consecutive to the "last" frame of this run
    set offset = `echo "$template" | nawk '{print index($1,"\043")}'`
    ls -1Lrt $framedir | egrep "^${framepattern}" |\
    nawk -v last=$last -v offset=$offset '{num=substr($1,offset)+0} \
	num==last+1{++last; printf "%d %s\n", last, $1;}' |\
    tail -1 >! ${tempfile}
    set newframe = `nawk '{print $NF}' ${tempfile}`
    set newlast  = `nawk '{print $1}' ${tempfile}`
    rm -f ${tempfile}

    if("$newframe" != "" && $?USER_WEDGE_SIZE) then
	@ test = (( $newlast - $first ) + 1 )
	if($test < $USER_WEDGE_SIZE) then
	    # this is within the number of frames the user originally specified
	    echo "extending wedge to ${framedir}/$newframe"
	    set last = $newlast
	    @ number_of_frames = (( $last - $first ) + 1 )
	    unset LAST_RUN
	    unset SMOOTH_RUNS
	    set mosflm_postref_segs = "auto"
	    set frames_per_segment  = "auto"
	    # don't bother with asking
	    set newframe = ""
	endif
    endif

    # see if there was a "new" frame
    if("$newframe" != "") then
	# see if it is newer than the script we just ran
	set temp = `ls -1Lrt $scriptname ${framedir}/$newframe | tail -1`
	if("$temp" != "$scriptname") then
	    # a new frame has appeared (potentially in this wedge)
	    echo "${framedir}/$newframe has appeared."
	    set temp = "Yes"
	    #if($?USER_WEDGE_SIZE) set temp = "No"
	    echo "Shall we extend the wedge to ${newframe}? [$temp]"
	    echo -n "$PROMPT"
	    if($?AUTO) then
		echo "$temp"
	    else
		echo -n "$BELL"
		set in = ( $< )
		if("$in" != "") set temp = ( $in )
	    endif
	    if("$temp" =~ [Yy]*) then
		# update the wedge size
		set last = $newlast
		@ number_of_frames = (( $last - $first ) + 1 )
		unset LAST_RUN
		unset SMOOTH_RUNS
		set mosflm_postref_segs = "auto"
		set frames_per_segment  = "auto"
	    else
		# don't ask about this again
		set NO_EXTEND
	    endif
	endif
    endif 
endif

# speed things up a bit? 
if(($?Convergeing)||("$check_frames" == "no")) goto CheckSegments

CheckWedge:
###############################################################################
# check that all the frames are there, and have consecutive phis
# if not, remove them from the processing list
#
###############################################################################
set number = $last
set savelast = $last

# This can take a while, tell user what we are doing
echo -n "Checking frames "

# Ctrl-C breaks out of frame check
if(! $?AUTO) then
    onintr SkipCheckWedge
    echo -n "(Ctrl-C to skip) "
endif

# check for existence of files
while($number >= $first)

    # generate the expected filename
    set img = `echo "$framedir/$template $number" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
    
    # check that it is readable
    test -r $img >& /dev/null
    if($status) then
	echo ""
	@ last = ($number - 1)
    endif
    
    # check if it even exists
    if(! -e "$img" ) then
	echo ""
        echo "WARNING: $img does not exist"
        @ last = ($number - 1)
    endif
    
    @ number = ($number - 1)
end

#check phi, distance, etc. on images we can read
set number = $first
set next_phi = $phi0
set step = $osc
while($number <= $last)

    # for entertainment purposes only
    echo -n "."

    # generate the expected filename
    set img = `echo "$framedir/$template $number" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
    
    set phi = ""
    if("$SCANNER" =~ *ADSC* || "$SCANNER" =~ *SBC*) then
	set phi = `nawk 'BEGIN{RS="\f"} {print;exit}' $img | egrep "PHI|ROTATION_START" | nawk -F "=" '{ print $2+0}'`
    endif
    if($?RAXIS_SMV) then
	set phi = `nawk 'BEGIN{RS="\f"} {print;exit}' $img | egrep "^ROTATION=" | nawk -F "=" '{print $2+0; exit}'`
    endif
    if(("$SCANNER" =~ *RAXIS*)&&("$swap" != "")&&(! $?RAXIS_SMV)) then
	# get phi value from header
	od -vb -j 524 -N 4 $img |\
	nawk '{for(i=2;i<=5;++i){printf "%d ", 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)};exit}' |\
	nawk '{w=x=$2} $1+$2+$3+$4==0{--w;++x} {print $0, w,x-1}' |\
	nawk '{printf "%c%c%c%c", '$swap'}' | ood -f |\
	nawk '{print $2+0;exit}' |\
	cat >! ${tempfile}phi
	set temp = `nawk '$1>-370 && $1<800 {print $1;exit}' ${tempfile}phi`
	rm -f ${tempfile}phi >& /dev/null	
	if("$temp" != "") set phi = $temp
    endif
    if("$ext" =~ mar*) then
	set phi = `head -56 $img | nawk '/^PHI/{print}' | nawk 'BEGIN{RS=" "} /START/{getline; print $0+0}'`
    endif
    
    # check MARCCD header?
    if("$SCANNER" =~ *MARCCD*) then
	od -bv -j 1024 -N 1024 $img |\
	nawk '{for(i=2;i<=NF;++i){print 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)}}' |\
	nawk 'NR%4==1{printf "\n%d ", NR+1023} {printf "%d ", $1}' |\
	nawk '/^1052 210 4 0 0/{little=1} /^1052 0 0 20 341/{big=1} \
	     little{print $1, $2+256*($3+256*($4+256*$5))} \
	        big{print $1, $5+256*($4+256*($3+256*$2))}' |\
	nawk '/^1708 /{ print $2/1000}' |\
	cat >! ${tempfile}phi
	set temp = `nawk '$1>-370 && $1<800 {print $1;exit}' ${tempfile}phi`
	rm -f ${tempfile}phi >& /dev/null	
	if("$temp" != "") set phi = $temp
    endif
    
    # defeat check if headers are just unreadable
    if("$phi" == "") then
	set phi = $phi0
	set step = 0
    endif
    
    # reset "phi0" value to that of first image (bug workaround)
    if(("$img" == "$FirstImage")&&("$phi" != "$phi0")) then
	echo "WARNING: resetting phi0 to $phi (from first frame)"
	set phi0 = $phi
	set next_phi = $phi
    endif

    set temp = `echo "$phi $next_phi" | nawk '{printf "%.2f", ((($1 - $2)*1000 + 36180000) % 360000)/1000}'`
    if("$temp" != "180.00") then
	echo ""
	echo "WARNING: $img phi value: $phi is out of sequence."
	@ last = ($number - 1)
	echo "   $next_phi expected."
#	echo "   will only process to frame $last"
    endif

    set next_phi = `echo "$phi $step" | nawk '{print $1+$2}'`
    
    @ number = ($number + 1)
end
echo ""

# reset Ctrl-C catch to normal
onintr

@ temp = (($last - $first) + 1 )
if(($last < $savelast)&&($temp > 1)) then
    echo "Only $temp frames are available."
endif
#if(($temp <= 1)&&(! $?NORUN)&&(! $?autoindexing)) then
if(0) then
    echo "There are not enough frames for a processing run $BELL"
    echo "    (mosflm cannot postrefine just one frame) ... "
    # turn POSTREF off?
    set postref = "no"

    # maybe just want to index? 
    set temp = "Yes"
    if($?AUTO) set temp = "No"
    echo "Do you just want to index ${FirstImage}? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo $temp
	
	# Wedger has no business looking for more frames now
	echo "Agressive image searching will not be done in automatic mode."
	echo ""
	echo "please run: $0 directory/name_001.$ext"
	echo "where directory/name_001.$ext is the first x-ray image"
	echo "in a multi-image wedge."
	echo "Later! "
	set mosflm_status = 100
	goto Cleanup
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	# skip ahead to indexing
	set autoindexing
	set NORUN
	goto autoindex
    endif
    # user says this frame is useless
    set bad_frames = "$bad_frames ${FirstImage}"

    # get the "next" image in this directory
    set img = `basename $FirstImage`
    set img = `ls -lnL $framedir |& nawk '$0 ~ /^\-/ && $5+0 > 800000 {print $NF}' |& nawk "$IMAGE_pattern" |& grep "$ext" |& nawk -v key="$img" '$0 == key {getline; print}' `
    if("$img" != "") set img = "${framedir}/$img"
    echo ""
    if(-e "$img") then
	# this could be a workable first image

	set temp = "Yes"
	echo "Is $img the start of this wedge? [$temp]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $temp
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	endif
	if("$temp" =~ [Yy]*) then
	    # try this again
	    set FirstImage = $img
	    
	    # might need to reset some frame-specific variables
	    goto FirstImageFound
	endif
    endif
    
    # no alternative images are available
    
    # ask for more frames
    set temp = "No"
    echo "Will there be more frames like $FirstImage? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo $temp
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then

	# ask how many frames there will, evenutally,  be
	@ temp = (($savelast - $first) + 1)
	echo "How many? [$temp]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $temp
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	endif
	
	if("$temp" =~ [1-9]*) then
	    set number_of_frames = `echo $temp | nawk '{print $1+0}'`
	    set USER_WEDGE_SIZE = $number_of_frames
	    echo ""
	    echo "$scriptname will be created, but not run."
	    echo "run $scriptname when there are $number_of_frames frames in this wedge."
	    @ last = ($first + $number_of_frames)
	    set savelast = $last
	    set NORUN
	endif
    else
	set newframe = "keep looking"
	echo "What is the first frame of the wedge you want to process? [$newframe]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo "$newframe"
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set newframe = "$in"
	endif
	
	# go back and check this
	set bad_frames = `echo $bad_frames $FirstImage`
	set FirstImage = ""

	# if user said so, frame is no longer bad
	set temp = ""
	foreach baddie ( $bad_frames )
	    if(("$baddie" !~ *"$newframe"*)&&("$newframe" !~ *$baddie*)) set temp = "$temp $baddie"
	end
	set bad_frames = `echo $temp`
	
	set inframes = `echo $newframe $inframes |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	goto PickFirstImage
    endif
endif
SkipCheckWedge:
onintr

#if($?NORUN) then
#    # just restore number of frames
#    set last = $savelast
#endif

# lock in number of frames in this wedge
@ number_of_frames = (( $last - $first ) + 1 )
# integer value to check wedge size
set wedge_width = `echo "$first $last $osc" | nawk '{printf "%d", $3*($2 - $1 + 1)}'`


# once frames have been checked, we probably don't need to do it again
set check_frames = "no"


CheckSegments:
###############################################################################
# check/make sure that postrefinement segments will fit in wedge
#
###############################################################################

# integer value to check wedge size
set wedge_width = `echo "$first $last $osc" | nawk '{printf "%d", $3*($2 - $1 + 1)}'`

# cannot postrefine just one frame
if($number_of_frames == 1) then
    set integrate = "yes"
    set postref = "no"
    goto Check_Space_Group
endif

# automatically determine decent subwedges for this wedge
if(("$frames_per_segment" == "auto")||("$mosflm_postref_segs" == "auto")) then
    # get wedge size
    @ number = ( ($last - $first) + 1 )
    
    # do about 1/2 of frames, unless wedge is already small
    if($number > 12) @ number = ($number / 2 )
    
    # mosflm can't handle more than 30 frames in postrefinement
    if($number > 30) set number = 30
    
    # now 2 < number < 30
    if($number < 4) then
	# small wedge, just do one segment
	set mosflm_postref_segs = 1
	set frames_per_segment = $number
    else
	if($number < 11) then
	    # smallish wedge, two segments
	    @ frames_per_segment = ( $number / 2 )
	else
	    # do all subwedges as 4 frames each
	    set frames_per_segment = 4
	endif
	@ mosflm_postref_segs = ( $number / $frames_per_segment )
    endif
endif

# absolute minimum for segment
if($frames_per_segment < 2) set frames_per_segment = 2

@ number = (($last - $first) + 1)
# again, mosflm can't handle more than 30 frames in postrefinement
if($number > 30) set number = 29

# reduce frames per segment until number of frames is managable
if($number < ($frames_per_segment * $mosflm_postref_segs)) then
    echo "Too many refinement frames, compensating ..."
endif
while(($number < ($frames_per_segment * $mosflm_postref_segs))&&($frames_per_segment > 2))
    @ frames_per_segment = ( $frames_per_segment - 1 )
end
# reduce number of segments, (if segment size is minimal and we still have too many frames)
while($number < ($frames_per_segment * $mosflm_postref_segs))
    @ mosflm_postref_segs = ( $mosflm_postref_segs - 1 )
end

# make sure there is at least one segment
if($mosflm_postref_segs == 0) then
    set mosflm_postref_segs = 1
    set frames_per_segment = $number
endif

# absolute minimum for segment
if($frames_per_segment < 2) set frames_per_segment = 2



###############################################################################
# check if space group has been set,  if not, now is a good time to bug user
#
###############################################################################
Check_Space_Group:
if("$SG" != "unknown") then
    if("$SG" =~ *-ish) then
	set SG_choice = "auto"
	set SG = `echo $SG | nawk -F "[-]" '{print $1}'`
    endif
    # make sure SG is in the space group library
    set SG = `echo $SG | nawk '{print toupper($1)}'`
    cat $CLIBD/symop.lib |&\
    nawk -v SG=$SG '$4==SG{type=substr(tolower($6),1,1); key=substr($6,4,1);\
        if((type=="t")&&(key=="G")) type="h"; if((type=="t")&&(key=="C")) type="a";\
	print $1, $5, type substr($4,1,1), $6;exit}' |\
    head -1 >! ${tempfile}sgdata
    set SG_number = `nawk '{print $1}' ${tempfile}sgdata`
    set PG =        `nawk '{print $2}' ${tempfile}sgdata`
    set BRAV =      `nawk '{print $3}' ${tempfile}sgdata`
    set LATT =      `nawk '{print $4}' ${tempfile}sgdata`
    rm -f ${tempfile}sgdata >& /dev/null
    if("$SG_number" == "") then
	# this SG was not listed in the CCP4 library! 
	echo ""
	echo "Woops! $SG is not in space group library. $BELL "
	echo ""
	set temp = "unknown"
	echo "What is your space group? [$temp]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $temp
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" =~ [PpCcIiFfRrHh][1-6]*) set temp = ( $in )
	endif
        set SG = "$temp"

	# now go back and check this one
	goto Check_Space_Group
    endif

    # now decide between high-symmetry and low-symmetry refinement mode
    set test = `echo "$hires" | nawk '{printf "%.0f", $1}'`
    if($SG_number < 143 && $test > 3) then
	# space group is < trigonal symmetry, cannot refine cell on small wedge
	if($wedge_width < 45 && $wedge_width > 1) then
	    # don't refine cell unless we have 45 degrees of data or more
	    
	    if($fixcell == no) then
		echo ""
		echo "WARNING: Cell refinement might be unstable with only $wedge_width$DEG of data! "
		if("$true_cell" == "unk") then
		    # user is undecided about this
		    set temp = "No"
		    echo "Shall we fix the cell? [$temp]"
		    echo -n "$PROMPT"
		    if($?AUTO) then
			echo "$temp"
		    else
			echo -n "$BELL"
			set in = ( $< )
			if("$in" != "") set temp = ( $in )
		    endif
		    if("$temp" =~ [Yy]*) set fixcell = yes
		    
		    # don't do this again
		    set true_cell = no
		endif
	    endif
	else
	    # should have wide enough angle to refine cell, even with low symmetry
	endif
    else
	# can refine cell with only a few frames
    endif    
endif

CheckCell:
# Check that the cell is consistant with the space group
if(("$CELL" != "unknown")&&("$SG" != "unknown")) then
    # get the lattice type
    set latt = `nawk -v SG="$SG" '$4 == toupper(SG) {print $6;exit}' $CLIBD/symop.lib |& head -1`
    
    # check Cell against lattice
    echo "$CELL $latt" |\
    nawk '{a=$1+0; b=$2+0; c=$3+0; A=$4+0; B=$5+0; G=$6+0}\
    $NF == "MONOCLINIC" { A=90; ; G=90; if($4+0 > 5) B=$4+0; if($5+0 > 5) B=$5+0}\
    $NF == "ORTHORHOMBIC" {A=90; B=90; G=90}\
    $NF == "TETRAGONAL" || $NF == "TRIGONAL" || $NF == "HEXAGONAL" {\
    b=a; A=90; B=90; G=120;\
    if((c==0) && (($2-a)^2 > .0001)) {c = $2+0}}\
    $NF == "TETRAGONAL" {G=90}\
    $NF == "CUBIC" {b=a; c=a; A=90; B=90; G=90}\
    END{if(a>5 && b>5 && c>5 && A>5 && B>5 &&G>5) print a, b, c, A, B, G}' |\
    cat >! ${tempfile}
    set temp = `cat ${tempfile}`
    rm -f ${tempfile}
    if("$#temp" == 6) then
	# actual, corrected unit cell was given
	set CELL = `echo "$temp"`
    endif
endif

# check the mosaicity, if it has not been set, pick a reasonable value
if(("$mosaic" == "auto")||("$mosaic" == "")) then
    set mosaic = `echo "$osc" | nawk '$1+0>0.05{print $1/2}'`
    if("$mosaic" == "") set mosaic = 1

    set temp = `echo "$MosflmVersion" | nawk '/[0-9]/{printf "%d", $1*100}'`
    if("$temp" > 619) set mosaic = "estimate"
endif

# calculate resolution limit from detector geometry (unless user set it manually)
if(("$res_choice" == "auto")&&("$Width" != "")&&($#beam_center == 2)) then
    # get resolution at all four corners and four midpoints
    echo "$Width $beam_center" |\
    nawk '{xmax=$1; ymax=$1; xc=$2; yc=$3; \
        print xc,yc,"C"; print xc,ymax-yc,"C"; print xmax-xc,yc,"C"; print xmax-xc,ymax-yc,"C";\
        print xc,0,"E";  print 0,yc,"E"; print xmax-xc,0,"E"; print ymax-yc,0,"E"}' |\
    nawk -v distance=$distance -v two_theta=$two_theta 'BEGIN{two_theta*=3.14159/180} \
        NF==3{x=$1;y=$2; L=distance-x*sin(two_theta); x=x*cos(two_theta);\
              print sin(atan2(sqrt(x^2 + y^2),L)/2),$3}' |\
    nawk -v wavelength=$wavelength '$1+0>0{print wavelength/(2*$1),$2}' |\
    cat >! ${tempfile}res

    # disregard corners for circular detectors
    if(("$Site" =~ MAR*)||(0)) then
        tail -4 ${tempfile}res >! ${tempfile}
        mv -f ${tempfile} ${tempfile}res >& /dev/null
    endif

    # set resolution limits
    set hires = `sort -n ${tempfile}res | nawk '$1+0>0{printf "%.1f", $1; exit}'`
    set edge_res = `tail -4 ${tempfile}res | sort -n | nawk '$1+0>0{printf "%.1f", $1; exit}'`
    rm -f ${tempfile}res >& /dev/null
endif


PrintIntentions:
###############################################################################

 #####   ######  #####    ####   #####    #####
 #    #  #       #    #  #    #  #    #     #
 #    #  #####   #    #  #    #  #    #     #
 #####   #       #####   #    #  #####      #
 #   #   #       #       #    #  #   #      #
 #    #  ######  #        ####   #    #     #

###############################################################################
#
#   As a check, print out what Wedger Elves think they are supposed to do.
#
###############################################################################
if(($?autoindexing)&&(! $?NOMOSFLM)) goto autoindex
unset FIRSTIME
echo ""
echo ""
set temp = " that will run $MOSFLM"
if($?NORUN) set temp = " (but will not run it.)"
set LastImage = `echo "$framedir/$template $last" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`

echo "Wedger elves will create a script called ${scriptname}"$temp
echo "         and process from $FirstImage"
echo -n "                       to $LastImage"
if($integrate == yes) then
    echo " into $mtzout"
else
    echo ""
endif
if((-e "$inmatrix")&&(! $?autoindexing)) then
    echo -n "         using the orientation in $inmatrix"
    if(($add != 0)&&($integrate == yes)) then
	echo ", and adding $add to each batch number."
    else
	echo ""
    endif
else
    echo "         after obtaining an orientation from autoindexing."
endif
if(("$Interactive" == "PLOT")&&(! $?AUTO)) then
    echo ""
    echo "        The Mosflm interactive graphics window will be launched."
endif
#if($?NEW) then
#    echo ""
#    echo "        First time processing these data."
#endif
if(($?LAST_RUN)&&(! $?NO_CCP4)) then
    echo ""
    echo "        Then $mtzout will be scaled and merged into $mergefile."
endif
echo ""
#set temp = `echo "${phi0} + ($osc * ($last - $first + 1)) " | bc`
set temp = `echo "$phi0 $osc $last $first" | nawk '{print $1+($2*($3-$4+1))}'`
echo "        Data were collected from ${phi0}$DEG to ${temp}$DEG, in ${osc}$DEG steps with the "
echo "        $Site detector (gain = $GAIN) at $distance mm from the crystal and"
set temp = `echo $two_theta | nawk '$1+0 > 0{print $1+0} $1+0 < 0{print -($1+0)}'`
if("$temp" != "") then
    echo -n "        swung ${temp}"
    set temp = `echo $two_theta | nawk '$1+0 > 0{print "counter-"}'`
    echo "$DEG ${temp}clockwise around the crystal rotation axis (2theta)"
endif
echo "        the direct beam hit the detector at: $beam_center"
echo ""
#set temp = `echo "$wavelength $DISPERSION" | nawk '{if($1+0 == 0)$1=1.54; printf "%.1f", 12398.4245/$1 - (12398.4245/($1+ $1*$2))}'`
echo -n "        X-rays were ${wavelength} $ANG, "
#set temp = `echo "$DISPERSION" | nawk '$1+0 > 0{print 1/$1}'`
#if("$temp" != "") then
#    echo "with a spectral bandwidth of 1:${temp}, and "
#else
#    echo "with perfect bandwidth, and "
#endif
#echo -n "        the beam was "
#set temp = `echo "$DIVERGENCE" | nawk 'NF==1{print $1} NF==2{print $1 " x " $2}'`
#echo -n "diverging by ${temp}$DEG "
set temp = `echo "$POLARISATION" | nawk '{print $NF}'`
echo "with polarization $temp"
set temp = ""
echo ""
echo "        Unit Cell is $CELL"
if($fixcell  == yes) echo "        and it will not be refined in this run."
set sg_suffix = ""
if("$SG_choice" == "auto" && "$SG" != "unknown") set sg_suffix = "-ish"
set mosflmSG = $SG
echo "        Spots will be measured out to ${hires} $ANG with space group $SG${sg_suffix}"
set temp = `echo $fixmosaicity $mosaic | nawk '/no/{$1="of"} /yes/{$1="held at"} {printf "%s %.3f", $1,$2}'`
set temp = "${temp}$DEG"
if("$mosaic" == "estimate") set temp = "estimated from image $first"
echo "        and a mosaic spread ${temp}"
echo ""
if($integrate == no) echo "        Refinement will be in ${mosflm_postref_segs} blocks of ${frames_per_segment} frames. No integration."
#if($usebeam  == yes) echo "        Parameters will be refined for each frame."
if($fixyscale == no) echo "        The detector X-to-Y scale will be refined."
if(($integrate == yes)&&($postref == no)) echo "        Postrefinement will be turned OFF."

echo ""
if(("$PREAMBLE" != "")||("$EXTRA_REFINE_CARDS" != "")) then
    echo "        additional keywords:"
    echo "$PREAMBLE" | nawk 'BEGIN{RS="n"} {print "        " $0}' | nawk 'NF!=0'
    echo "$EXTRA_REFINE_CARDS" | nawk 'BEGIN{RS="n"} {print "        " $0}' | nawk 'NF!=0'
    echo ""
endif

if($?NEW) then
    cat << EOF
           ^   ###  ####   #   ###    ##### #  # #  ###    ^
          /|\  #  # #     # #  #  #     #   #  # # #      /|\
           |   ###  ###  ##### #  #     #   #### #  ###    |
           |   # #  #    #   # #  #     #   #  # #     #   |
           |   #  # #### #   # ###      #   #  # # ####    |

      Make sure all the above numbers are correct.
           (Especially the beam center)

EOF

endif
#
# do Strategy?
#
#if(("$strategize" == "yes")&&(-e "$inmatrix")&&($#CELL == 6)&&($SG =~ [PpCcIiFfRrHh][1-6]*)&&(! $?autoindexing)&&(! $?Convergeing)) then
if(("$strategize" == "yes")&&(-e "$inmatrix")&&($#CELL == 6)&&($SG =~ [PpCcIiFfRrHh][1-6]*)&&(! $?autoindexing)) then
    set temp = "No"
    if($?NEW) set temp = "Yes" 
    if("$SG_choice" == "auto") set temp = "Yes" 
    echo "Do you want our opinion on your collection strategy? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
        echo "$temp"
    else
        echo -n "$BELL"
        set in = ( $< )
        if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	set strategize = "done"
	goto Strategy
    endif
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
        # weird answer, send it to interpreter
        set input = "$temp"
        goto Questionaire
    endif
    # User has turned down the strategy offer
    set strategize = "done"
endif
ReturnFromStrategy:
#
# Warn user if matrix and SG are still not set up
if(($SG == unknown)||(! -e "$inmatrix")) then
    echo -n "NOTE: $scriptname will not run without "
    if(! -e "$inmatrix") echo -n "a matrix file"
    if(($SG == unknown)&&(! -e "$inmatrix")) echo -n " and "
    if($SG == unknown) echo -n "a space group"
    echo "."
    if(! -e "$inmatrix") echo "      We can create a new matrix file by autoindexing."
    if($SG == unknown) then
#	 echo "      You can pick a space group by autoindexing interactively with mosflm,"
#	 echo "      or let the elves pick one for you."
    endif
    echo ""
#    set autoindexing
endif


if($?NORUN) then
    # add BLU-ICE support here?

    set temp = "Yes"
    echo "Update $scriptname and exit Wedger Elves? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo "$temp"
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	# user specified updating the script,  but not running it
	set NORUN
	goto ProcessData
    endif
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
        # non-standard user input
	set input = "$temp"
	goto Questionaire
    endif
    
    # user seems to have changed mind about the -norun option
    unset NORUN
endif

#
#  Obligatory autoindexing
#
#if((($?autoindexing)||($SG == unknown)||(! -e "$inmatrix"))&&(! $?NORUN)) then
if(($?autoindexing)||($SG == unknown)||(! -e "$inmatrix")) then
    set temp = "Yes"
    echo "Shall we autoindex now? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo "$temp"
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) goto autoindex
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
        # non-standard user input
	set input = "$temp"
	goto Questionaire
    endif
    
    # can't process, and can't autoindex,  what do you want from me?
    set input = ""
    if($SG == unknown) set input = "wrong space group"
    if((! -e "$inmatrix")&&($SG == unknown)) set input = "${input} and"
    if(! -e "$inmatrix") set input = "${input} no matrix"

    # default to missing info
    set temp = "$input"
    if("$temp" == "") set temp = "nothing"
    echo "What's wrong? [$temp]?"
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
    if("$temp" != "nothing") then
	set input = "$temp"
	goto Questionaire
    endif
endif

# be a pest about the graphics window
if(((! $?AUTO)&&(! $?NORUN)&&($?NEW))||("$Interactive" == "PLOT")) then
    # graphics window will be displayed this run
    set temp = "No"
    if((! $?AUTO)&&(! $?NORUN)&&($?NEW)) set temp = "Yes"
    if($?Explicit_window) set temp = "Yes"
    unset Explicit_window
    echo "Do you want to monitor this run in the graphics window? (3x slower) [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo $temp
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	set Interactive = "PLOT"
	goto ProcessData
    endif
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
	# weird answer, send it to interpreter
	set input = "$temp"
	goto Questionaire
    endif
    set Interactive = "#PLOT"
endif

# if this variable is set, we are converging
if($?CATCH_USER) onintr Questionaire
if(($?AUTO)||($?ONCEONLY)||($?Convergeing)) goto ProcessData

if((! $?NORUN)&&(-e "$inmatrix")&&(! $?autoindexing)) then
    set temp = "Yes"
    echo "Shall we run $scriptname now? [$temp]? $BELL"
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
    if("$temp" =~ [Yy]*) goto ProcessData
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
	# weird answer, send it to interpreter
	set input = "$temp"
	goto Questionaire
    endif
endif


set temp = ""
if($#CELL != 6) set temp = "bad cell"
if($SG == "unknown") set temp = "wrong space group"
if(($#CELL != 6)&&($SG == "unknown")) set temp = "wrong space group and bad cell"

if("$temp" == "") set temp = "nothing"
echo "What's wrong? [$temp]?"
echo -n "$PROMPT"
echo -n "$BELL"
set in = ( $< )
if("$in" != "") set temp = ( $in )
if("$temp" != "nothing") then
    set input = "$temp"
    goto Questionaire
endif

UpdateScript:
set temp = "Yes"
if("$mosflm_status" != 0) set temp = "No"
echo "Shall we update ${scriptname}? [${temp}]?"
echo -n "$PROMPT"
if(! $?AUTO) then
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
else
    echo "$temp"
endif
if("$temp" =~ [Nn]*) then
    set NORUN
    goto Cleanup
endif

# user specified updating the script,  but not running it
set NORUN
goto ProcessData

Questionaire:
###############################################################################

  ####   #    #  ######   ####    #####     #     ####   #    #    ##       #   #####   ######
 #    #  #    #  #       #          #       #    #    #  ##   #   #  #      #   #    #  #
 #    #  #    #  #####    ####      #       #    #    #  # #  #  #    #     #   #    #  #####
 #  # #  #    #  #            #     #       #    #    #  #  # #  ######     #   #####   #
 #   #   #    #  #       #    #     #       #    #    #  #   ##  #    #     #   #   #   #
  ### #   ####   ######   ####      #       #     ####   #    #  #    #     #   #    #  ######

###############################################################################
#
#   Question user about each variable, defaulting to previous value
#
###############################################################################
# forget recommendation, since user is explicitly telling us to do something
unset recommendation

# reset Ctrl-C catch
onintr
unset AUTO
unset BURSTMODE
unset LAST_RUN
set understood = ""
#
#
#   Performs a keyworded search on user input to expedite proper initialization of variables
#
#
# backup question, for calls without their own prompts
if("$input" == "") then
    set temp = "nothing"
    echo "What's wrong? [$temp]?"
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
#    if("$temp" != "nothing") then
	set input = "$temp"
#    endif
endif

# Deploy Ginger, the English-to-Elvish translator

# look for special characters
set temp = `echo "$input" | nawk '/\177/'`
if("$temp" != "") then
    # keep this from happening again
    stty erase '^?'
    set input = `echo "$input" | nawk '{gsub("\177","",$0);print}'`
endif

echo "$input" | egrep '^\$' > /dev/null
if(! $status) then
    # execute an escaped shell command
    set input = `echo "$input" | nawk '{print substr($0,2)}'`
    $input
    goto ProcessInput
endif


# look for Wedger-specific commands

# space group
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^space/ || /^sg$/ || /^[PpCcIiFfRrHh][1-6]/'`
if("$temp" != "") then
    # see if space group was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} /^[PpCcIiFfRrHh][1-6]/'`
    if("$temp" !~ [PpCcIiFfRrHh][1-6]*) then
	set temp = "$SG"
	# something is wrong with space group, but we don't know what
	echo "What is your space group? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [PpCcIiFfRrHh][1-6]*) then
	set SG = "$temp[1]"
	set SG_choice = user
    endif
    if("$temp" =~ unk*) set SG = unknown
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif

# new preamble cards
set temp = `echo $input | nawk '{print toupper($0)}' | egrep "$PASSTHRU_CARDS"`
if("$temp" == "") set temp = `echo $input | egrep "^REFINE|^POSTREF|^LIMIT"`
if("$temp" != "") then
    # add these to preamble (check it later)
    echo $PREAMBLE | nawk 'BEGIN{RS="n"} {print}' >! $tempfile
    echo $temp |\
    nawk '! (/^LIMIT/ && $2 !~ /^EXCLU/)' >> $tempfile
    set PREAMBLE = `nawk 'BEGIN{ORS="n"} NF != 0' ${tempfile} | nawk -v L=$MAXLINE '{print substr($0,1,L)}'`
    set understood = "$understood $temp"
endif

# clear PREAMBLE
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^clear/ || /^remove/ || /^addit/ || /^keyword/'`
if("$temp" != "") then
    set temp = "Yes"
    echo "Do you want to clear the additional keywords? [$temp]"
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
    if("$temp" =~ [Yy]*) then
	set PREAMBLE = ""
	set EXTRA_REFINE_CARDS = ""
    endif
    
    set understood = "$understood clear"
endif

# unit cell
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^cell/'`
if("$temp" != "") then
    # see if unit cell was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '($0+0 > 5 || /^unk/) && p>0 {print $0; --p} /^cell/{p=6}'`
    set cell = `echo $temp |& nawk 'BEGIN{RS=" "} $0+0 > 5 && p<6 {printf "%g ", $0+0; ++p}'`
    if(($#cell != 6)&&("$temp" !~ unk*)) then
	set temp = "$CELL"
	# something is wrong with the cell, but we don't know what
	echo "What is your unit cell? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    set cell = `echo $temp |& nawk 'BEGIN{RS=" "} $0+0 > 5 && p<6 {printf "%g ", $0+0; ++p}'`
    if($#cell == 6) set CELL = `echo "$cell"`
    if("$temp" =~ unk*) set CELL = unknown
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif


# resolution
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^reso/ || /^measu/ || /^diffra/ || /[\305]/'`
if("$temp" == "") set temp = `echo $input | nawk 'BEGIN{RS=" "} $1=="A" && val>0.1{print val} {val = $1+0} $1 ~ /[0-9]A$/ && $1+0>0.1 {print $1+0}'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0.1 && p>0 {printf "%g ", $0+0; --p} /^reso/{p=1} /^diffra/{p=1} /^measu/{p=4}'`
    if("$temp" !~ *[0-9]) set temp = `echo $input | nawk 'BEGIN{RS=" "} $1=="A" && val>0.1{print val} {val = $1+0} $1 ~ /[0-9]A$/ && $1+0>0.1 {print $1+0}'`
    # make sure diffraction limit is possible
    if("$temp" =~ *[0-9]) then
	# diffraction limit cannot exceed x-ray wavelength
	if(`echo $temp $wavelength | nawk '{print ($1<$2)}'`) set temp = ""
    endif
    if("$temp" !~ [0-9]*) then
	set temp = "$hires"
	# something is wrong with this parameter, but we don't know what
	echo "How far could this crystal possibly diffract? [$temp $ANG]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk '$1+0 > 0 {print $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [0-9]*) then
	set hires = "$temp"
	set merge_res = "$temp"
	set res_choice = user
    endif
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif

# mosaicity
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^mosaic/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0.01 && $0+0 < 10 && p>0 {printf "%g ", $0+0; --p} /^mosaic/{p=1}'`
    if("$temp" !~ [0-9]*) then
	set temp = "$mosaic"
	# something is wrong with this parameter, but we don't know what
	echo "What is the mosaicity? [$temp $DEG]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk '$1+0 > 0.01 {print $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [0-9]*) set mosaic = "$temp"
    set understood = "$understood $temp"
endif

# wavelength
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^wave/ || /^x-ray/ || /^energy/ || /ev$/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0 && p>0 {val=$0+0; getline; if($0 == "kev") val *=1000; printf("%g ", val); --p} /^wave/{p=1} /^energy/{p=1}'`
    if("$temp" !~ *[0-9]) then
	set temp = "$wavelength"
	# something is wrong with this parameter, but we don't know what
	echo "X-ray wavelength/energy? [$temp $ANG]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk 'tolower($0) ~ /kev$/{print $1*1000} ! /kev$/{print $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    set temp = `echo $temp | nawk '{w = $1+0; if(w>0.2){ if(w<10){print w}else{print 12398.4245/w}}}'`
    if("$temp" =~ *[0-9]) set wavelength = "$temp"
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif

# detector gain
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^gain/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0.01 && $0+0 < 20 && p>0 {printf "%g ", $0+0; --p} /^gain/{p=1}'`
    if("$temp" !~ [0-9]*) then
	set temp = "$GAIN"
	# something is wrong with this parameter, but we don't know what
	echo "What is the quantum gain of the detector? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk '$1+0 > 0 {print $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [0-9]*) set GAIN = "$temp"
    set understood = "$understood $temp"
endif


# beam polarization
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^polar/ || /^monoc/ || /^graphite/ || /^mirror/ || /^pinhole/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0 && $0+0 < 1 && p>0 {printf "%g ", $0+0; --p} /^polar/{p=1}'`
    if("$temp" !~ [0-9]*) set temp = `echo $input | nawk 'BEGIN{RS=" "} {print toupper($0)}' | nawk '/^MONOC/ || /^GRAPH/{print "MONOCHROMATOR"} /^MIRROR/ || /^PINHOLE/'`
    set temp = `echo "$temp" | nawk '{print $1}'`
    if("$temp" == "") then
	set temp = `echo $POLARISATION | nawk '{print $NF}'`
	# something is wrong with this parameter, but we don't know what
	echo "What is the beam polarization? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
	if("$temp" !~ [0-9]*) set temp = `echo $temp | nawk 'BEGIN{RS=" "} {print toupper($0)}' | nawk '/^MONOC/ || /^GRAPH/{print "MONOCHROMATOR"} /^MIRROR/ || /^PINHOLE/'`
    endif
    if("$temp" != "") set POLARISATION = "$temp"
        
    # make sure mosflm recognizes this
    if("$POLARISATION" =~ [0-9]*) set POLARISATION = `nawk -v p=$POLARISATION 'BEGIN{print "SYNCHROTRON", p+0}'`
    set understood = "$understood $temp"
endif



#
# Initialize data collection strategy
#
# starting phi
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^phi/ || /^start/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk ' ! /[a-z,A-Z]/ && /[0-9]/ && p>0 {printf "%g ", $0+0; --p} tolower($0) ~ /^phi/{p=1}'`
    if("$temp" !~ [0-9]*) then
	set temp = "$phi0"
	# something is wrong with this parameter, but we don't know what
	echo "What is your starting phi? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = `echo $in | nawk '{print $1+0}'`
    endif
    if("$temp" =~ *[0-9]*) set phi0 = "$temp"
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif

# Oscillation angle
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^osc/ || /^step/ || /^delta/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0 && $0+0 < 20 && p>0 {printf "%g ", $0+0; --p} tolower($0) ~ /^osc/{p=1}'`
    if("$temp" !~ [0-9]*) then
	set temp = "$osc"
	# something is wrong with this parameter, but we don't know what
	echo "Oscillation? (delta phi) [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk '$1+0 > 0 {print $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [0-9]*) set osc = "$temp"
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif


#
#   Processing mode
#
# Interactive? 
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/inter/ || /graph/ || /watch/ || /window/ || /display/ || /predic/'`
if("$temp" != "") then
    # see if we can figure out flag from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{p="Y"} /nopost/{print "N"} /^no/{p="N"; getline} /^don/{p="N"; getline} /^stop/{p="N"; getline} /inter/{print p} /graph/{print p} /window/{print p} /predic/{print p} {p=""}'`
    if("$temp" == "") then
	# get current setting
	set temp = "No"
	
	# something is wrong with this parameter, but we don't know what
	echo "Do you want the graphics window? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	set Interactive = "PLOT"
	set Explicit_window
	if($?AUTO) unset AUTO
    endif
    if("$temp" =~ [Nn]*) set Interactive = "#PLOT"

    set understood = "$understood interactive"
    set strategize = no
endif

# automatic?
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$1 == "auto"'`
if("$temp" == "auto") then
    set temp = "Yes"
    if("$input" != "auto") then
	# might have meant something else
	echo "Shall we go fully automatic? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )	
    endif
    if("$temp" =~ [Yy]*) then
	set AUTO
	set CATCH_USER
	set understood = "$understood go auto"
    endif
endif

# autoindex? 
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/autoin/ || /index/'`
if("$temp" == "") then
    set temp = `echo $input | nawk '{print tolower($0)}' | nawk '/matr/ && /bad/'`
    if("$temp" != "") then
	# remove mention of matrix, it will be handled here
	set input = `echo $input | nawk 'BEGIN{RS=" "} {print}' | grep -iv matr`
    endif
endif
if("$temp" != "") then
    # see if we can figure out flag from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{p="Y"} /noauto/{print "N"} /^no/{p="N"; getline} /^don/{p="N"; getline} /^stop/{p="N"; getline} /autoin/{print p} /index/{print p} {p=""}'`
    if("$temp" == "") then
	# get current setting
	set temp = "No"
	if($?autoindexing) set temp = "Yes"
	
	# something is wrong with this parameter, but we don't know what
	echo "Auto-index? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) set autoindexing
    if("$temp" =~ [Nn]*) unset autoindexing

    set understood = "$understood index"
    if("$strategize" == "done") set strategize = "yes"
endif


# integrate? 
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/integ/'`
if("$temp" != "") then
    # see if we can figure out flag from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{p="Y"} /nointe/{print "N"} /^no/{p="N"; getline} /^don/{p="N"; getline} /^stop/{p="N"; getline} /^integ/{print p} {p=""}'`
    if("$temp" == "") then
	# get current setting
	set temp = `echo "$integrate" | nawk '{print substr(toupper($0),1,1)}'`
	
	# something is wrong with this parameter, but we don't know what
	echo "Integrate? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) set integrate = yes
    if("$temp" =~ [Nn]*) set integrate = no
    
    # have to do at least one of these
    if("$integrate" == "no") set postref = yes

    if(("$integrate" == "yes")&&($?NEW)) unset NEW
    
    set understood = "$understood integ"
endif

# merge (or last run)
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^merge/ || /^scale/'`
if("$temp" != "") then
    # asking for smooth scaling
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/smooth/'`
    if("$temp" != "") then
	echo "switching on smooth scales"
	set SMOOTH_RUNS = "scales rotation spacing 5 bfactor on"
    endif

    # see if we can figure out flag from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{p="Y"} /nomerge/{print "N"} /^no/{p="N"; getline} /^don/{p="N"; getline} /^stop/{p="N"; getline} /^merge/{print p} {p=""}'`
    if("$temp" == "") then
	# get current setting
	set temp = "No"
	if($?LAST_RUN) set temp = "Yes"
	
	# something is wrong with this parameter, but we don't know what
	echo "Merge data now? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	set LAST_RUN
	# merge now, of we can
	if(-e $mtzout) goto scale_and_merge
	echo "Sorry, $mtzout does not exist."
	echo "We have to integrate before we can merge."
	set integrate = "yes"
    endif
    if("$temp" =~ [Nn]*) unset LAST_RUN
    
    # no sense mergeing if we didn't integrate
    if("$integrate" == "no") set integrate = yes

    if(("$integrate" == "yes")&&($?NEW)) unset NEW

    set understood = "$understood merge"
endif

# run Strategy? 
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^strateg/'`
if("$temp" != "") then
    # see if we can figure out flag from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{p="Y"} /nostrat/{print "N"} /^no/{p="N"; getline} /^don/{p="N"; getline} /^stop/{p="N"; getline} /^strateg/{print p} {p=""}'`
    if("$temp" =~ [Yy]*) then
	set strategize = "yes"
	if((-e "$inmatrix")&&("$SG" != "unknown")) then
	    goto Strategy
	else
	    echo "Elves cannot strategize without a matrix and space group! "
	endif
    endif
    if("$temp" =~ [Nn]*) set strategize = "no"
    
    set understood = "$understood strategy"
endif

# postrefine? 
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/postr/ || /refine/'`
if("$temp" != "") then
    # see if we can figure out flag from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{p="Y"} /nopost/{print "N"} /^no/{p="N"; getline} /^don/{p="N"; getline} /^stop/{p="N"; getline} /ref/{print p} {p=""}'`
    if("$temp" == "") then
	# get current setting
	set temp = `echo "$postref" | nawk '{print substr(toupper($0),1,1)}'`
	
	# something is wrong with this parameter, but we don't know what
	echo "Refine parameters this run? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) set postref = yes
    if("$temp" =~ [Nn]*) set postref = no

    set understood = "$understood postref"
endif


# segmentation parameters
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^bloc/ || /^segment/'`
if(("$temp" != "")&&($postref == yes)&&($integrate == no)) then

    # see if we can figure out number of segments from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '{num=""} $0+0 > 0 {num=$0+0; getline} /^bloc/{print num} /^segment/{print num}'`
    if("$temp" == "") then
	set temp = "$mosflm_postref_segs"
	echo "number of frame blocks to postrefine? [${temp}|auto]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" != "") set mosflm_postref_segs = "$temp"

    # see if we can figure out block size from context
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 1 && $0+0 < 30 && p>0 {printf "%g ", $0+0; --p} /^block/{p=1} /^segment/{p=1}'`
    if("$temp" == "") then
	set temp = "$frames_per_segment"
	echo "postrefinement block size (in frames)? [${temp}|auto]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" != "") set frames_per_segment = "$temp"

    set understood = "$understood $temp"

    # prevent embarassing double-hit
    set input = `echo $input | nawk 'BEGIN{RS=" "; ORS=" "} /frame/ && ! hit {getline; ++hit} {print}'`
endif

# quit? 
if(("$input" == "quit")||("$input" == "exit")||("$input" == "exit")) then
    # ask about the script first
    goto UpdateScript
endif



# fix CELL
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^no/{p= p "n"} /^un/{p= p "n"}  /^don/{p = p "n"} /refine/{p= p "n_f"} /fix/{p= p "f"} /hold/{p= p "f"} /keep/{p= p "f"} /cell/{print p "c"; p=""} {p = p "_"}' | tail -1`
if("$temp" =~ *f*) then
    # see if we can figure out flag from context
    set temp = `echo $temp | nawk '/f__c/ || /f_c/{if(($0 ~ /n_f/)||($0 ~ /n__f/)){print "N"}else{print "Y"}}'`
    if("$temp" == "") then
	# get current setting
	set temp = `echo "$fixcell" | nawk '{print substr(toupper($0),1,1)}'`
	
	# something is wrong with this parameter, but we don't know what
	echo "Fix the cell during refinement? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) set fixcell = yes
    if("$temp" =~ [Nn]*) set fixcell = no
    if("$temp" =~ [Nn]*) set true_cell = no
    
    set understood = "$understood fixcell"

    # prevent embarassing double-hits
    set input = `echo $input | nawk 'BEGIN{RS=" "; ORS=" "} /cell/ && ! hit {getline; ++hit} {print}'`
endif


# fix mosaicity
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^no/{p= p "n"} /^un/{p= p "n"} /^don/{p = p "n"} /refi/{p= p "nf"} /fix/{p= p "f"} /hold/{p= p "f"} /keep/{p= p "f"} /mosa/{print p "m"; p=""} {p = p "_"}' | tail -1`
if("$temp" =~ *f*) then
    # see if we can figure out flag from context
    set temp = `echo $temp | nawk '/f__m/ || /f_m/{if(($0 ~ /nf/)||($0 ~ /n_f/)||($0 ~ /n__f/)){print "N"}else{print "Y"}}'`
    if("$temp" == "") then
	# get current setting
	set temp = `echo "$fixmosaicity" | nawk '{print substr(toupper($0),1,1)}'`
	
	# something is wrong with this parameter, but we don't know what
	echo "Keep the mosaicity at $mosaic from now on? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) set fixmosaicity = yes
    if("$temp" =~ [Nn]*) set fixmosaicity = no
    
    set understood = "$understood fixcell"
endif

# fix YSCALE
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^no/{p= p "n"} /^un/{p= p "n"} /^don/{p = p "n"} /fix/{p= p "f"} /scale/{print p "s"; p=""} ! /^y/{p = p "_"}' | tail -1`
if("$temp" =~ *f*) then
    # see if we can figure out flag from context
    set temp = `echo $temp | nawk '/f__s/ || /f_s/{if(($0 ~ /n_f/)||($0 ~ /n__f/)){print "N"}else{print "Y"}}'`
    if("$temp" == "") then
	# get current setting
	set temp = `echo "$fixyscale" | nawk '{print substr(toupper($0),1,1)}'`
	
	# something is wrong with this parameter, but we don't know what
	echo "Fix the X-to-Y scale during refinement? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) set fixyscale = yes
    if("$temp" =~ [Nn]*) set fixyscale = no
    
    set understood = "$understood fixcell"
endif

#
#  Finding files, etc.
#
# frame location
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^frame/ || /^image/ || /^directory/ || /^locat/ || /^start/'`
if(("$temp" != "")&&(! $?FIRSTIME)) then
    echo "Double-check: "
    
    # see if frame file name was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print}' | egrep "${framepattern}" | head -1`
    if(("$temp" != "")&&(! -e "$temp")) set temp = ${framedir}/$temp
    if(! -e "$temp") then
	set temp = "$FirstImage"
	# something is wrong with this parameter, but we don't know what
	echo "What is the first image in this wedge? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if(! -e "$temp") then    
	# see if directory name was given
	set temp = `echo $input | nawk 'BEGIN{RS=" "} /\//' | head -1`
	if(! -e "$temp") then
	    #set temp = "$framedir"
	    set temp = "$FirstImage"
	    # something is wrong with this parameter, but we don't know what
	    echo "Where are your frames? [$temp]"
	    echo -n "$PROMPT"
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	endif
    endif
    if(-e "$temp") then
	set FirstImage = "$temp"
    else
	echo "Sorry! the file $temp does not exist! "
	set input = ""
	goto Questionaire
    endif

    # the following is essentially duplicated from FirstImageFound:

    # get file name info from the frame's name
    set framedir    = `dirname $FirstImage`
    set ext         = `echo $FirstImage |& nawk 'BEGIN{FS="."} $NF~/^[a-z]/{print "."$NF}'`
    set FirstImage  = `basename $FirstImage`
    set frameprefix = `basename $FirstImage $ext`

    # construct the template pattern from this filename
    set template    = `echo ${frameprefix} $ext | nawk '{while($1~/[0-9]$/){patt=patt "\043"; $1=substr($1,1,length($1)-1)}} {print $1 patt $2}'`
    set compatible  = `echo "$template" | nawk '/[_-]\043\043\043[.]/{print "yes"}'`

    # scan for the last possible file in the wedge
    ls -lnL ${framedir} |&\
    nawk -v first=$FirstImage '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
    nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	$1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
    nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
    cat >! ${tempfile}
    set LastImage = `nawk '{print; exit}' ${tempfile}`
    rm -f ${tempfile} >& /dev/null
   
    # constrain template based on available filenames
    ls -1 $framedir |\
    nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	$1 ~ "^"w[1] && $1 ~ w[n]"$" {print}' |\
    nawk -v first=$FirstImage -v last=$LastImage '\
	$1==first{p=1} p{print} $1==last{p=0}' |\
    nawk '{if(length($0)>maxlen) maxlen=length($0);\
	for(col=1;col<=maxlen;++col){c=substr($0,col,1);\
	if(tpl[col]!=c){tpl[col]=tpl[col] c}}} \
	END{for(col=1;col<=maxlen;++col){\
	    if(length(tpl[col])!=1) tpl[col]="\043";\
	    printf "%s", tpl[col]}; print ""}' |\
    cat >! ${tempfile}
    set temp = `nawk 'BEGIN{FS="\043"} {print NF}' ${tempfile}`
    if("$temp" > 2) then
#	set template = `cat ${tempfile}`
    endif
    rm -f ${tempfile}
    # now we have template in "prefix###.img format"
    
    # make a pattern for recognizing new images
    set noglob
    set framepattern = `echo "$template" | nawk '{gsub("[.]","[.]",$0); gsub("[+]","\+",$0); gsub("\043","[0-9]",$0); print "^" $0 "$"}'`
    unset noglob
    
    set first     = `echo "$FirstImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
    set last      = `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
    set FirstImage = `echo "$framedir/$template $first" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
    
    # check for backward-compatibility
    if("$compatible" != "") then
	# template has the form prefix[-_]###.ext
	# so, safe to use "old" image file breakdown
	set ext         = `echo $FirstImage |& nawk 'BEGIN{FS="."} {print $NF}'`
	set frameprefix = `basename $FirstImage .$ext | nawk '{print substr($1, 1, length($1)-4)}'`
	set TEMPLATE = ""
    else
	# we will have to use the mosflm v5.4+ TEMPLATE keyword
	set TEMPLATE = "TEMPLATE $template"
	set frameprefix = `echo "$template" | nawk 'BEGIN{FS="\043"} {print $1}'`
    endif
    
    # check for user-specified last image
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0 && $0 !~ /\./ && p>0 {printf "%d ", $0+0; --p} /^last/{p=1}'`
    if("$temp" == "") set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 0 && $0 !~ /\./ {v = $0+0; getline; if($0 == "frames") print v}'`
    if("$temp" != "") set last = "$temp"
    echo "What is the ending frame number? [${last}]"
    echo -n "$PROMPT"
    set temp = "$<"
    set temp = `echo "$temp" | nawk '{print $1+0}'`
    if($temp > 0) set last = "$temp"
    @ number_of_frames = ( ( $last - $first ) + 1 )

    set LastImage  = `echo "$framedir/$template $last" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
    
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif



# output script
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/.sh$/ || /.com$/ || /^output/ || /^script/ || /^file/ || /^name/'`
set temp = ""
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print}' | nawk '/.sh$/ || /.com$/' | head -1`
    if("$temp" == "") then
	set temp = "$scriptname"
	# something is wrong with this parameter, but we don't know what
	echo "What do you want the script to be called? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" != "") then
	set scriptname = "$temp"
	set understood = "$understood $temp"
    endif
endif

# output mtz file
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/.mtz$/ || /^output/ || /^file/ || /^name/'`
if(("$temp" != "")&&("$understood" !~ *file*)&&("$understood" !~ *output*)&&("$understood" !~ *name*)) then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} /.mtz$/' | head -1`
    if("$temp" == "") then
	set temp = "$mtzout"
	# something is wrong with this parameter, but we don't know what
	echo "What do you want the output mtz file to be called? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ *.mtz) then
	set mtzout = "$temp"
    else
	echo "SORRY, unmerged output is (currently) only in MTZ format."
	echo "       But, you can always use mtz2various.com to convert ${mtzout}."
    endif
    set understood = "$understood $temp"
endif

# mosflm executable file
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/mosflm/ || /execut/'`
if(("$temp" != "")&&("$understood" !~ *mosflm*)) then
    # see if real filename was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print}' | nawk '/mosflm/' | head -1`
    if( -e "$temp") set temp = `ls -lnLd $temp |& nawk '$5>3000000{print $NF}'`
    if(! -e "$temp") then
	set temp = "$MOSFLM"
	# something is wrong with this parameter, but we don't know what
	echo "Which Mosflm executable shall we use? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if(-e "$temp") then
	set mosflm = "$temp"
	set temp = `echo "GO" | $mosflm SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
	rm -f mosflm.lp >& /dev/null
	if("$temp" !~ [1-9]*) then
	    # no dice
	    echo "$mosflm does not appear to be a MOSFLM executable! "
	    set mosflm = ""
	else
	    unset NORUN
	    set MOSFLM = $mosflm
	    set MosflmVersion = "$temp"
	endif
    else
	echo "HEY! $temp does not exist! "
    endif

    set understood = "$understood $temp"
endif

# "ADD" value for batch numbers
set temp = `echo $input | nawk '/^ADD /'`
#set temp = ""
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > -0.1 && $0+0 < 9000 && p>0 {printf "%d ", $0+0; --p} /^add/{p=1}'`
    if("$temp" !~ [0-9]*) then
	set temp = "$add"
	# something is wrong with this parameter, but we don't know what
	echo "What value should be added to frame numbers in ${mtzout}? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk '$1+0 >= 0 {printf "%d", $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    if(($temp + $last - $first) < 9999) then
	set add = "$temp"
    else
	echo "SORRY: batch numbers greater than 9999 are not allowed here. "
    endif
    set understood = "$understood $temp"
endif

#
#  Alignment
#
# XTF distance
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^dist/ || /^xt/ || /^crystal/ || /^detect/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '$0+0 > 10 && $0+0 < 1000 && p>0 {printf "%g ", $0+0; --p} /^dist/{p=1} /^xtf/{p=1}'`
    if("$temp" !~ [0-9]*) then
	set temp = "$distance"
	# something is wrong with this parameter, but we don't know what
	echo "Crystal-to-Film Distance? [$temp mm]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set in = `echo $in | nawk '$1+0 > 10 {print $1+0}'`
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [0-9]*) set distance = "$temp"

    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif


# 2THETA angle
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^detect/ || /^swing/ || /^swung/ || /^twoth/ || /theta/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk 'p>0 && /[0-9]/ && ! /[a-z]/ {printf "%g ", $0+0; --p} /theta/{p=1} /^twoth/{p=1} /^swing/{p=1} /^swung/{p=1}'`
    if("$temp" !~ *[1-9]*) then
	set temp = "$two_theta"
	# something is wrong with this parameter, but we don't know what
	echo "2THETA angle (counterclockwise detector swing around phi axis)? [${temp}$DEG]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = `echo $in | nawk '{print $1+0}'`
    endif
    if("$temp" =~ *[0-9]*) set two_theta = "$temp"

    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif


# orientation matrix
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^matr/ || /^orien/ || /.mat$/'`
if("$temp" != "") then
    # see if matrix filename was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} {print}' | nawk '/.mat$/' | head -1`
    if(! -e "$temp") then
	if(! -e "$temp") set temp = "$inmatrix"
	foreach word ( $input )
	    # look for last word that is an existing file
	    if(-e $word) set temp = $word
	end
	# something is wrong with this parameter, but we don't know what
	echo "Where is your orientation matrix? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if(-e "$temp") then
	set inmatrix = "$temp"
	unset autoindexing
	set input = "$input scan $inmatrix"	
    else
	echo "HEY! $temp does not exist! "
    endif

    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif


#Beam center
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print tolower($0)}' | nawk '/^direct/ || /^beam/ || /^center/'`
if("$temp" != "") then
    # see if value was given
    set temp = `echo $input | nawk 'BEGIN{RS=" "} $0+0 > 10 && $0+0 < 1000 && p>0 {printf "%g ", $0+0; --p} tolower($0) ~ /^beam/{p=2}'`
    if($#temp != 2) then
	set temp = "$beam_center"
	# something is wrong with this parameter, but we don't know what
	echo "What is the direct beam center? [$temp]"
	echo -n "$PROMPT"
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if($#temp == 2) then
	# something was entered by user
	set beam_center = `echo $temp`
	
	if(($temp[1] =~ [1-9]*)&&($temp[2] =~ [1-9]*)) then
	    set temp = "mosflm"
	    echo "Is this beam center from Mosflm, adxv, R-axis(horiz, vert), or denzo? [$temp]"
	    echo -n "$PROMPT"
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = `echo $in | nawk '{print tolower($0)($1)}'`
	    
	    if("$temp" =~ mos*) then
		# no change
	    endif
	    
	    if(("$temp" =~ den*)&&("$Site" =~ *mar*)) then
		# different origin for MAR
		set beam_center = `echo "$beam_center $Site" | nawk '{print $2, $NF-$1}'`
	    endif
	    
	    if("$temp" =~ ad*) then
		set temp = `echo $beam_center`
		# mosflm X is ( frame width) - (ADXV's Y),  mosflm Y is ADXV's X
		if(! $?Width) set Width = 188
		#set beam_center = `echo "$Width - $temp[2]" | bc`
		set beam_center = `echo "$Width $temp[2]" | nawk '{print $1-$2}'`
		set beam_center = `echo $beam_center $temp[1]`
	    endif
	    
	    if("$temp" =~ r*) then
		# R-axis horizontal axis is Y, vertical axis is X
		set beam_center = `echo "$beam_center[2] $beam_center[1]"`
	    endif
	    
	endif
    endif
    
    set understood = "$understood $temp"
    if("$strategize" == "done") set strategize = "yes"
endif


# (re)scan a file? 
set temp = `echo $input | nawk 'BEGIN{RS=" "} {print}' | nawk 'tolower($0)~/^scan|^rescan|^read/{p=1} p==1{print}'`
if("$temp" != "") then
    # see if we can figure out files from context
    set sources = ""
    foreach file ( $temp )
	if(-e "$file") then
	    # scan these in order specified by user
	    set sources = "$file $sources"
	endif
    end
    if("$sources" != "") goto GetParamsFromSources

    # must want to scan something, but we don't know what
    set temp = "$oldscripts"
    echo "Scan an input file(s)? [$temp]"
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )

    if("$temp" != "") then
	set sources = "$temp"
	goto GetParamsFromSources
    endif
    
    set understood = "$understood scan"
endif



if(("$understood" == "")&&("$input" != "nothing")) then
    # What matter of sanscrit is this?! 
#    echo "$input" | mail jamesh@ucxray6.berkeley.edu

    set temp = "nothing"
    echo "Um ... what, exactly, do you mean by "\"$input\""? [$temp]"
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
    set input = "$temp"
    goto Questionaire
endif

set input=""

goto ProcessInput

ProcessData:
###############################################################################

 #    #    ##    #    #  ######       ####    ####   #####      #    #####    #####
 ##  ##   #  #   #   #   #           #       #    #  #    #     #    #    #     #
 # ## #  #    #  ####    #####        ####   #       #    #     #    #    #     #
 #    #  ######  #  #    #                #  #       #####      #    #####      #
 #    #  #    #  #   #   #           #    #  #    #  #   #      #    #          #
 #    #  #    #  #    #  ######       ####    ####   #    #     #    #          #

###############################################################################
#
#
#   At this point, all relevant information about this processing run has been
#   gathered and checked for validity.
#
###############################################################################

# some numbers we will need
set first_frame = `echo "$template $first" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
if("$TEMPLATE" != "") set first_frame = "$first"
set end_phi = `echo $phi0 $osc | nawk '{printf "%d", $1+$2}'`
# must be no-run, so make up a matrix name
if("$inmatrix" == "") set inmatrix = "best.mat"

###############################################################################
# create the README file, if necessary
#
###############################################################################
if(! -e README) then
    cat << EOF-readme >! README

Wedger Elves guide to their scripts

1) In a rush?  Just type this:

$scriptname integ >! logs/mosflm.log
$mergescript >! logs/merge.log


That should do it.  

The logs from these runs: logs/mosflm.html and logs/merge.log can be viewed in 
CCP4's xloggraph program or netscape for a graphical view of your data reduction
parameters.

Your scaled and merged data will end up in ${mergefile}, (in CCP4 format) 
to convert it to other formats, read on...



2) Okay, how does it work?

    Wedger Elves do a lot of fancy footwork to get mosflm running properly and
smoothly.  It is HIGHLY recommended that you use Wedger Elves, and let them optimize
your parameters as much as they can before you start messing around with these
scripts yourself.  They are more likely to run properly if you do.  

In this directory (`pwd`):

################################################################################
$scriptname	- mosflm script
    reads: x-ray images (${framedir}/${template})
           $inmatrix	- the crystal's orientation matrix (mosflm format)
    makes: $mtzout	- integrated spot intensity data (CCP4 mtz format)
           $outmatrix	- the refined crystal orientation matrix 
    usage: $scriptname [integ]
    
    example: $scriptname

    The $scriptname script is meant to be a bare-bones script for running 
    A.G.W. Leslie's ipmosflm program. If you don't have mosflm, you can 
    download it for free from:

    netscape ftp://ftp.mrc-lmb.cam.ac.uk/pub/mosflm/
    
    As long as the Wedger Elves could find the ipmosflm executable, and
    some x-ray data, they should have set up mosflm.com to at least run.
    Remember, a mosflm matrix must be obtained from autoindexing, (or from
    another wedge of data collected from the same data collection session)
    before mosflm.com will run.  (see autoindex.inp below)

    NOTE: THIS SCRIPT HAS TWO MODES! 

    1) if this script has a "POSTREF SEGMENTS" line in it, then it is
    set up to only refine your crystal and camera parameters.  It will 
    produce the refined crystal orientation in $outmatrix  This file
    should be copied to $inmatrix if you want to re-input this orientation
    into the next mosflm run.

    2) if this script has no "POSTREF SEGMENTS" line, and only one "PROCESS"
    line, then it is set up to integrate.  It will produce a list of measured
    spot intensities in $mtzout

    To convert from a refining script to an integrating script, delete the
    "POSTREF SEG" line, and make sure there is only one "PROCESS" line indicating
    all of the data in your wedge.  

    See the mosflm manual for more details on how to edit and run mosflm scripts.


################################################################################
$mergescript	- semi-intelligent mergeing script

    reads: $mtzout	- an mtz of integrated spot intensity data
    makes: $mergefile	- an mtz of averaged structure factor data 
    usage: $mergescript [SG] [raw.mtz] [1.8A] [120aa]
    where: 
    SG	    is the space group to apply in mergeing (default: $SG)
    raw.mtz contains the (unmerged) data to merge   (default: $mtzout)
    1.8A    is the desired outer resolution limit   (default: $hires)
    120aa   is the number of amino acids in the asymmetric unit (for truncate)

    Example: $mergescript $SG raw.mtz 3A 100aa
    will scale and merge the data in raw.mtz out to to 3.0 A with the symmetry
    operators from $SG, and run truncate with an ASU of 100aa.  
    
    This script is meant to get you started with scaling and mergeing your data.
    Wedger Elves will examine the results of this script to see if scale smoothing
    might be appropriate, and will try to apply it if it is.
    
    If a space group is provided, the CCP4 program reindex will be applied to
    the raw data before scaling and mergeing.  The outer resolution limit can
    also be specified on the command-line, as well as the number of amino acids
    residues in the asymmetric unit.  This latter value is used by truncate to
    try to put the final structure factors on an absolute scale (electron units).
    It is not critical, but a good habit to get into.
    
    Although merge.com was meant for the raw data produced from the Wedger Elves
    scripts, it should be applicable to almost any unmerged mtz data.

################################################################################
autoscala		- optimizer for SDCORR card
    reads: a scala script
    makes: a better scala script
    usage: autoscala script.com
    where: script.com is the scala script to optimize

    example: autoscala merge.com

    Scala's SDCORRECTION card allows the assigned error (sigma) of the spot 
    intensities to be edited.  Most measurement programs cannot predict the
    effects of absorption and other systematic measurement errors, and therefore
    usually give unrealisticially low estimates of the error in the measured
    spot intensities.  You should read the scala documentation to find out 
    exactly how SDCORR works.
    Briefly, "correct" sigmas should be similar to the scatter of observed intensities.
    That is, if the 10 observations of hkl=(5,9,12) deviate from the average value
    of (5,9,12) by 100 units (rms), then the sigma of (5,9,12) should be 100.  So, 
    if the assigned sigma is 50, then the scatter/sigma will be 2.  This analysis, 
    grouped by intensity bins, is the last graph in the scala logfile.  You want 
    all the points on this graph to be as close to 1.0 as possible.  If you see this, 
    then your assigned sigmas are probably realistic.
    To save you from hours of diddling with the SDCORR numbers, autoscala uses a 
    "Golded-Section" search (derived from Numerical Recipies), to optimize the three 
    numbers for scala's SDCORRECTION card, using the deviation of the aforementioned
    graph from 1.0 as a target.  In CCP4 3.3 and beyond, the first number on the SDCORR 
    card is optimized internally (and might as well be "1"), but the remaining two can 
    be tuned up by autoscala.

################################################################################
SGsearch.com		- exhaustive space-group search
    reads: a scala script
    makes: a table of mergeing statistics
    usage: SGsearch.com [script.com] [raw.mtz] [rootSGs]
    where: 
	script.com is the scala script to use        (default: merge.com)
	raw.mtz    is the raw, unscaled data         (default: raw.mtz)
	rootSGs    is/are the "starting" space group (default: SG from raw.mtz)

    example: SGsearch.com merge.com P212121

	will run merge.com with every orthorhombic space group:
	    P222, P2221, (P2122, P2212), P21212, (P21221, P22121), and P212121

    Picking the wrong space group has been known to waste weeks to years of an 
    investigators time.  SGsearch.com uses the space group provided to get the
    general crystal system your crystal was indexed with, and will then try 
    mergeing your data in EVERY space group belonging to that crystal system.
    The Rmerge, systematic absences, and asymmetric unit volume will be presented
    in a neat table for your review.  
    
    The actual logs from the individual merge.com runs will be placed in the ./logs/
    directory, named merge.SG.log.  If SGsearch.com finds these logs aready exist, 
    it will use the statistics in them to make the table, this usually saves you a 
    lot of time re-generating the table, and you can always delete these logs, and 
    run SGsearch.com again.
    
    SGsearch.com is desiged to work with the merge.com provided by Wedger Elves, 
    but should work fine with any scala/truncate script that is capable of 
    accepting and applying a space group provided on its command line.

################################################################################
Patt.com		- basic Patterson script
    reads: merged.mtz
    makes: Patt.map
    usage: Patt.com merged.mtz [merged2.mtz]
    where: 
	merged.mtz   is the merged mtz file (containing DANO or F)
	merged2.mtz  is another merged mtz file (containing F)

    examples:
	Patt.com merged.mtz
	  - will calculate a Patterson of DANO in merged.mtz
	Patt.com merged.mtz ../wedge2/merged.mtz
	  - will calculate a Patterson of F-F between the two mtzs

    description:
	Patt.com will have to be edited for most customizations.  All it
	really is is a basic framework for calculationg Pattersons.  Data
	sets are expected to be named "DANO" or "F", and changing
	the resolution or difference cutoffs must be done by editing the
	top of the script.  Patt.com exists for your convenience in
	calculating preliminary Pattersons as your data are being processed.

################################################################################
mtz2various.com		- basic format-converter script
    reads: merged.mtz
    makes: outfile.EXT
	EXT -> FORMAT
	cif -> CIF
	hkl -> shelx
	tnt -> TNT
	fin -> XtalView
	phs -> XtalView
	fobs-> XPLOR
	cv  -> XPLOR
	cns -> CNS
    usage: mtz2various.com merged.mtz outfile.EXT [format]
    where: 
	merged.mtz   is the merged mtz file (containing Fs)
	outfile.EXT  is the filename you want to use for the exported data
	format	     is the (optional) program you want outfile.EXT formatted for

    examples:
	mtz2various.com merged.mtz merged.cif
	  - will convert merged.mtz to CIF format
	mtz2various.com all.mtz "F1" merged.fobs
	  - will convert "F1" in all.mtz to XPLOR format
	mtz2various.com merged.mtz merged.hkl shelx
	  - will convert merged.mtz to shelx format
	mtz2various.com merged.mtz merged.hkl tnt
	  - will convert merged.mtz to TNT format

    description:
	mtz2various.com is a general-purpose "smart" script for converting
	"F" data from an mtz file (such as merged.mtz) to other file formats
	for other non-CCP4 programs.  The format of the output file can either
	be implied by using a standard file extension in the output file name,
	or declared explicitly and separately on the command line.  Free-R 
	flags are exported automatically, if they are present.  In the case of 
	XtalView files, a suitable CRYSTAL file is also generated.

################################################################################
autoindex.com		- mosflm autoindexing script
    usage: ./autoindex.com
    
    The autoindex.com file was created for your convenience if you want
    to resort to manually tinkering with autoindexing in mosflm.  It can
    also be edited (and renamed) to work as a script for a full mosflm
    run to integrate your data, or refine cell parameters.
    
################################################################################
strategy.com		- mosflm strategy script
    usage: ./strategy.com
    
    The strategy.com file was created for your convenience if you want
    to resort to manually tinkering with STRATEGY in mosflm.  Changing 
    things like mosaicity, distance, and 2theta can all affect the results
    of the strategy calculation.
    You can also run STRATEGY interactively by editing strategy.com
    file.  Just un-comment the "IMAGE" and "GO" lines, and run the script.        
    
    
################################################################################

3) Data files
################################################################################
best.mat	- mosflm's crystal orientation matrix

    This file contains the orientation information (and cell dimensions) of
    your crystal.  It is periodically updated by Wedger Elves, as the crystal
    orientation is refined.  
    As long as you are working with the same crystal setting, you can point
    Wedger Elves to a copy of best.mat from another wedge instead of autoindexing
    again.  best.mat holds regardless of phi, distance, 2theta, and other
    camera parameters.

################################################################################
raw.mtz		- raw, unmerged intensity data

    This is a multirecord (unmerged) mtz file produced by the last "integration"
    run of $scriptname it should contain the raw intensity measurements for
    all the spots in the processed wedge.  
    This file is meant to go into scala, or Scaler Elves

################################################################################
merged.mtz	- scaled and merged data from the wedge

    This is a "standard" mtz file containing F, SIGF, DANO, SIGDANO for
    the data measured in the wedge just processed by Wedger Elves.  It is
    produced from raw.mtz by merge.com

################################################################################
rejected_spots.txt  - list of spot observations rejected during scaling

    "Outlier" observations that did not agree with other symmetry-equivalent
    observations are listed here (by merge.com).  However, this list is given
    in the context of the "other" observations.  It is usually a good idea for
    you to visually inspect these rejected spots and make sure there really was
    something wrong with them (i.e. behind the beamstop shadow)  The quickest
    way to do this is with Spotter Elves:
    Spotter logs/merge.log $FirstImage

################################################################################
Patt.map	- anomalous difference Patterson

    By default, Wedger Elves create a "standard" anomalous-difference Patterson
    map in Patt.map by running Patt.com (above).  If you do not have access to
    a graphics program for viewing the map, logs/patt.log should contain a peak-
    pick of this map that you can review.

################################################################################

    


4) What if something goes wrong?

    The Wedger elves have been trained to handle a number of common problems 
encountered in using mosflm.  However, if something happens that
is beyond their experience, it's up to you to figure it out.  :(  But, please
email jamesh@ucxray6.berkeley.edu about your problem.

The mosflm manual is available from:

netscape ftp://ftp.mrc-lmb.cam.ac.uk/pub/mosflm/


5) tips and tricks:


If you search for the words "Ding" and "Dang" in Wedger Elves output, 
you can instantly see the rate at which mosflm runs have been sucessful or
crashing.
---

use the following awk program to average a bunch of numbers:
---

uncommenting the following lines:
#IMAGE blah blah blah
#GO
in mosflm.com will turn it into a fully-interactive mosflm script.  You run it, 
and the mosflm graphics pops up, giving you interactive control.
---

EOF-readme
endif

###############################################################################
# create $scriptname script
#
###############################################################################
if(-e "${scriptname}.older") mv ${scriptname}.older ${scriptname}.oldest
if(-e "${scriptname}.old") mv ${scriptname}.old ${scriptname}.older
if(-e "$scriptname") mv $scriptname ${scriptname}.old

# set up missetting angle reinput logic
if($#missets != 3) set missets = `nawk 'NR==4 && NF==3' $inmatrix`
set MISSET = "MISSETS       $missets RESET"
if($reinput_missets != yes) then
    # keep command for user's reference
    set MISSET = "#$MISSET"
else
    # consider "average" missets for "last" run to be 0 0 0
    set missets = ( 0 0 0 )
endif
#
# make printing decisions now
set print_swing = ""
set print_cell  = ""
set temp = `echo "$two_theta" | nawk '{printf "%d", $1*100}'`
if("$temp" != "0")     set print_swing = "SWUNG_OUT "
if($#CELL == 6)        set print_cell  = "CELL          $CELL"
set integ = "END"
if($integrate == yes) set integ = ""
#set END = ""
#if($integrate == no) set END = "END"
set mosflmSG = $SG
if("$PG" == "PG222" && "$SG" =~ P*) set mosflmSG = P222
if("$SG" =~ R* || "$SG" =~ H*) set mosflmSG = $SG_number

set ESTIMATING = ""
if("$res_choice" == "auto") then
    # need a better estimate of resolution
    # should do this before or after estimating resolution?
    set ESTIMATING = resolution
endif
if("$mosaic" == "estimate") then
    # just going to run mosaic estimation
    set ESTIMATING = "mosaic spread"
endif
set print_overload = "OVERLOAD CUTOFF $OVERLOAD"
set test = `echo $OVERLOAD | nawk '{print ($1+0<1000)}'`
if($test) then
    set print_overload = ""
endif
set print_gain = "GAIN $GAIN"
set test = `echo $GAIN | nawk '{print ($1+0<=0)}'`
if($test) then
    set print_gain = ""
endif


set mosflm_temp = mosflm_temp
if($?CCP4_SCR) then
    if(-e "$CCP4_SCR") set mosflm_temp = '${CCP4_SCR}/mosflm_temp$$'
endif


cat << eof-topscript >! $scriptname
#! /bin/csh -f
#
#  Wedger Elves automatically generated mosflm script
#
# 
# option to integrate after refining
set integ = "$integ"
if("\$1" =~ integ*) set integ = ""
#
# temporary file prefix
set tempfile = $mosflm_temp
set outfile  = $mtzout
#
#
${MOSFLM} HKLOUT \${tempfile}.mtz	\
         SPOTOD  \${tempfile}.spotod	\
         SUMMARY ${logfile}mosflm.xlog	\
         COORDS  \${tempfile}.coords << eof-ipmosflm
#
TITLE Raw data wedge from ${template} $first to $last at lambda= $wavelength
#
GENFILE \${tempfile}.gen
#
# the following keywords were not understood by Wedger Elves, but passed on
# because they resemble mosflm commands.
# ----
`echo "$PREAMBLE" | nawk 'BEGIN{RS="n"} {print}'`
# ----

# Detector parameters (range, quantum gain, etc.)
$SCANNER
$print_overload
$print_gain
$LIMITS

# Beam parameters (i.e. (delta-lambda)/lambda, H,V divervence in degrees)
WAVELENGTH    $wavelength
DISPERSION    $DISPERSION
DIVERGENCE    $DIVERGENCE
POLARISATION  $POLARISATION

# Alignment parameters
DISTANCE      $distance
BEAM          ${print_swing}$beam_center
TWOTHETA      $two_theta
MATRIX        $inmatrix
$MISSET
NEWMATRIX     ${outmatrix}

# Crystal parameters
${print_cell}
SYMMETRY      $mosflmSG
RESOLUTION    $hires
MOSAIC        $mosaic

# Frame filename breakdown
DIRECTORY     $framedir
IDENTIFIER    $frameprefix
EXTENSION     $ext
$TEMPLATE
#
# To run mosflm interactively,
# uncomment the following lines (and DON'T redirect output)
#IMAGE $first_frame PHI $phi0 TO $end_phi
#GO
#END
$Interactive
#
eof-topscript
unset print_swing
unset print_cell

if("$mosaic" == "estimate") then
    # must ALWAYS have a IMAGE to estimate resolution from
    cp $scriptname $tempfile
    echo "IMAGE $first_frame" >> $scriptname
    echo "go" >> $scriptname
    echo "end" >> $scriptname
endif

echo "$EXTRA_REFINE_CARDS" | nawk 'BEGIN{RS="n"} {print}' | nawk 'NF!=0'   >> $scriptname
echo "REFI RESID 100"					    >> $scriptname

###############################################################################
# prepare to integrate or postrefine
#   command cards will be placed in $scriptname
###############################################################################
if($fixcell   == yes) echo "POSTREF FIX ALL"      >> $scriptname
if($fixmosaicity == yes) echo "POSTREF BEAM 0"    >> $scriptname
if($fixyscale == yes) echo "REFINE  FIX YSCALE"   >> $scriptname
#if($usebeam   == yes) echo "POSTREF USEBEAM"     >> $scriptname

echo "# Processing commands: "                    >> $scriptname
###############################################################################
# set up cards to refine and integrate
#
###############################################################################
if($postref == no) echo "POSTREF OFF" >> $scriptname


if("$ESTIMATING" == "resolution") then
    # set up one-frame integration, but
    # don't do anything that might hang us up
    set integrate = yes
    cat << EOF-res_est >> $scriptname
POSTREF OFF
# skip next line
PROFILES NOOPTIMIZE
PROCESS $first to $first START ${phi0} ANGLE ${osc} ADD ${add}
go
end
EOF-res_est
endif

if($integrate == no) then
    ###############################################################################
    # create POSTREF segments commands
    #
    ###############################################################################

    echo "POSTREF SEGMENTS $mosflm_postref_segs" >> $scriptname
    
    set number = $first
    set i = 1
    @ frames_per_run = ( $last - $first )
    while( $i <= $mosflm_postref_segs )
        @ segend = ( $number + $frames_per_segment - 1 )
        if($segend > $last) set segend = $last
	#set phi = `echo "(( $number - $first ) * $osc) + $phi0" | bc`
	set phi = `echo "$number $first $osc $phi0" | nawk '{print (( $1 - $2 ) * $3) + $4}'`
        echo "PROCESS $number TO $segend START $phi ANGLE $osc  ADD ${add}" >> $scriptname
        echo "go"                                               >> $scriptname
        
        @ temp = ($mosflm_postref_segs - 1 )
        if($temp == 0) set temp = 1
        @ temp = ( ($frames_per_run - $frames_per_segment )  / $temp )
        @ number = ( $number + $temp )
        @ i = ($i + 1);
            
        # make sure last segment ends with last frame
        if($i == $mosflm_postref_segs) then
            set segend = $last
            @ number = ( $segend - $frames_per_segment - 1 )
        endif   
    end
    cat << EOF-option >> $scriptname

# to perform full integration, either put the word "integ" on the command line,
# or remove the text on the next line:
\$integ
EOF-option

endif

# now put in full integration card (wether we intend to use it or not)
cat << eof-endscript >> $scriptname
PROCESS ${first} to ${last} START ${phi0} ANGLE ${osc} ADD ${add}
GO
END

eof-ipmosflm
set mosflm_status = \$status

# update mtz only after run is finished
if((! \$mosflm_status)&&(-e \${tempfile}.mtz)&&("\$integ" == "")) then 
    mv \${tempfile}.mtz \${outfile}
endif

# Life's messy, clean it up.
rm -f \${tempfile}.spotod >& /dev/null
rm -f \${tempfile}.coord  >& /dev/null
rm -f \${tempfile}.gen    >& /dev/null
rm -f \${tempfile}.mtz    >& /dev/null
ls fort* >& /dev/null
if(! \$status) rm -f fort*


exit \$mosflm_status
eof-endscript
chmod a+x $scriptname

if($?NORUN) then 
    echo "$scriptname is ready..."

    if(! -e "$inmatrix") then
	echo "Make sure you have a good $inmatrix before you run $scriptname "
	echo ""
    endif
    
    goto Cleanup
endif


RunMOSFLM:
###############################################################################

 #####   #    #  #    #          #    #   ####    ####   ######  #       #    #
 #    #  #    #  ##   #          ##  ##  #    #  #       #       #       ##  ##
 #    #  #    #  # #  #          # ## #  #    #   ####   #####   #       # ## #
 #####   #    #  #  # #          #    #  #    #       #  #       #       #    #
 #   #   #    #  #   ##          #    #  #    #  #    #  #       #       #    #
 #    #   ####   #    #          #    #   ####    ####   #       ######  #    #

###############################################################################
#  run MOSFLM
#
###############################################################################

if("$ESTIMATING" != "") then
    echo "estimating ${ESTIMATING}..."
else
    if($integrate == yes) then
	echo "Integrating..."
    else
	echo "Refining..."
    endif
endif
    
if("$Interactive" == "PLOT") then
    set temp = "Yes"
    cat << EOF
Mosflm's output will now be dumped onto your screen

When the window comes up, you will probably want to:
Turn Prompts "off"      (lower left corner)
Turn Timeout mode "on"  (lower left corner)
Hit "Continue"          ( 5th button down )

Okay? [$temp]
EOF
    # make user confirm having read this
    echo -n "$BELL"
    echo -n "$PROMPT"
    set in = ( $< )
    if("$in" != "") set temp = "$in"
    if(($#temp > 1)||("$temp" !~ [Yy]*)) then
	set input = "$temp"
	if("$input" =~ [Nn][Oo]) set input = ""
	goto Questionaire
    endif
else
    echo You can watch the full output in `pwd`/${logfile}mosflm.log
endif
echo ""

if($?DEBUG) then
    echo "DEBUGGING: STATUS? "
    set mosflm_status = "$<"
    cp $inmatrix $outmatrix
    goto check
endif

# check, and backup old logfiles (if they have interesting stuff in them)
if(-e "${logfile}mosflm.log" ) then
    set temp = `head -10000 ${logfile}mosflm.log | grep -c "Processing Image"`
    if("$temp" > 2) mv ${logfile}mosflm.log ${logfile}mosflm.log.old
endif
if(-e "${logfile}mosflm.xlog" ) then
    set temp = `grep -c "GRAPHS" ${logfile}mosflm.xlog`
    if("$temp" == 1) mv ${logfile}mosflm.xlog ${logfile}mosflm.xlog.old
    if("$temp" > 1) mv ${logfile}mosflm.xlog ${logfile}mosflm.xlog.lastinteg
endif
if(-e "${logfile}mosflm.html" ) then
    set temp = `grep -c "GRAPHS" ${logfile}mosflm.html`
    if("$temp" == 1) mv ${logfile}mosflm.html ${logfile}mosflm.old.html
    if("$temp" > 1) mv ${logfile}mosflm.html ${logfile}mosflm.lastinteg.html
endif

# keep track of how many times we have done this
@ Cycle = ( $Cycle + 1 )

# here is where we actually launch MOSFLM
if("$Interactive" == "PLOT") then
    ./$scriptname $integ
    set mosflm_status = $status
    mv mosflm.lp ${logfile}mosflm.log
else
    # unwrap the logfile sumarizer
    cat << EOF-logsum >! ${tempfile}logsum.awk
#! $nawk -f
#
#
#	Displays a (running) summary of a mosflm log file
#
#
#
BEGIN{
    print "      spot-prd                      |xtal slip around|"
    print "frame residual ovlap mosaic  dist   beam   \\"Y\\"     phi  unit cell"
}

/Processing Image/{

    if(overloads+0 > 0)
    {
#	printf "               %4d overloads\\n", overloads
#	overloads = 0;
    }
    if(frame != "")
    {
	printf "%4d  %5s mm %5s %5s %6s%21s  %s\\n", frame, resid, overlaps, mos, dist, missets, cell;
    }
    frame = \$3; 
    mos = " n/d";
    dist = " n/d";
    cell = " n/d";
    misset = "  ??     ??     ??   "
#    overloads = 0
    overlaps  = "    ?"
}

/Final rms residual:/{
    resid = sprintf("%5.2f", \$4+0);
}

/ XTOFD /{
    getline;
    dist = sprintf("%5.1f", \$4);
}

/Real cell parameters\$/{
    getline;
    cell = \$1 " " \$2 " " \$3 " " \$4+0 " " \$5+0 " " \$6+0;
}

/Mosaic spread/{
    getline; 
    if(\$1=="New") mos = sprintf("%5.2f", \$NF);
}

/Refined Orientation Angles/{
    getline;
    getline;
    missets = sprintf("%7.2f%7.2f%7.2f", \$1, \$2, \$3);
}

/ are OVERLOADS/ && \$5 !~ /[^0-9]/{
    overloads += \$5;
}

/ Reflections generated/ && \$1 !~ /[^0-9]/{
    total_spots = \$1+0;
}
/ Overlapped reflections/ && \$1 !~ /[^0-9]/{
    overlaps = sprintf("%4d", \$1);
    if(total_spots > 0) overlaps = sprintf("%3d%%", 100*overlaps/total_spots);
}

END{
    if(frame != "")
    {
	printf "%4d  %5s mm %5s %5s %6s%21s  %s\\n", frame, resid, overlaps, mos, dist, missets, cell;
	printf "                %4d overloads (total)\\n", overloads
    }
}

EOF-logsum

    # catch Ctrl-C 
    set input = ""
    if(! $?AUTO) onintr Questionaire

    ./$scriptname $integ | head -1000000 | tee ${logfile}mosflm.log | nawk -f ${tempfile}logsum.awk

    set mosflm_status = $status
    rm -f ${tempfile}logsum.awk

    if(! $?CATCH_USER) onintr
endif
#
check:
###############################################################################

  ####   #    #  ######   ####   #    #       #####   ######   ####   #    #  #        #####   ####
 #    #  #    #  #       #    #  #   #        #    #  #       #       #    #  #          #    #
 #       ######  #####   #       ####         #    #  #####    ####   #    #  #          #     ####
 #       #    #  #       #       #  #         #####   #            #  #    #  #          #         #
 #    #  #    #  #       #    #  #   #        #   #   #       #    #  #    #  #          #    #    #
  ####   #    #  ######   ####   #    #       #    #  ######   ####    ####   ######     #     ####

###############################################################################
#  check, and sumarize mosflm results 
#
###############################################################################
if(! $mosflm_status) then
    # mosflm says everything is okay, but let's check anyway...

    # jump ahead if all we did was estimate mosaicity
    if("$mosaic" == "estimate") then
	    set lastlog = "${logfile}mosflm.log"
	    set sources = "$lastlog"
    	    goto GetParamsFromSources
    endif
 
    # jump ahead if all we did was estimate resolution
    if("$ESTIMATING" == "resolution") then
        set lastlog = "${logfile}mosflm.log"
        set sources = "$lastlog"
	set res_choice = "estimating"
        goto GetParamsFromSources
    endif


    ######################################
    # Print out Refinement Residual info #
    ######################################
    cat ${logfile}mosflm.log |\
    nawk '/Processing Image/{frame=$3} \
          /Weighted residual/{resid[frame] = $4+0 " " $NF} \
	  END{for(frame in resid) print resid[frame]}'    |\
    nawk 'BEGIN{minR=9} NF==2{++n\
                if($1<minR ){minR =$1} avgR +=$1; \
		if($2>maxWR){maxWR=$2} avgWR+=$2;} \
          END{if(n) printf "%.2f %.2f %.2f %.3f", avgWR/n, maxWR, avgR/n, minR}' |\
    cat >! $tempfile
    set resid = `cat $tempfile`
    rm -f $tempfile >& /dev/null    
    if($#resid == 4) then	 
#	echo "Average Weighted Residual = $resid[1]    (should be ~ 1)"
#	echo "Maximum Weighted Residual = $resid[2]    (should be < 5)"
#	echo "RMSD of Spot Predictions  = $resid[3] mm (pixel = $PIXEL mm)"
#	echo "Spots are $resid[3] mm (rms) from their predictions."
#	echo "(pixel is $PIXEL mm)"
	echo " (rms) $resid[3] mm between spots and their predictions."
	set temp = `echo $PIXEL | nawk '{printf "%.2f", $1}'`
	echo " (with $temp mm pixels)"
	
	# evaluate best positional residual (> 2.0 pixels is unacceptable)
	set temp = `echo $resid[4] $PIXEL | nawk '{printf "%d", $1/(2.0*$2)}'`
	if("$temp" > 0) then
	    # even the best frame is pretty far off
	    set mosflm_status = "bad_preds"
	endif
    else
	echo "could not read spot residuals! "
	# something is probably wrong! 
	set mosflm_status = "no_WR"
    endif
    
    # summarize rejected spots in moviefy format
    set filepattern = `cd $framedir ; pwd`"/"`echo "$template" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}'`
    cat ${logfile}mosflm.log |\
    nawk -v filepattern=$filepattern '\
	# get image batch number, convert to full filename \
	/Integrating Image/{file=sprintf(filepattern, $3);\
	                    nf=split(file,w,"/");base=w[nf];}\
	# detect "BADSPOTS" list \
	/H   K   L/{badspot=1} /Calculated detector/{badspot=0}\
	/Spots measured on this image/{badspot=0}\
	/SERIOUS ERROR/{serious=1} NF==0{serious=0}\
	# reformat "bad" spot entry \
	badspot && $1 ~ /^[0-9-]/ && $NF !~ /[0-9]/{\
    print file, "-center", substr($0, 34, 6), substr($0, 40, 6), \
    "-label", substr($0, 1, 13), "on", base, substr($0, 99)} \
	# reformat "serious" error entry \
	serious && /Pixel coordinates are/{X=$5;Y=$7} \
	serious && $1 == "h,k,l"{HKL=substr($0,7,12); \
    print file, "-center", X, Y, "-label", HKL, "on", base, "SERIOUS ERROR"}' |\
    cat >! ${logfile}rejects.moviekey
    
    echo ""    

    if($integrate == no) then
	##################################
	# check Postref results          #
	##################################
        if(! -e "${outmatrix}") then
            echo "Dang!  ${outmatrix} was not generated."
	    nawk '/ERROR/{print; getline; print; getline; print; getline; print}' ${logfile}mosflm.log
            echo "  Mosflm died for some reason:"
	    echo "  To find out more: more ${logfile}mosflm.log"
            set mosflm_status = "no_matrix"
        endif
    else
	##################################
	# check Integration results      #
	##################################
	if(-e "${mtzout}") then
	    if($?NO_CCP4) then
		echo "Unable to check ${mtzout} because CCP4 is not installed."
	    else
		##############################  
		# check the output mtz file. #  
		##############################
		echo "go" | mtzdump hklin ${mtzout} >! $tempfile.mtzdump
		set SGnum = `nawk '/Space group/{print $NF+0}' $tempfile.mtzdump`
		set temp = `grep "Number of Batches" $tempfile.mtzdump`
		set temp = $temp[$#temp]
		if($temp == "") then
		    echo "Dang!  ${mtzout} seems to be corrupted."
		    nawk '/ERROR/{print; getline; print; getline; print; getline; print}' ${logfile}mosflm.log
		    grep "ERROR" $tempfile.mtzdump
		    echo "  Integration didn't work:  more ${logfile}mosflm.log"
		    set mosflm_status = "bad_mtz"
		else
		    # mtzout could be read...
		    if($temp != (($last - $first) + 1)) then
			echo "Dang!  ${mtzout} does not contain all frames."
			nawk '/ERROR/{print; getline; print; getline; print; getline; print}' ${logfile}mosflm.log
			grep "ERROR" $tempfile.mtzdump
			echo "  Mosflm probably choked on one frame.  more ${logfile}mosflm.log"
			set mosflm_status = "short_mtz"
			else
				# mtzout seems to be okay...
				set mtz_res = `nawk '/Resolution Range/{getline;getline;print $6}' ${tempfile}.mtzdump`
				set mtz_res = `echo $mtz_res 1.05 | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`
		    endif
		endif
		rm -f ${tempfile}.mtzdump >& /dev/null
	    endif
        else
            echo "Dang!  ${mtzout} was not generated."
	    grep ERROR ${logfile}mosflm.log
            echo "  Mosflm must have died.  Check ${logfile}mosflm.log"
            set mosflm_status = "no_mtz"
        endif

	# check out the mtz
	if(-e "$mtzout" && "$mosflm_status" == "0" && ! $?NO_CCP4) then

	    # check and see if high resolution limit is beyond detector edge
	    set test = `echo "$mtz_res $hires" | nawk 'NF==2{print ($1 > $2)}'`
	    if("$test" == "1") then
		# we asked for a higher resolution than we got
		# must just be the edge of the detector is the limit
		echo "detector face only goes to $mtz_res ${ANG}"
		set detector_res_limit = $mtz_res
		set hires = $mtz_res
	    endif

	    # measure completeness (now that we finally can)
	    sortmtz hklin $mtzout hklout ${tempfile}.sorted.mtz << EOF >& /dev/null
${VRSET}VRSET -9e+38
H K L M/ISYM BATCH
EOF
	    
	    scala hklin ${tempfile}.sorted.mtz hklout ${tempfile}.merged.mtz << EOF-merge >& /dev/null
nodump
analyse noplot
onlymerge
EOF-merge

if(! $?SGnum) set SGnum = "$SG_number"
	    unique hklout ${tempfile}.unique.mtz << EOF-unique >& /dev/null
SYMM $SGnum
CELL $CELL
RESOLUTION $hires
LABOUT  F=IMEAN SIGF=SIGIMEAN
EOF-unique
  
	    mtzutils hklin1 ${tempfile}.merged.mtz \
         	hklin2 ${tempfile}.unique.mtz \
         	hklout ${tempfile}.complete.mtz << EOF-util >& /dev/null
UNIQUE
RUN
EOF-util
	    echo "stats nbin 100" |\
	     mtzdump HKLIN ${tempfile}.complete.mtz |&\
	    nawk '/PARTIAL FILE STATISTICS/,/No. of reflections/' |\
	    nawk '$1==4 && NF>3{res=$(NF-2)+0; if(substr($0,28)+0!=0)miss+=substr($0,20)}\
	      /partial statistics for resolution bin/{sum+=$NF; \
	        print res,100*(sum-miss)/sum}' |\
	    sort -n |\
	    nawk -v ANG="$ANG" 'NR==1 || $2>90{\
	        printf "    %.1f%% complete to %.2f %s\n",$2,$1,ANG}\
	        $2>90{exit}'

	    rm -f ${tempfile}.unique.mtz ${tempfile}.complete.mtz >& /dev/null
	    rm -f ${tempfile}.merged.mtz ${tempfile}.sorted.mtz >& /dev/null
	    rm -f ${tempfile}mtzstats >& /dev/null
	    rm -f ANOMPLOT NORMPLOT ROGUES >& /dev/null
	    echo ""
	endif

        # figure out effective outer resolution limit from mosflm log.
        cat ${logfile}mosflm.log |\
        nawk 'h==0 && /Analysis as a function of resolution./{h=1;getline;\
                       print $3, $4, $5, $6, $7, $8, $9, $10} \
              /^  <I\/sigma>/{print $2, $3, $4, $5, $6, $7, $8, $9}' |\
        nawk 'NR==1{for(i=1;i<9;++i){res[i]=$i};++n} \
              NR!=1{for(i=1;i<9;++i){signal[i]+=$i;++count[i]}}\
              END{if(n) for(i=8;i>0;--i){print res[i], signal[i]/count[i]}}' |\
	sort -nr >! ${tempfile}res_limit
        set res_limit = `nawk '$NF > 0.0 {print $1+0} $NF<=0 {exit}' ${tempfile}res_limit | tail -1`
        rm -f ${tempfile}res_limit >& /dev/null
	if("$res_limit" == "") then
	    # assume top bin still has spots?
	    set res_limit = "$hires"
	endif

    endif

    ###################################################################################
    #
    #	    Convergence Criteria: 
    #				    missets	average < 0.03 deg (rms)
    #				    mosaicity   changes < 0.03 deg
    #				    distance	changes < 0.1%
    #				    cell	changes < 0.1%
    #
    #	Convergence during integration (with maximally free cell) exits.
    #
    ###################################################################################
    if($postref == yes) then

	# read refined parameters here (to check convergence)
	
	# average missetting angles (should, eventually, tend toward zero)
	echo -n "orientation "
	# compute average misorientation angles (in degrees)
	cat ${logfile}mosflm.log |\
	nawk '/Processing Image/{f=$3} \
              /Refined Orientation Angles/{getline; getline; Cx[f]=$1; Cy[f]=$2; Cz[f]=$3}  \
              END {n=0; for(f in Cx){++n;} \
	           for(f in Cx){CX+=Cx[f]/n; CY+=Cy[f]/n; CZ+=Cz[f]/n; }; \
    	           printf "%12.6f %12.6f %12.6f", CX, CY, CZ }' >! $tempfile
	set new_missets = `cat $tempfile`
	rm -f $tempfile >& /dev/null
	
	# retrieve missets for FIRST image in run
	#set new_missets = `nawk '/Refined Orientation Angles/{getline; getline; missets=$0} /Processing Image/ && missets!=""{print missets; exit}' ${logfile}mosflm.log`

	if($#new_missets == 3) then
	    # compute RMS shift from starting orientation

	    # compute change in orientation from from previous values
	    set Delta_orient = `echo $new_missets $missets | nawk '{printf "%.3f", sqrt(((($1-$4)^2)+(($2-$5)^2)+(($3-$6)^2))/3)}'`
	    if("$Delta_orient" != "0.000") then
		echo "changed ${Delta_orient}$DEG"
	    else
		echo "unchanged."
	    endif
	
	    # compute "shift" in missetting angles since last run
	    set shift_orient = `echo $Delta_orient 0.03 | nawk '{printf "%d", $1/$2}'`
    	else
	    echo "unreadable! "
	    set mosflm_status = "no_missets"
	endif
	# these "new" missets will be "previous missets" for the next run
	set missets = ( $new_missets )

	# new mosaicity
	echo -n "mosaicity   "
	
	# check mosaicity
	# flailing refinement will give REALLY small mosaicities
	cat ${logfile}mosflm.log |\
	nawk '/Mosaic spread/{getline;if($1 == "New"){\
	    if($NF < 0.01){print $NF}}}' | sort -n >! $tempfile
	set temp = `cat $tempfile | head -1`
	rm -f $tempfile
	if("$temp" != "") then
	    echo "negative! $temp"
#	    set mosflm_status = "bad_mosaic"
	else
	    # get mosaicity
	    cat ${logfile}mosflm.log |\
	    nawk '/Mosaic spread/{getline; if($1 == "New"){print $NF}}' |\
	    nawk '{avg += $1; ++n;v[n]=$1} \
	    max+0<$1 {sec=max; max = $1}\
	    END{if(n){avg/=n;\
	        for(i=1;i<=n;++i){ms += (v[i]-=avg)^2};\
	    print avg, sqrt(ms/n), max, sec}}' |\
	    cat >! $tempfile
########    # average
########    set new_mosaic = `nawk '{print $1}' $tempfile`
	    # average + 1sd
	    set new_mosaic = `nawk '{print $1+$2}' $tempfile`
########    # largest (refined value)
########    set new_mosaic = `nawk '{print $3}' $tempfile`
########    # 2nd largest
########    set new_mosaic = `nawk '{print $NF}' $tempfile`
	    if($#new_mosaic == 1) then
		# determine change in mosaicity
		set Delta_mosaic = `echo $new_mosaic $mosaic | nawk '{printf "%.3f", sqrt(($1-$2)^2)}'`
		if("$Delta_mosaic" != "0.000") then
		    echo "changed ${Delta_mosaic}$DEG"
		else
		    echo "unchanged."
		endif
		
		# now check for oscillating refinement
		if(! $?mosaic_history) set mosaic_history = ""
		set mosaic_history = `echo " $mosaic $mosaic_history " | nawk 'BEGIN{RS=" "} NF==1{++n} n<7'`
		set Delta_mosaic = `echo $Delta_mosaic $new_mosaic $mosaic_history | nawk '{print $1; for(i=5;i<=NF;++i) printf "%.3f\n", sqrt(($2-$i)^2)}' | sort -n | head -1`
		
		# compute "shift" in mosaicity (integer)
		set shift_mosaic = `echo $Delta_mosaic 0.03 | nawk '{printf "%d", $1/$2}'`
	    else
		echo "unreadable! "
		#if("$fixmosaicity" != "yes") set mosflm_status = "no_mosaic"
		set shift_mosaic = 0
	    endif
	endif

	# average cell (if it were possible to refine it)
	echo -n "unit cell   "
	if($fixcell == no) then
	    # unit cell was refined, see how much it changed
	    
	    if($integrate == yes) then
		# cell is in the logfile
		cat ${logfile}mosflm.log |\
		nawk '/Processing Image/{print gather}       \
    /^          Real cell parameters/{getline; gather = $0}  \
		END{print gather}'                           | \
		nawk 'NF==6{++n; a+=$1; b+=$2; c+=$3;        \
	                       al+=$4; be+=$5; ga+=$6}       \
		  END{if(n) print a/n, b/n, c/n, al/n, be/n, ga/n}'  >! $tempfile
		set Delta_cell = `head -1 $tempfile`
		rm -f $tempfile >& /dev/null
	    else
		# cell is in the new matrix
		set Delta_cell = `nawk 'NF == 6' $outmatrix |& nawk '{for(i=1;i<=NF;++i) if($i+0 > 10) printf $i+0 " "}'`
	    endif
	    # compute %RMS shift of cell parameters
	    if(($#Delta_cell == 6)&&($#CELL == 6)) then
		set temp = 0
		foreach i ( 1 2 3 4 5 6 )
		    set temp = `echo $Delta_cell[$i] $CELL[$i] $temp | nawk '{print (($1-$2)/$2)^2 +$3}'`
		end
		set Delta_cell = `echo $temp | nawk '{printf "%.2f", sqrt($1)}'`
		if("$Delta_cell" != "0.00") then
		    echo "changed ${Delta_cell}%"
		else
		    echo "unchanged."
		endif
		
		# compute "shift" in cell
		set shift_cell = `echo $Delta_cell 0.1 | nawk '{printf "%d", $1/$2}'`
	    else
		echo "unreadable! "
		set mosflm_status = "no_cell"
	    endif
	else
	    # cell was not refined
	    echo "n/d"
	    
	    set Delta_cell = 0.00
	    set shift_cell = 0
	endif
    else
	# converge if we weren't even refining? 
	set shift_orient = 0
	set shift_mosaic = 0
	set shift_cell = 0
    endif
    
    # average distance
    echo -n "distance    "
    cat ${logfile}mosflm.log |\
    nawk '/Processing Image/{print gather}  \
	    /XTOFD/{getline; gather = $0} END{print gather}' |\
    nawk 'NF>6{++i; dist+=$4} END{if(i) print dist/i}' >! $tempfile
    set temp = `cat $tempfile`
    rm -f $tempfile >& /dev/null
    if("$temp" =~ [1-9]*) then
	# compute "shift" in distance
	set Delta_distance = `echo $temp $distance | nawk '{printf "%.2f", sqrt((($1-$2)/$2)^2)*100}'`
	if("$Delta_distance" != "0.00") then
	    echo "changed ${Delta_distance}%"
	else
	    echo "unchanged."
	endif
    
	# add shift in distance to total shift
	set shift_distance = `echo $Delta_distance 0.1 | nawk '{printf "%d", $1/$2}'`
    else
	echo "unreadable! "
	set mosflm_status = "no_distance"
    endif
    echo ""

    # ignore change in mosaicity if it's supposed to be fixed
    if("$fixmosaicity" == "yes") set shift_mosaic = 0

    # sum of all shifts (to decide when it has settled)
    @ shift = ( $shift_orient + $shift_mosaic + $shift_cell + $shift_distance )

    # ignore orientation drift if it is misbehaving
    if($?ignore_missets) then
	# orientation shift doesn't really matter anyway, as long as we
	# keep reinputing it.
	@ shift = ( $shift_mosaic + $shift_cell + $shift_distance )
    endif

else
    # error condition directly from mosflm
    echo "ERROR from MOSFLM (" $mosflm_status ")"
    
    # print error messages in file (discarding repeats)
    cat ${logfile}mosflm.log |\
    nawk '/ERROR/{print; getline; print; getline; print; getline; print}' |\
    nawk '{p=1;for(i in m){if(m[i]==$0){p=0}}; if(p==1){++n;m[n]=$0;print}}'
        
endif

###############################################################################

  ####    ####   #    #   #####     #    #    #   ####   ######  #    #   ####
 #    #  #    #  ##   #     #       #    ##   #  #    #  #       ##   #  #    #
 #       #    #  # #  #     #       #    # #  #  #       #####   # #  #  #
 #       #    #  #  # #     #       #    #  # #  #  ###  #       #  # #  #
 #    #  #    #  #   ##     #       #    #   ##  #    #  #       #   ##  #    #
  ####    ####   #    #     #       #    #    #   ####   ######  #    #   ####

###############################################################################
#   Various "contingency plans" for known problems
###############################################################################


grep "QOPEN failed - no streams left" ${logfile}mosflm.log >& /dev/null
if(! $status) then
    # this always happens with buggy mosflm
    echo "detected bug in mosflm 6.2.3 ... compensating."
#    set input = "NUSPOT OFF"
#    goto Questionaire
    set PREAMBLE = "${PREAMBLE}nNUSPOT OFF"
    set mosflm_status = "bugfix"
    set recommendation = "use keyword NUSPOT OFF"
    goto Suggest
endif


grep "DOES NOT EXIST" ${logfile}mosflm.log | grep "Image FILE " >& /dev/null
if(! $status) then
    # this happens when the specified number of images is wrong

#    set last = `nawk '/Processing Image /{print $3}' ${logfile}mosflm.log | tail -1`
#    set LastImage = `nawk '/Image FILE / && /DOES NOT EXIST/{print $3}' ${logfile}mosflm.log | tail -1`

    ls -lnL ${framedir} |&\
    nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
    nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
        $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
    nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
    cat >! ${tempfile}
    set LastImage = `nawk '{print; exit}' ${tempfile}`
    rm -f ${tempfile} >& /dev/null

    set last      = `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
    if("$last" =~ [0-9]*) then
        @ number_of_frames = (( $last - $first ) + 1 )
        echo "you lied to me.."
        set recommendation = "use image $last as the end of the wedge"
        goto Suggest
    endif
endif

# catch explicit kill
if((("$mosflm_status" == "1")||("$mosflm_status" == "141"))&&(! $?AUTO)) then
    # no need for darastic action
    if($?DISPLAY && "$Interactive" == "PLOT") then
	set temp = "$DISPLAY"
    else
	set temp = `whoami`
    endif
    echo "killed by $temp..."
    set mosflm_status = "killed"
    set input = ""
    goto Questionaire
endif


if($mosflm_status =~ [a-z]*) then
    # Elves detected a problem (mosflm exited with a 0)
endif


# do some reading/interpretation of error messages?
grep "BGSIG too large" ${logfile}mosflm.xlog >& /dev/null
if(! $status) then
    # this usually happens when the resolution is too ambitious
    echo "resolution is probably too ambitious."
endif

if("$mosflm_status" != 0) then
#    unset LAST_RUN
endif
#
############################################################
# sumarize Refinement results    (regardless of success)   #
############################################################
if((-e ${logfile}mosflm.xlog)) then
    # replot refinement stuff
    echo ' $TABLE: Elven plots:'				>> ${logfile}mosflm.xlog
    echo ' $GRAPHS:Unit Cell (deviation):A:1,2,3,4,5,6,7:'	>> ${logfile}mosflm.xlog
    echo ':Crystal Orientation (deviation):A:1,8,9,10:'		>> ${logfile}mosflm.xlog
    echo ':Detector Orientation (deviation):A:1,11,12,13:'	>> ${logfile}mosflm.xlog
    echo ':Beam Center (deviation):A:1,14,15:'			>> ${logfile}mosflm.xlog
    echo ':Distance:A:1,16:'					>> ${logfile}mosflm.xlog
    echo ':X-Y Scale:A:1,17: $$'				>> ${logfile}mosflm.xlog
    echo 'Frame A B C alpha beta gamma around_x-ray_beam around_axis_phi-X-beam around_phi_axis aournd_beam aournd_horiz aournd_vert x_beam y_beam distance x-y_scale $$' >> ${logfile}mosflm.xlog
    echo ' $$'							>> ${logfile}mosflm.xlog
    cat ${logfile}mosflm.log |\
    nawk '/Processing Image/{f=$3}  \
/^          Real cell parameters/{getline; a[f]=$1; b[f]=$2; c[f]=$3; al[f]=$4; be[f]=$5; ga[f]=$6 }  \
          /Refined Orientation Angles/{getline; getline; Cx[f]=$1; Cy[f]=$2; Cz[f]=$3}  \
          /CCOM:/{Dx[f]=$NF}  \
          /XCEN    YCEN/{getline; Bx[f]=$1; By[f]=$2; xtf[f]=$4; Sy[f]=$5; Dh[f]=$6/100; Dv[f]=$7/100}  \
        END {n=0; for(f in a){++n;} \
         for(f in a){A+=a[f]/n; B+=b[f]/n; C+=c[f]/n; Al+=al[f]/n; Be+=be[f]/n; Ga+=ga[f]/n}; \
         for(f in a){CX+=Cx[f]/n; CY+=Cy[f]/n; CZ+=Cz[f]/n; DX+=Dx[f]/n; DH+=Dh[f]/n; DV+=Dv[f]/n; }; \
         for(f in a){BX+=Bx[f]/n; BY+=By[f]/n}; \
    	 for(f in a){printf "%3d %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",\
	     f, a[f]-A, b[f]-B, c[f]-C, al[f]-Al, be[f]-Be, ga[f]-Ga,\
	     Cx[f]-CX, Cy[f]-CY, Cz[f]-CZ, Dx[f]-DX, Dh[f]-DH, Dv[f]-DV, Bx[f]-BX, By[f]-BY, xtf[f], Sy[f]} }' |\
    sort -n							>> ${logfile}mosflm.xlog
    echo ' $$'							>> ${logfile}mosflm.xlog
    
    # extend to CCP4 4.x Java plot HTML format
    cat << EOF-javacise >! ${tempfile}javacize
#! $nawk -f
#
#	convert "ordinary" xloggraph input to CCP4 4.x Java graphs
#
#
BEGIN{
    if(! CBIN) CBIN = ENVIRON["CBIN"]

    print "<html><pre>"
}

/<html>/{already_html=1}
already_html==1{print; next}

\$1 ~ /^\\\$TABLE/{
    line=\$0; \$1= ""; print; \$0=line;
    print "<applet width=\\" 700\\" height=\\" 300\\" code=\\"JLogGraph.class\\""
    print "codebase=\\""CBIN"\\"><param name=\\"table\\" value=\\""
    table = 5
}

{
    print;
    for(i=1;i<=NF;++i) if(\$i=="\$\$") {--table}
}

table == 1{
    --table;
    print "\\"><b>For inline graphs use a Java browser</b></applet>";
}

END{print "</pre></html>"}

EOF-javacise

    # add the HTML tags in the appropriate places
    nawk -f ${tempfile}javacize ${logfile}mosflm.xlog >! ${logfile}mosflm.html

    # clean up
    rm -f ${tempfile}javacize >& /dev/null
endif

#
# use bell to signal completion
if(! $?AUTO) echo -n "$BELL"
echo ""


Auto_Step:
###############################################################################

   ##    #    #    ##    #        #   #  ######  ######
  #  #   ##   #   #  #   #         # #       #   #
 #    #  # #  #  #    #  #          #       #    #####
 ######  #  # #  ######  #          #      #     #
 #    #  #   ##  #    #  #          #     #      #
 #    #  #    #  #    #  ######     #    ######  ######


  ####   #    #   #####  #####   #    #   #####
 #    #  #    #     #    #    #  #    #     #
 #    #  #    #     #    #    #  #    #     #
 #    #  #    #     #    #####   #    #     #
 #    #  #    #     #    #       #    #     #
  ####    ####      #    #        ####      #

###############################################################################
# finally, decide what to do next
#
#   The following procedure defines the "go auto" protocol of refinement
#   We have tried to make it as universal a procedure as possible, but
#   it still has a lot of shortcomings.
#   As always, the best advise is to know what you are doing and program
#   your own procedure in a batch file, like this:
#   Wedger -1 refine fixcell    >! Wedger.log
#   Wedger -1 refine no fixcell >> Wedger.log
#   Wedger -1 integrate fixcell >> Wedger.log
#   etc.
#
#   notes to self:
#   with:				we get new:
#     integ  nopostref nousebeam	dist beam
#     integ  nopostref   usebeam	dist beam 
#     integ    postref nousebeam	dist beam mosaic GAIN
#     integ    postref   usebeam	dist beam mosaic GAIN
#   nointeg    postref nousebeam	dist beam mosaic 
#   nointeg    postref   usebeam	dist beam mosaic 
#
#
###############################################################################
if(! $?recommendation) set recommendation

# never "finish" with an emergency-low resolution
if("$res_choice" == "backoff") unset LAST_RUN

if("$mosflm_status" == 0) then
    # Celebrate!

    echo -n "Ding! "
    if($integrate == yes) then
    else
    endif

    # no errors occured, increase the degrees of freedom
    set recommendation = "$0"
    
    # run is no longer "new"
    if($?NEW) unset NEW
    @ Successes = ( $Successes + 1 )
    
    if($integrate == yes) then
	#######################################
	#  Successful Integration             #
	#######################################
	echo "Integration was successful! "
	echo ""
	echo "$mtzout contains your spot intensities (ready for scaling)."

	if(($?BURSTMODE)&&("$res_choice" != "backoff")) then
	    echo "Burst mode set.  Further iterative mosflm runs will not be done."
	    echo ""
	    set LAST_RUN
	    goto scale_and_merge
	endif

	if(($?AUTO)&&($Cycle == $MAX_Cycles)) then
	    echo "Maximum number of automatic cycles exceeded.  One last time..."
	    echo ""
	    set LAST_RUN
	    goto Suggest
	endif

	if($?LAST_RUN) then
	    echo -n "Last run complete.  "
	    if((! $?BURSTMODE)&&(! $?ONCEONLY)) echo "Measurements are as good as elves can make them."
	    echo ""
	    goto scale_and_merge
	endif
		
	# if Postrefinement was turned off, try returning to "pure" postrefinement
	if(($postref == no)&&($number_of_frames > 1)) then
	    echo "Might want to refine again."
	    set postref = yes
	    set integrate = no
	    set recommendation = "$recommendation nointeg postref"
	    goto Suggest
	endif
	
#	# if USEBEAM was turned off, try turning it back on again.
#	if(($usebeam == no)&&($shift_mosaic == 0)) then
#	    echo "But, the "\"usebeam\"" option will allow parameters to be refined for each frame."
#	    set usebeam   = yes
#	    set fixcell   = yes
#	    set fixyscale = yes	    
#	    set last_changed = usebeam
#	    set recommendation = "$recommendation integ usebeam fixcell fixyscale"
#	    goto Suggest
#	endif
	
	# see if resolution limit is dangerously optimistic
	set test = `echo $res_limit $hires | nawk '{print ($1^3 > 3 * $2^3)}'`
	if($test &&("$res_choice" != "user")) then
	    # current resolution covers more than 3x the useful reciprocal-space volume

	    # pick an optimistic, but reasonable limit (1.5x the reciprocal-space volume of res_limit)
	    set newRES = `echo $res_limit 1.5 | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`

	    echo ""
	    echo "Resolution limit of $hires $ANG looks far too optimistic."
	    echo "this can cause mosflm to hang."
	    echo "Recomend you reduce the resolution limit to $newRES ${ANG}."
	    echo ""
	    set hires = $newRES
	    set res_choice = mosflm
	    set recommendation = "$recommendation $hires A"
	    goto Suggest
	endif

	# Cell fixed, unfixed, or even refinable
	if(($fixcell == no)||($SG_number < 134)||($true_cell == yes)) then
	    # cell is either free, or unwise to refine while integrating
	
#	    if($true_cell == yes) echo "-fixcell was specified on command line, cell will remain fixed."
	
	    if($shift == 0) then
		# Convergence reached with cell as free as it's gonna get.
		
		echo "All refinable parameters are stable! "
		if("$res_choice" == "backoff") then
		    # restore resolution range
		    set res_choice = $SAVE_res_choice
		    if(("$res_choice" == "user" || "$res_choice" == "script")&&("$SAVE_hires" != "")) then
			set hires = $SAVE_hires
			echo "now try returning to $hires $ANG"
			set recommendation = "$recommendation $hires A"
		    else
			echo "now try optimizing resolution limit."
			# all bets are off, use integration logs to re-establish resolution limit
			set res_choice = mosflm
			set recommendation = "$recommendation $hires A"
		    endif
		    goto Suggest
		endif
		
		if($true_cell == yes) then
		    # We are DONE! 
		    echo "Spots should now be ready for scaling and mergeing."
		    
		    set LAST_RUN
		    set recommendation = "$recommendation integ -fixcell"
		else
		    echo "Now integrate again, with the cell constant over all frames."
		    set integrate = yes
		    set fixcell = yes
		    set true_cell = yes
		    set recommendation = "$recommendation integ -fixcell"
		endif		
	    else
		# Orientation will not be properly propagated to next run if we continue 
		# integrating, but everything else will
		if(("$shift_orient" == 0)&&($postref == yes)) then
		    # orientation is stable
		
		    # might as well keep refining mosaicity, distance, and cell here
		    echo "Integrate again, to keep refining against all frames."
		    set integrate = yes
		    set recommendation = "$recommendation integ refine"
		else
		    # mean orientation shifted significantly during the run
		
		    echo "Mean crystal orientation differs from input."
		    echo "Go back to refinement again, to update the orientation matrix."
		    set integrate = no
		    # leave cell refinement status where it is, absorb orientation only
		    set fixcell   = yes
		    
		    # danger of oscillation here?
		    #
		    #	the average orientation for a subset (refinement) is not, necessarily
		    #	the same as for all frames, but we can only update a matrix in
		    #	refinement
		    #
		    #if($reinput_missets == yes) then
		    if(1) then
			# tell refinement NOT to converge, just absorb orientation into matrix
			if($?REFINE_NO_CONVERGE) then
			    if($REFINE_NO_CONVERGE > 0) then
				# try to maximize segment size
				set mosflm_postref_segs = 6
				set frames_per_segment = 5
			    else
				echo "Never mind, we've done this too many times already."
				# don't go back to refinement, keep integrating
				set integrate = yes
				
				# orientation drift will be ignored (above)
				set ignore_missets
				# and missetting angles will NOT be reset (above)
				#set reset_missets = no
			    endif
			else
			    # count down, only do this a few times
			    set REFINE_NO_CONVERGE = 3
			endif
		    endif

		    set recommendation = "$recommendation nointeg fixcell"
		endif
	    endif
	else
	    # Cell was fixed, but symmetry permits refining it while integrating
	    echo "Consider allowing the cell to refine next time."
	    set fixcell = no
	    set last_changed = nofixcell
	    set recommendation = "$recommendation nofixcell "
	endif
	
    else
	#######################################
	#  Successful Refinement              #
	#######################################
	echo "Refinement was successful! "
	echo ""
	
	set recommendation = "mv $outmatrix $best_matrix ;$recommendation"

	# try expanding wedges? 
	@ temp = ( $mosflm_postref_segs * $frames_per_segment )
	if(( $temp < (($last - $first) / 3 ) )&&($temp < 20)) then
	    echo "You might want to refine more frames."
	    if($mosflm_postref_segs < 2 ) then 
		set mosflm_postref_segs = 2
	    else
		@ frames_per_segment = ( $frames_per_segment + 1 )
	    endif
	else
	    # do not exit postrefinement until things have converged

	    if(($?REFINE_NO_CONVERGE)) then
		# absorbed last integration's mean missetting angles into newmatrix
		
		echo "return to integration, with this new orientation matrix."
		# don't do this too many times, can oscillate
		@ REFINE_NO_CONVERGE = ( $REFINE_NO_CONVERGE - 1 )
		# don't put THESE missetting angles into the integration
		set reinput_missets = no
		set integrate = yes
		
		set recommendation = "$recommendation integ"
		    
		goto Suggest
	    endif
		
	    #if(($reinput_missets == no)&&(($shift_distance + $shift_mosaic + $shift_cell) == 0)&&($failure_count < 2)) then
	    if(0) then
		# absorb new missetting angles into next matrix
		echo "absorb the missetting angles into the next run."
		set reinput_missets = yes
		set fixcell         = yes
		
		set recommendation = "$recommendation ${logfile}mosflm.log fixcell"
		    
		goto Suggest
	    endif
		
	    if($shift == 0) then
		# Converged!! 
		
		echo -n "Refinement seems stable, "
		
#		if("$res_choice" == "backoff") then
#		    # restore original resolution range
#		    set res_choice = $SAVE_res_choice
#                    if(("$res_choice" == "user" || "$res_choice" == "script")&&("$SAVE_hires" != "")) then
#                        set hires = $SAVE_hires
#                        echo "now try refining to $hires $ANG"
#                        set recommendation = "$recommendation $hires A"
#                    else
#                        echo "now try optimizing resolution limit."
#                        set recommendation = "$recommendation $hires A"
#                    endif
#                    goto Suggest
#		endif
		
		if($fixcell == yes) then
		    # refine cell if we have enough frames to do so
		    if(1 || (($wedge_width >= 45)||($SG_number >= 143))&&($true_cell != "yes")) then
			# refining the cell is technically reasonable, and user approves
			echo "consider unfixing the unit cell next time."
			set fixcell = no
			set recommendation = "$recommendation nofixcell"
		    else
			if($true_cell != "yes") echo "but there are not enough frames to refine the cell in $SG."
			echo "Go ahead and integrate with this cell."
			set integrate = yes
			set recommendation = "$recommendation integ fixcell"
		    endif
		else
		    # cell was not fixed, and matrix is good! 
		    echo "Try integrating next! "
		    set integrate = yes
		    set fixcell   = yes
		    set recommendation = "$recommendation integ fixcell"
		endif
	    else
		# not converged yet, keep doing whatever we were doing
		echo "Parameters are still drifting.  Refine again."
		
		set recommendation = "$recommendation refine nointeg"
	    endif
	endif

	# count if we have done n-round burst
	if(($?BURSTMODE)&&("$res_choice" != "backoff")) then
	    if($BURSTMODE == 1) then
		set integrate = yes
		# should fix the cell we just refined
		set fixcell = yes
		set LAST_RUN
		set recommendation = "$recommendation integ"
	    else
		@ BURSTMODE = ( $BURSTMODE - 1 )
	    endif
	endif

    endif
else

    echo -n "Dang! $BELL "
#    echo ""

    ###################################
    # MOSFLM failed somehow, back off #
    ###################################

    # should probably look at preds next time
    set Interactive = "PLOT"
    unset LAST_RUN

    # decide how to best deal with this problem
    set recommendation = "$0"
    
    
    # First, look for problems we know how to fix
    grep -i "try" ${logfile}mosflm.log |\
    egrep "NADD|WIDTH|more images|changed by more than 10" >! ${tempfile}
    set test = `cat $tempfile | wc -l`
    rm -f $tempfile
    
    if($test != 0) then
	# mosflm suggested "more images"
	
	# see if POSTREF WIDTH is already in use
	echo "$EXTRA_REFINE_CARDS" |\
	nawk 'BEGIN{RS="n"} {print $0}' |\
	nawk '/^POST/' |\
	egrep " WIDTH | ADD " >! ${tempfile}
	set test = `cat $tempfile | wc -l`
	rm -f ${tempfile}
	
	if("$test" == 0) then
	    set addsize = `echo "$first $last" | nawk '{n=30;if($2-$1 < n){n=$2-$1}; print n}'`

	    # try the POSTEF WIDTH CARD
	    echo "Try constraining the cell in groups of $addsize frames."

	    echo "$EXTRA_REFINE_CARDS" | nawk 'BEGIN{RS="n"} {print}' |\
	     nawk 'NF!=0' >! ${tempfile}
	    echo "POSTREF ADD $addsize" >> $tempfile
	    set EXTRA_REFINE_CARDS = `nawk 'BEGIN{ORS="n"} NF != 0' $tempfile`
	    rm -f $tempfile

	    set recommendation = "Put "\""POSTREF ADD $addsize"\"" in $scriptname"		    
	    goto Suggest
	endif
    endif

    # bad image? 
    grep "ERROR READING IMAGE FILE" ${logfile}mosflm.log >& /dev/null
    if(! $status) then
	
	cat ${logfile}mosflm.log |\
	nawk '$3 == "Filename:" {file = $NF} /ERROR READING IMAGE FILE/{print file}' |\
	cat >! ${tempfile}
	set temp = `cat ${tempfile}`
	rm -f ${tempfile}

	# get the number of this file, and eliminate it from processing
	set newlast = `basename $temp .$ext | nawk '{print substr($1,length($1)-2)-1}'`

	if(($newlast > 0)&&($newlast < $last)) then
	    echo "$temp seems to be a bad frame. "
	    echo "Please either repair it, or delete it. "
	    echo "Try ending the wedge at frame $newlast"
	    set last = $newlast
	    @ number_of_frames = ( ( $last - $first ) + 1 )
	    
	    set recommendation = "$recommendation $number_of_frames frames"		    
	    goto Suggest
	endif
    endif

    # ridiculously high resolution can cause lots of problems
    # figure out pessimistic outer resolution limit from mosflm log.
    cat ${logfile}mosflm.log |\
    nawk 'h==0 && /Analysis as a function of resolution./{h=1;getline;\
                   print $3, $4, $5, $6, $7, $8, $9, $10} \
          /^  <I\/sigma>/{print $2, $3, $4, $5, $6, $7, $8, $9}' |\
    nawk 'NR==1{for(i=1;i<9;++i){res[i]=$i};++n} \
          NR!=1{for(i=1;i<9;++i){signal[i]+=$i;++count[i]}}\
          END{if(n) for(i=8;i>0;--i){print res[i], signal[i]/count[i]}}' |\
    sort -nr >! ${tempfile}res_limit
    set res_limit = `nawk '$NF > 2.0 {print $1+0} $NF<=1 {exit}' ${tempfile}res_limit | tail -1`
    rm -f ${tempfile}res_limit >& /dev/null
    if("$res_limit" != "") then
	#echo "average I/sig drops below 2 at $res_limit ${ANG}."
    endif
 
    # this seems to happen when refinement drifts a LOT
    grep "lies outside currently defined standard profile areas" ${logfile}mosflm.log >& /dev/null
    if(! $status) then
        # this usually happens when the resolution is too ambitious
	if("$res_limit" == "") then
	    # must have been refining...
	    if($?edge_res) then
		# is this a good idea?
#		set res_limit = `echo $edge_res $hires | nawk 'NF==2 && $1+0>$2+0 && $1<20{print $1}'`
	    endif
	endif
	if("$res_limit" == "") then
	    # just reduce it a bit
	    set res_limit = `echo $hires 0.9 | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`
	endif

	# pick a resolution limit that covers 0.9x the reciprocal space volume of res_limit
	set newRES = `echo $res_limit 0.9 | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`

        # suggest a more reasonable limit
	set test = `echo $hires $newRES | nawk 'NF==2{print ($1<$2)}'`
	if ("$test" == 1) then
            echo "$hires ${ANG} might be overly optimistic."
            echo "Try using $newRES ${ANG} to be safe"
	    set RES_TROUBLE

            if("$res_choice" == "user") then
        	if($?AUTO) echo "but, you insisted on ${hires}A ..."
            else
        	set hires = $newRES
        	set res_choice = mosflm
		set recommendation = "$recommendation ${hires}A"
        	goto Suggest
	    endif
        endif
    endif
    
    # excessive background rejection implies resolution too high
    grep "rerun with a larger value for BGSIG" ${logfile}mosflm.log >& /dev/null
    if(! $status) then
        # this usually happens when the resolution is too ambitious

        # pick a resolution limit that covers 0.9x the reciprocal space volume of res_limit
        set newRES = `echo $res_limit 0.9 | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`

        # suggest a more reasonable limit
        set test = `echo $hires $newRES | nawk 'NF==2{print ($1<$2)}'`
        if ("$test" == 1) then
            echo "$hires ${ANG} might be overly optimistic."
            echo "Try using $newRES ${ANG} to be safe"

            if("$res_choice" == "user") then
                if($?AUTO) echo "but, you insisted on ${hires}A ..."
            else
                set hires = $newRES
                set res_choice = mosflm
                set recommendation = "$recommendation ${hires}A"
                goto Suggest
            endif
        endif
    endif


    # could there be some other crashes resulting from too high a resolution limit?

    # pick a resolution limit that covers 1.0x the reciprocal space volume of res_limit
    set newRES = `echo $res_limit 1.0 | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`
    set newRES = `echo $newRES $detector_res_limit | nawk 'NF==2 && $1<$2{$1=$2} {print $1}'`

    set test = `echo $hires $newRES | nawk '{print ($1 < $2)}'`
    if($test) then
	# mosflm failed and
	# current resolution covers more than 1.0x the useful reciprocal-space volume

	# suggest a more reasonable limit
	echo "$hires ${ANG} might be overly optimistic."
	echo "Try using $newRES ${ANG} to be safe"

	if("$res_choice" == "user") then
	    if($?AUTO) echo "but, you insisted on ${hires}A ..."
	else
	    set hires = $newRES
	    set res_choice = mosflm
	    set recommendation = "$recommendation ${hires}A"
            goto Suggest
	endif
    endif

    
    # keep track of failures
    @ failure_count = ( $failure_count + 1 )
    if("$mosflm_status" == "$last_mosflm_failure") @ chronic_failures = ( $chronic_failures + 1 )

    # have a look at predictions (indirectly)
    nawk '$1 ~ /^[\*\-]/ && ! /[a-z,\.]/ && /[0-9]/' ${logfile}mosflm.log >! ${tempfile}
    set temp = `ls -ln $tempfile | nawk '{print $5}'`
    rm -f $tempfile >& /dev/null
    if("$temp" < 10) then
	# the average peak-area pixel value is unusually low
	echo "Spot profiles were not even made."
	echo ""
	set temp = `nawk -v wave=$wavelength 'BEGIN{print 12398.4245/wave}'`
	echo "crystal-to-film     = $distance mm"
	echo "x-ray wavelength    = $wavelength $ANG / $temp eV"
	echo "direct beam spot at   $beam_center (in mosflm window)"
	echo "detector 2theta     = $two_theta $DEG"
	echo "unit cell           = $CELL"
	echo "matrix file         = $inmatrix"
	echo ""
	set temp = "Yes"
	echo "Are you sure these alignment parameters are correct? [$temp] $BELL"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo "$temp"
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = `echo "$in"`
	endif
	if(("$temp" =~ [Nn]*)&&($#temp == 1)&&(! $?AUTO)) then
	    # duh...
	    echo "Uhh, okay.  What are the correct parameters? "
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	    set input = "$temp"
	    goto Questionaire
	endif
	if("$temp" !~ [Yy]*) then
	    set input = "$temp"
	    if("$input" =~ [Nn][Oo]) set input = ""
	    goto Questionaire
	endif
    endif

    if("$mosflm_status" == "bad_preds") then
	echo "Spots are too far off their predictions."
	echo "                       (best is $resid[4] mm)"
    endif


#    if(($Successes == 0)&&("$SG_choice" == "auto")) then
#        # we may have just picked a bad space group
#        echo "maybe Bravais lattice is not really ${BRAV}?  Autoindex again."
#
#        set recommendation = "$0 index"
#        goto Suggest
#    endif

    if($chronic_failures > 3) then
	echo "${chronic_failures}th occurence of this problem."
	
	# try re-autoindexing
	if(($SG_number < 75)&&(! $?REINDEXED)) then
	    echo "Try autoindexing again."
	    set REINDEXED
	    set KEEP_SG
	    set recommendation = "$recommendation -new index"
	endif
	
	# try indexing again?
	if("$SG_choice" == "auto" && "$SG" != "P1") then
	    echo "Perhaps $BRAV is not the Bravais lattice.  Autoindex again."

	    set recommendation = "$recommendation index"
	    goto Suggest
	endif
	
	# roll back into list of matricies
	
	if($number_of_frames > 5) then
	    echo "Try reducing the size of the wedge."
	    set temp = `nawk '/Filename:/ {print $NF}' ${logfile}mosflm.log | grep ".$ext" | tail -1`
	    set newlast = `basename $temp .$ext | nawk '{print substr($1,length($1)-2)-1}'`
	    if((-e "$temp")&&($newlast > ($first + 2))&&($newlast < $last)) then
		# legitimate last frame loaded
		set last = $newlast
		@ number_of_frames = ( ( $last - $first ) + 1 )
	    else
		# just try cutting it in half
		@ number_of_frames = ( $number_of_frames / 2 )
	    endif
	    
	    set recommendation = "$recommendation $number_of_frames"
	    goto Suggest
	else
	    echo "The Wedger elves are confounded! "
	    echo ""
	    echo "Please check and make sure they have the right"
	    echo "wavelength, distance, two-theta, cell, etc."
	    echo ""
	    echo "You should check that spots are actually being "
	    echo "predicted in an interactive mosflm run, and give "
	    echo "THAT matrix to a noninteractive Wedger run."
	    echo "If you STILL have probelms, you need to know"
	    echo "more than we do.  Start reading manuals."
	    goto Cleanup
	endif
    endif
    
    # remember last failure message
    set last_mosflm_failure = "$mosflm_status"
    
    # 
    set last_changed = failure

    # No-brainers:
    if($reinput_missets == yes) then
	# don't absorb mean missetting angles into next matrix, pretty dangerous
	echo "Don't use the misseting angles from ${logfile}mosflm.log this time."
	set reinput_missets = no
	set recommendation = "$recommendation -new"		    
#	goto Suggest
    endif

#    if(usebeam == yes) then
#	# Definitely don't use beam if we are having problems
#	echo "Turn off the "\"usebeam\"" feature until refinement has converged."
#	set usebeam = no
#	set recommendation = "$recommendation nousebeam"
#	goto Suggest
#    endif

    if($fixcell == no) then
	# don't mess around with cell if we are having problems
	echo "Try fixing the cell this time."
	set fixcell = yes
	set recommendation = "$recommendation fixcell"
#	goto Suggest
    endif

    set temp = `echo $mosaic $osc | nawk '{printf "%d", $2/($1+0.001)}'`
    if($temp > 5) then
	# reset mosaic spread if we are having problems
	echo "Use a wider mosaic spread."
	set temp = `echo $osc | nawk '{print 0.8*$1}'`
	set recommendation = "$recommendation mosaic $temp"
	if("$fixmosaicity" != "yes") set mosaic = "$temp"
#	goto Suggest
    endif

    if($integrate == yes) then
	# Died while trying to integrate
	echo "Full integration may have been premature, go back to refinement."
	set integrate = no
	set postref   = yes
	set recommendation = "$recommendation nointeg"
    else
	# Died during POSTREFINEMENT!, uh oh.
	
	if(("$res_choice" != "backoff")&&("$mosflm_status" != "fixed")) then
	    # maybe we should reduce resolution to shure up refinement?
	    set SAVE_hires = $hires
	    set SAVE_res_choice = $res_choice
	    set res_choice = backoff
	    # pick a resolution avoiding ice rings
	    set hires = `echo $hires | nawk '{printf "%.1f", (0.3*$1^-3)^(-1/3)}' | nawk '$1<3.9 && $1>2.5{$1 = 3.9} {print}'`
	
	    echo "Try refining low-resolution spots only."
	    if("$res_choice" == "user" || "$res_choice" == "script") then
		# user-specified res choice should always be restored
		set res_choice = backoff
	    endif
	    set recommendation = "$recommendation $hires A"
	    unset LAST_RUN
	    goto Suggest
	endif
	
	# no adjustable cell (crystal slippage?)
	if($frames_per_segment > 3 ) then
	    echo "Try reducing your refinement wedge size."
	    @ frames_per_segment = ($frames_per_segment / 2 )
	else
	    if($mosflm_postref_segs > 1) then
		echo "Try reducing your number of postref blocks."
		set mosflm_postref_segs = 1
	    else
		# If we get here, we were doing the most conservative
		# postref possible:
		# fixed cell
		# fixed yscale
		# no usebeam
		# 1 block of 2-3 frames
		#
		echo "Most basic postref run is not working."
		echo ""
		
		# see if there were other possibilities for a matrix
		foreach mat ( $matrixfiles )
		    foreach bad ( $badmatrix $inmatrix $outmatrix )
			if("$mat" == "$bad") set mat = ""
		    end
		    if(-e "$mat") then
			# might be worth a try
			set badmatrix = `echo $badmatrix $inmatrix $outmatrix`
			echo "Try starting over again with $mat"
			set badmatrix = `echo $badmatrix $inmatrix $outmatrix`

			set recommendation = "mv $inmatrix ${inmatrix}.bad;$recommendation $mat -new"
			goto Suggest
		    endif
		end

		# no other matricies available.  Make one?
		echo "Either some major parameter is wrong (distance?, wavelength?)"
		echo "or the orientation is too far off to converge."
		if((! $?AUTO)||("$SG_choice" == "auto")) then
		    echo "Autoindex again."

		    set set recommendation = "mv $inmatrix ${inmatrix}.bad;$recommendation $FirstImage -new index"
		    set lastlog = ""
		else
		    # automatic refinement is no longer appropriate, user should look at graphics
		    echo ""
		    echo "You should check that spots are"
		    echo "*** ACTUALLY BEING PREDICTED *** "
		    echo "in an interactive mosflm run, and give "
		    echo "THAT matrix to a noninteractive Wedger run."
		    echo "If you STILL have probelms, then you need"
		    echo "to know more than we do.  Start reading manuals."
		    goto Cleanup
		endif
	    endif
	endif
    endif
endif


Suggest:
###############################################################################

  ####   #    #   ####    ####   ######   ####    #####     #     ####   #    #
 #       #    #  #    #  #    #  #       #          #       #    #    #  ##   #
  ####   #    #  #       #       #####    ####      #       #    #    #  # #  #
      #  #    #  #  ###  #  ###  #            #     #       #    #    #  #  # #
 #    #  #    #  #    #  #    #  #       #    #     #       #    #    #  #   ##
  ####    ####    ####    ####   ######   ####      #       #     ####   #    #

################################################################################
#
#   Output recommendations to user
#
#

# on CCD, this is probably always the case.
if(($fixyscale == no)&&(("$ext" == "img")||("$SCANNER" =~ *CCD*))) then
    echo "On the CCD, you should probably fix the X-Y scale."
    set recommendation = "$recommendation fixyscale"
    set fixyscale = yes
endif

# suggest convergence run to user
echo ""
echo "Recommend:"
echo "$recommendation" | nawk 'BEGIN{RS=";"}{print $0}'

if($?ONCEONLY) then
    goto UpdateScript
endif

echo ""
set temp = "Yes"
echo "Do this now? [${temp}/go auto]?"
echo -n "$PROMPT"
if($?AUTO) then
    echo "$temp"
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
echo ""
if(("$temp" =~ [Gg][Oo]*)||("$temp" =~ [Aa][Uu][Tt][Oo]*)) then
    set AUTO
    set Interactive = "#PLOT"
    echo "Rock 'n Roll! "
    set CATCH_USER
    echo "(We will beep if something bad happens ...)"
    goto Converge
endif
if("$temp" =~ [Yy]*) goto Converge
if(("$temp" !~ [Nn]*)||($#temp > 1)) then
    set input = "$temp"
    goto Questionaire
endif

set temp = "quit"
echo "What do you want to do? [$temp]?"
echo -n "$PROMPT"
echo -n "$BELL"
set in = ( $< )
if("$in" != "") set temp = ( $in )
if("$temp" != "quit") then
    set input = "$temp"
    goto Questionaire
endif

echo ""
echo "Okay, bye! "
goto Cleanup

Converge:
set Convergeing
set last_mosflm_status = "$mosflm_status"

echo "$recommendation" | grep $outmatrix >& /dev/null
if(! $status) then
    # moving the matrix was suggested
    echo "moving $outmatrix to $best_matrix ..."
    if(-e "$best_matrix") mv $best_matrix ${best_matrix}.old
    mv $outmatrix $best_matrix
    # make this the input next time
    set inmatrix = $best_matrix
endif

echo "$recommendation" | grep index >& /dev/null
if(! $status) then
    # autoindexing was suggested
    set autoindexing
    
    # make a fresh start
    set lastlog = ""
    set chronic_failures = 0
    set failure_count    = 0
    set last_mosflm_failure = indexing
    set argv = ( $command_line_argv )
    
    if(! $?KEEP_SG) then
	# disqualify everything in this Bravais lattice
	set wrongSGs = ( $wrongSGs $BRAV )
	set CELL = "unknown"
	set SG   = "unknown"
    endif
    unset KEEP_SG
    
    # these sources shouldn't give us back an cell/sg. should they?
    set sources  = "$oldscripts"
    goto GetParamsFromSources
endif

echo "$recommendation" | grep "mv $inmatrix ${inmatrix}.bad" >& /dev/null
if(! $status) then
    # moving the matrix was suggested
    echo "moving $inmatrix to ${inmatrix}.bad ..."
    mv $inmatrix $inmatrix.bad 
    
    set temp = "old matrix"
    goto FindMATRIX
endif

# clear command-line args (they are now out of date)
set argv = ""
#set 0 = $temp

# Repeat the run, using last output as input
set lastlog = "${logfile}mosflm.log"
set sources = "${logfile}mosflm.log $inmatrix"

# don't read logfile if there were problems
if("$mosflm_status" != 0) set sources = "$inmatrix"

goto GetParamsFromSources
#
#
#

Cleanup:
onintr
# restore old TTY settings (for emacs sake)
test -t 1 >& /dev/null
if(! $status) then
    stty erase $oldTTYerase
endif

#restore resolution limit if we messed with it
if(("$SAVE_hires" != "")&&(-e $scriptname)&&("$mosflm_status" != "0")) then
    # restore resolution range
    set hires = $SAVE_hires
    if($?SAVE_res_choice) then
	set res_choice = $SAVE_res_choice
    endif

    echo "restoring $hires $ANG in $scriptname"
    cat $scriptname |\
    nawk -v hires=$hires '! /^RESO/{print} /^RESO/{print "RESOLUTION", hires}' |\
    cat >! ${tempfile}oldhires
    mv -f ${tempfile}oldhires $scriptname
    chmod a+x $scriptname
endif

###############################################################################
# get rid of temp files that you will never look at anyway
#
###############################################################################
if((-e "${logfile}mosflm.log")&&(! $?NORUN)&&("$mosflm_status" == 0)) then
    echo "For a detailed review of your measurement,"
    echo " have a look at ${logfile}mosflm.log and ${logfile}mosflm.html"
endif
echo "Cleaning up..."
rm -f ${tempfile}* >& /dev/null
rm -f mosflm_temp >& /dev/null
rm -f fort* >& /dev/null

if(($?NORUN)&&($number_of_frames < 2)) then
    echo "As soon as you have enough frames, "
    echo "you can edit and run $scriptname, or run $0 again."
endif

if((-e "$outmatrix")&&("$mosflm_status" == 0)&&(! $?NORUN)) then
    echo "Don't forget to mv $outmatrix $inmatrix"
    echo "before you run $0 again."
endif

if($?NO_CCP4) then
    # clean up band-aid files
    rm -f ${CLIBD}/symop.lib >& /dev/null
    rm -f ${CINCL}/environ.def >& /dev/null
    rm -f ${CINCL}/default.def >& /dev/null

    cat << EOF

From here on out, you're going to need CCP4.  Don't worry, it's free.
Get yourself a copy at:
netscape ftp://ccp4a.dl.ac.uk/pub/ccp4/
Unfortunately, you'll have to compile it. 

If, however, you have Red Hat linux, you can get an RPM from the O people at:
netscape http://origo.imsb.au.dk/~mok/linux/dist/

Good Luck.

In case this all seems like too much trouble, the raw data in $mtzout 
are now being converted to a flat text file called raw.hkl so you can 
more easily import it into some other scaling and mergeing program.
EOF
    # extract raw data to text?
    echo "   H    K    L M/ISYM BATCH      I            SIGI         IPR          SIGIPR  FRACTIONCALC  XDET         YDET           ROT            WIDTH        LP      MPART" >! raw.hkl
    ood -f ${mtzout} |\
    nawk '{for(i=2;i<=NF;++i){print $i}}' |\
    nawk 'NR > 20{printf "%s ", $1+0; ++i; if(i%16 == 0) print ""}' |\
    nawk '$1 != int($1) || $2 != int($2) || $3 != int($3) || ($1+$2+$3)==0 || ($1+$2+$3)>1000000 || ($1+$2+$3)<-1000000 {++done}  ! done {print}' |\
    nawk '{printf "%4d %4d %4d %5d %6d %12f %12f %12f %12f %12.10f %12f %12f %12f %12f %12f %4d\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16}' |\
    cat >> raw.hkl
    echo "done! "
    echo ""
endif

if($?LAST_RUN) then
    if($?NOSCALE) then
cat << EOF

Now what?
        1) review ${logfile}mosflm.log and ${logfile}mosflm.html
        2) Edit and run $mergescript, or:
	    - Use sortmtz to combine $mtzout with your other raw data files.
	    - Use scala to scale and merge the sorted data into HKLs
	    - Use truncate to convert scala's results into Fs, in mtz format.
	    - Use mtz2various.com to export Fs to various other X-ray programs.
           OR
        Use Scaler Elves to do all the above automatially. :)
	
EOF
    else  
cat << EOF

Now what?
        - review ${logfile}mosflm.log and xloggraph ${logfile}mosflm.html
        - also, view and xloggraph ${logfile}merge.log
	
        - IF THIS IS THE ONLY WEDGE OF DATA FOR THIS CRYSTAL:
	    Optimize $mergescript for scaling and mergeing $mtzout (see scala documentation)
	    (Maybe use SGsearch.com to evaluate alternative space groups.)
	    Use the CCP4 program scaleit to compare $mergefile with data from other crystals
	    Use mtz2various.com to export your Fs to various other X-ray programs.

        - IF THERE ARE OTHER WEDGES:
	    Use sortmtz to combine $mtzout with your other raw data files.
	    Use scala to scale and merge the sorted data into HKLs
	    Use truncate to convert scala's results into Fs, in mtz format.
	    Use mtz2various.com to export your Fs to various other X-ray programs.

           OR
        Use Scaler Elves to do all the above automatially. :)
	
EOF
    endif
endif

# make it a number
set mosflm_status = `echo $mosflm_status | nawk '$1~/[a-z]/{$1+=100} {print $1+0}'`
exit $mosflm_status

###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
#######################       END OF MAIN SCRIPT      #########################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
###############################################################################
# Below are a bunch of routines that were moved here to improve the readability
# of this script.




























exit
FindMOSFLM:
###############################################################################

 ######     #    #    #  #####       #    #   ####    ####   ######  #       #    #
 #          #    ##   #  #    #      ##  ##  #    #  #       #       #       ##  ##
 #####      #    # #  #  #    #      # ## #  #    #   ####   #####   #       # ## #
 #          #    #  # #  #    #      #    #  #    #       #  #       #       #    #
 #          #    #   ##  #    #      #    #  #    #  #    #  #       #       #    #
 #          #    #    #  #####       #    #   ####    ####   #       ######  #    #

###############################################################################
# Hunt for ipmosflm executable
#
###############################################################################
# $mosflm should be set to the expected location of the ipmosflm executable
# if found, The fully-qualified pathname of a working mosflm executable will 
# be returned in $mosflm.  Otherwise, $mosflm will be blank
# ($MOSFLM is used as a default name, set above, or in a script file)
#
# make sure this thing runs
if( -e "$mosflm") then
    set mosflm = `ls -lnL $mosflm |& nawk '$5>1000000{print $NF}'`
    if(-e "$mosflm") then
	set MosflmVersion = `echo "GO" | $mosflm SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
	rm -f mosflm.lp >& /dev/null
	if("$MosflmVersion" !~ [1-9]*) then
	    # no dice
	    set mosflm = ""
	    set MosflmVersion = ""
	endif
    endif
endif

# check command-line first
set i = 0
while($i < $#argv)
    @ i = ( $i + 1 )
    set file = `ls -lnLd $argv[$i] |& nawk '$5>1000000{print $NF}'`
    if((-e "$file")&&(! -e "$mosflm")) then
	# try running it
	set mosflm = "$file"
	set MosflmVersion = `echo "GO" | $mosflm SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
	rm -f mosflm.lp >& /dev/null
        if("$MosflmVersion" !~ [1-9]*) then
            # no dice
            set mosflm = ""
            set MosflmVersion = ""
        endif
    endif
end


# try the "which" command first
if(! -e "$mosflm") then
    foreach filename ( $mosflm $MOSFLM ipmosflm mosflm )
	if(! -e "$mosflm") then
	    set temp = `which $filename |& grep -v ' not in ' |& tail -1 `

	    foreach file ( $temp )
		# see if file is big enough
		set file = `ls -lnLd $file |& nawk '$5>1000000{print $NF}'`
	        if((-e "$file")&&(! -e "$mosflm")) then
		    # try running it
		    set MosflmVersion = `echo "GO" | $file SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
		    rm -f mosflm.lp >& /dev/null
		    if("$MosflmVersion" =~ [1-9]*) then
			# got one
			set mosflm = "$file"
		    else
			# no dice
			set mosflm = ""
		    endif
		endif
	    end
        endif
    end
endif

if(! -e "$mosflm") then
    # discard original suggestion, try this one
    set mosflm = "ipmosflm"
    echo -n "Looking for $mosflm ... "
    onintr CantFindMosflm
    # look down a list of standard places for the executable
    foreach place ( ./ ../ ../../ ../../../ /programs/mosflm/bin/ /programs/mosflm/ /programs/ /pxsoft/mosflm /sw/ /usr/local/bin/ /usr/local/ /usr/local/mosflm/ )
	# stop looking when we find it
	if((! -e "$mosflm")&&(-e "$place")) then

	    # look for executable files with names containing "mosflm" in $place
    	    set files = `ls -lnLrt ${place} |& nawk '! /^d/ &&($1 ~ "x")&&($5+0 > 3000000)&&($NF ~ "mosflm"){print $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`

	    foreach file ( $files )
		# see if file is big enough
		set file = `ls -lnLd ${place}$file |& nawk '$5>1000000{print $NF}'`
    		if((-e "$file")&&(! -e "$mosflm")) then
		    # try running it
		    set MosflmVersion = `echo "GO" | $file SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
		    rm -f mosflm.lp >& /dev/null
		    if("$MosflmVersion" =~ [1-9]*) then
			# got one
			set mosflm = "$file"
		    else
			# no dice
			set mosflm = ""
		    endif
		endif
	    end
	    
	endif
    end
endif

if(! -e "$mosflm") then
    echo -n "looking harder ... "

    foreach place ( ../../../ ~/ /programs/ /usr/local/bin/ /usr/local/ /sw/ / )
	# look for files of right type
	if((! -e "$mosflm")&&(-e "$place")) then

	    # look for links, and big-enough files
	    set temp = `find $place -name \*mosflm\* \( -type l -o \( -type f -size +100000c \) \) -perm -1 -print |& nawk '! /^find:/' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	    if("$temp" != "") set temp = `ls -lnL $temp |& sort -4n |& nawk '($1 !~ "d")&&($5 > 3000000){print $NF}'`
	    foreach file ( $temp )
		# see if file is big enough
		set file = `ls -lnLd $file |& nawk '$5>1000000{print $NF}'`
		if((! -e "$mosflm")&&(-e "$file")) then
		    # try running it
		    set MosflmVersion = `echo "GO" | $file SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
		    rm -f mosflm.lp >& /dev/null
		    if("$MosflmVersion" =~ [1-9]*) then
			# got one
			set mosflm = "$file"
		    else
			# no dice
			set mosflm = ""
		    endif
		endif
	    end
	endif
    end
endif

# make sure this thing runs
if(( -e "$mosflm")&&("$MosflmVersion" == "")) then
    # see if file is big enough
    set mosflm = `ls -lnLd $mosflm |& nawk '$5>1000000{print $NF}'`
    set MosflmVersion = `echo "GO" | $mosflm SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
    rm -f mosflm.lp >& /dev/null
    if("$MosflmVersion" !~ [1-9]*) then
	# no dice
	set mosflm = ""
    endif
endif

CantFindMosflm:
onintr
if((! -e "$mosflm")||(("$MosflmVersion" !~ [678]*)&&(! -e "$inmatrix"))) then
    echo "Hmm."
    if(-e "$mosflm") then
	echo "we found $mosflm, but "
    endif
    echo "you do not appear to have Mosflm 6.x ! "
    ######################################################
    cat << EOF-getmosflm >! getmosflm.com
#! /bin/csh -f
#
#
#	Script for automatically retrieving ipmosflm 6.23
#	from the MRC ftp site
#
#
#
if("\$1" =~ compile*) set COMPILE
# see what kind of system this is
set uname    = \`uname -a\`
set ipmosflm = ""
set gunzip   = "gunzip"

set ftpsite  = "ftp.mrc-lmb.cam.ac.uk"
set ftpdir   = "pub/mosflm/ver623/"
set guide    = "pub/mosflm/ver623/mosflm_user_guide.html"

# figure out which mosflm executable to get
if(\$?COMPILE) then
    set ftpdir   = "pub/mosflm/ver623/build-it-yourself"
    set ipmosflm = "mosflm623.tar.gz"
    goto retrieve
endif
if("\$uname" =~ IRIX*) then
    set ipmosflm = "mosflm_irix5.3.gz"
    set ftpdir   = "pub/mosflm/ver623/pre-built/"

    if("\$uname" =~ IRIX6*) set ipmosflm = "mosflm_irix6.5_o32.gz"
    if("\$uname" =~ *" 6.2 "*) set ipmosflm = "mosflm_irix6.2.gz"
endif
if("\$uname" =~ OSF1*) then
    set ipmosflm = "mosflm_alpha.gz"
    set ftpdir   = "pub/mosflm/ver623/pre-built/"
    # check for 4D60T graphics card?
    set ipmosflm = "mosflm_alpha4D60T.gz"
    set ipmosflm = "mosflm_alpha_noso.gz"
endif
if("\$uname" =~ Linux*) then
    set ipmosflm = "mosflm_redhat9.0.gz"
    set ftpdir   = "pub/mosflm/ver623/pre-built/"

    if("\$uname" =~ *" "SUSE" "*) set ipmosflm = "mosflm_suse7.3.gz"
    if("\$uname" !~ *" "i?86" "*) set ipmosflm = "mosflm_ppc.gz"
endif
if("\$uname" =~ Darwin*) then
    set ipmosflm = "mosflm_macOSX.gz"
    set ftpdir   = "pub/mosflm/ver623/pre-built/"
endif
# random, failsafe defaults
if("\$ipmosflm" == "") set COMPILE
if(\$?COMPILE) set ipmosflm = "mosflm623.tar.gz"
if("\$ipmosflm" == "mosflm623.tar.gz") set ftpdir = "pub/mosflm/ver623/build-it-yourself/"


retrieve:
# now figure out how we're going to retrieve mosflm
echo "retrieving ftp://\${ftpsite}/\${ftpdir}/\$ipmosflm "
rm -f \$ipmosflm >& /dev/null
wget -O \$ipmosflm ftp://\${ftpsite}/\${ftpdir}/\$ipmosflm >& /dev/null
if((! \$status)&&(-e \$ipmosflm)) then
    wget -O \$guide ftp://\${ftpsite}/\$guide >& /dev/null
    goto decompress
endif

# wget didn't work, try ncftpget
ncftpget \${ftpsite} . \${ftpdir}/\$ipmosflm \$guide >& /dev/null
if((! \$status)&&(-e \$ipmosflm)) goto decompress

# dangerous! try using regular ftp:
# confirm?
if(-e ~/.netrc) then
    mv ~/.netrc ~/netrc.bak\$\$
    set RESTORE_NETRC
endif
onintr restore_netrc
echo "default login anonymous password user@site" >! ~/.netrc
chmod go-rwx ~/.netrc

ftp \$ftpsite << EOF
get \${ftpdir}/\$ipmosflm \$ipmosflm
get \$guide mosflm_user_guide.html
close
bye
EOF

restore_netrc:
onintr
if(\$?RESTORE_NETRC) then
    mv ~/netrc.bak\$\$ ~/.netrc
else
    rm -f ~/.netrc >& /dev/null
endif

# check if transfer worked
if(! -e "\$ipmosflm") then
    echo "transfer failed..."
    echo "perhaps the server is overloaded? "
    exit 9
endif

decompress:
set uncompressed = \`basename \$ipmosflm .gz\`
if ("\$uncompressed" != "\$ipmosflm") rm -f \$uncompressed >& /dev/null
foreach unzip ( \$gunzip unzip "gzip -d" /bin/gunzip /usr/bin/gunzip )
    \$unzip \$ipmosflm >& /dev/null
    if((! \$status)&&(-e "\$uncompressed")) break
end

# maybe wget decompressed it?
if(! -e "\$uncompressed") then
    set uncompressed = \`basename \$ipmosflm .tgz\`".tar"
endif

compile:
if(\$?COMPILE) then
    if(! \$?CCP4) then
	setenv CCP4 \`pwd\`
	setenv CCP4_LIB \`pwd\`
	setenv CLIB \$CCP4_LIB
	
	echo "mosflm needs the CCP4 libraries:"
	echo "libccp4.a libxdl_view.a"
	echo "in order to compile."
	exit 200
    endif

    echo "compiling mosflm..."
    tar xf \$uncompressed
    if(\$status) then
	echo "unable to decompress archive! "
	echo "is \$uncompressed corrupt?"
	exit 9
    endif
    # go into the build directory
    cd mosflm623
    build >! compile.log
    if(\$status) then
	cat compile.log
	echo "unable to compile mosflm on this system! "
	echo "type:"
	echo "cd "\`pwd\`
	echo "make"
	echo "to see why."
	exit 9
    else
	set uncompressed = \`pwd\`/bin/ipmosflm
    endif
    cd ..
endif

# re-name the executable
mv \$uncompressed ipmosflm
if(-e ipmosflm) then
    chmod a+x ipmosflm
    echo \`pwd\`"/ipmosflm is ready"
endif

done:

exit

EOF-getmosflm
chmod a+x ./getmosflm.com
    ######################################################
    set temp = "Yes"
    if($?AUTO) set temp = "No"
    echo "shall we retrieve ipmosflm 6.23 from ftp.mrc-lmb.cam.ac.uk"
    echo "using anonymous FTP? [$temp]"
    if(! $?AUTO) then
    	echo -n "$PROMPT"
    	echo -n "$BELL"
	set temp = "$<"
    else
	set temp = ""
    endif
    if("$temp" !~ [Nn]*) then
	./getmosflm.com
	set mosflm = 'pwd'"/ipmosflm"
    else
	echo "Okay, you can run the script called: ./getmosflm.com"
	echo "to automatically retrieve the latest version of mosflm"
    endif
endif

if(! -e "$mosflm") then
    echo "Darn! "
    echo "We can't find ipmosflm.  Looked everywhere ... :( "
    echo "Where is ipmosflm [don't worry about it]?"
    if(! $?AUTO) then
    	echo -n "$PROMPT"
    	echo -n "$BELL"
	set temp = "$<"
    else
	set temp = ""
    endif
    if(("$temp" =~ q*)||("$temp" == "")) then
        echo "The Wedger elves could not find the executable file for MOSFLM."
        echo "We need this file to process your data. :)"
        echo "Ask your friendly neighborhood sysadmin where it is,"
        echo "or go to: "
	echo "netscape ftp://ftp.mrc-lmb.cam.ac.uk/pub/mosflm/"
        echo "and get yourself the latest version."
        
    	if("$temp" =~ q*) then
	    goto Cleanup
	else
	    echo ""
	    echo "Don't forget to edit $scriptname before you run it! "
	    set NORUN
	    set mosflm = ""
	    set MosflmVersion = ""
	    goto ReturnFindMOSFLM
	endif
    endif
    
    # check the user-input executabe file
    set mosflm = `ls -lnLd $temp |& nawk '$5>1000000{print $NF}'`
    if("$mosflm" == "") echo "$temp does not look like ipmosflm! "
    
    set MosflmVersion = `echo "GO" | $temp SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
    rm -f mosflm.lp >& /dev/null
    if("$MosflmVersion" !~ [1-9]*) then
	# no dice
	set mosflm = ""
    	echo "Sorry, $temp won't run."
	goto CantFindMosflm
    endif
    
    # update program location to user-input one
    set mosflm = "$temp"
#    goto FindMOSFLM
endif


goto ReturnFindMOSFLM

exit












exit
GetParamsFromSources:
###############################################################################

  ####    ####     ##    #    #          ######     #    #       ######   ####
 #       #    #   #  #   ##   #          #          #    #       #       #
  ####   #       #    #  # #  #          #####      #    #       #####    ####
      #  #       ######  #  # #          #          #    #       #            #
 #    #  #    #  #    #  #   ##          #          #    #       #       #    #
  ####    ####   #    #  #    #          #          #    ######  ######   ####

###############################################################################
#
#   Initialize program variables from an ordered listing of:
#
#	$img	$lastlog    $inmatrix	$scriptname and other files
# 
#	in the variable $sources
#
###############################################################################

# create temporary files for script reading
rm -f ${tempfile}* >& /dev/null
touch ${tempfile}.preamble
touch ${tempfile}.extra_refine_cards

# reverse the order of the sources, so that "first" sources are scanned last (dominant)
set temp = ""
foreach source ( $sources )
    set temp = `echo $source $temp |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
end
set sources = `echo "$temp"`

# now scan through sources in reverse precedence order
foreach source ( $sources )


    # check for mistakes
    if(! -e "$source") then
	echo "$source does not exist! "
	continue
    endif

    # identify the file format of large file types
    set format = ""

    # naming conventions
    if($source =~ *[0-9][0-9][0-9].mar*) set format = MAR

    # magic numbers
    set magic = `ood -b $source |& nawk '{print $2 $3 $4 $5 $6 $7 $8 $9 $10;exit}'`
    if("$magic" =~ 173012110105101104105122*) set format = ADSC
    if("$magic" =~ 122055101130111123*)       set format = RAXIS
    if("$magic" =~ 122101130111123*)          set format = RAXIS
    if("$magic" =~ 322004000000*)             set format = MAR
    if("$magic" =~ 000000004322*)             set format = MAR
    if("$magic" =~ 111111052000*)             set format = TIFF
    if("$magic" =~ 115115000052*)             set format = TIFF
    if("$format" == TIFF) then
	# see if it's MAR ccd
	set temp = `od -vc -j 1028 -N 3 $source |& nawk 'NR==1{print $2, $3, $4}'`
	if("$temp" == "M M X") set format = MARCCD
    endif
    if("$format" == "ADSC") then
	# check and see if it's ADSC or just SMV
	nawk 'BEGIN{RS="\f"} {print;exit}' $source | grep "APS1_" >& /dev/null
	if (! $status) then
	    set format = SBC
	endif
	# new SMV format for RAXIS images
	nawk 'BEGIN{RS="\f"} {print;exit}' $source | grep "RAXIS_" >& /dev/null
	if (! $status) then
	    set format = RAXIS_SMV
	endif
    endif


     #    #    ##     #####  #####      #    #    #
     ##  ##   #  #      #    #    #     #     #  #
     # ## #  #    #     #    #    #     #      ##
     #    #  ######     #    #####      #      ##
     #    #  #    #     #    #   #      #     #  #
     #    #  #    #     #    #    #     #    #    #

    if(($source == "$inmatrix")||($source =~ *.mat)) then
	echo -n "Scanning $source ... "
	#######################################################################
	# Read in CELL from the matrix file
	#
	#######################################################################
	set temp = `nawk 'NF == 6' $source |& nawk '{for(i=1;i<=NF;++i) if($i+0 > 10) printf $i+0 " "}'`
	if($#temp == 6) then
	    # don't update cell if we want it fixed
	    if(("$true_cell" != "yes")||($#CELL != 6)) then
		set CELL = `echo $temp`
	    endif
	    echo -n "$CELL"
	else
	    # maybe this is a denzo .x file? 

	    set temp = `basename $source .x`
	    set temp = `basename $temp .y`
	    set mat = "${temp}.mat"
	    if(-e "$mat") mv $mat ${mat}.old
	    
	    # extract the (putative) unitary matrix
	    head -5 $source |& nawk 'NR>1 && NF == 6{printf "%12.8f%12.8f%12.8f\n", $4, $5, $6}' |\
	    nawk '{i=NR; for(j=1;j<4;++j){mat[i,j]=$j+0}}                \
	    END{det += mat[1,1]*((mat[2,2]*mat[3,3])-(mat[2,3]*mat[3,2]))  \
		det -= mat[1,2]*((mat[2,1]*mat[3,3])-(mat[2,3]*mat[3,1]))  \
		det += mat[1,3]*((mat[2,1]*mat[3,2])-(mat[2,2]*mat[3,1]))  \
		printf "%.4f", det}' >&! $tempfile
	    set temp = `cat $tempfile`
	    
	    if("$temp" == "1.0000") then
		# get the cell out of this file
		set temp = `grep -i cell $source |& tail -1 |& nawk '{for(i=1;i<=NF;++i) if($i+0 > 10) printf $i+0 " "}'`
		if($#temp == 6) set CELL = `echo $temp`
		
		# determinant indicates a valid matrix
	
		# convert denzo to york (if need be)
		cp $source ${tempfile}.x
		grep HEADER $source >& /dev/null
		if($status) then
		    echo "HEADER     1" >! ${tempfile}.x
		    head -10 $file >> ${tempfile}.x
		endif
	
		# use rotaprep logfile output to get mosflm matrix
		echo "" | nawk '{print "INPUT DENZO"; print "SYMM 1"; print "RESO 9"; print "END"}' |\
		rotaprep HKLIN ${tempfile}.x HKLOUT /dev/null |&\
		nawk '/Mosflm umat matrix/{getline; getline; getline; getline;\
		    getline; printf "%12.8f%12.8f%12.8f\n", $1, $2, $3; \
		    getline; printf "%12.8f%12.8f%12.8f\n", $1, $2, $3; \
		    getline; printf "%12.8f%12.8f%12.8f\n", $1, $2, $3}'|\
		cat >&! ${tempfile}.umat
		rm -f ${tempfile}.x >& /dev/null

		# quick check for validity
		set temp = `cat ${tempfile}.umat | nawk '$1+$2+$3 != 0' | wc -l`
		if("$temp" != 3) then
		    echo "bad matrix in $source"
		    set inmatrix = ""
		    set autoindexing
		    continue
		endif
		
		# create a mosflm matrix file where A = U**-1 (doesn't seem to affect predictions)
		cat ${tempfile}.umat 					    >! $mat
		# missetting angles are zero
		nawk 'BEGIN{printf "%12.3f%12.3f%12.3f\n", 0, 0, 0}'	    >> $mat
		# U matrix goes here
		cat ${tempfile}.umat					    >> $mat
		# put the cell here...
		echo "$CELL" | nawk '{for(i=1;i<=NF;++i){if($i ~ /[0-9]/)\
			printf "%12.4f",$i}} END{print ""}'		    >> $mat
		# missetting angles are zero
		nawk 'BEGIN{printf "%12.4f%12.4f%12.4f\n", 0, 0, 0}'	    >> $mat
		rm -f ${tempfile}.umat >& /dev/null
	    
		# inform user we created a new file
		echo -n "extracted $mat "
		set inmatrix = $mat
	    else
		# not a valid matrix, or .x file
		echo -n "BAD MATRIX! "
		set inmatrix = ""
		set autoindexing
	    endif
	endif

	echo ""
	
	# skip rest of scans
	continue
    endif




       ##    #####    ####    ####              #    #    #    ##     ####   ######
      #  #   #    #  #       #    #             #    ##  ##   #  #   #    #  #
     #    #  #    #   ####   #                  #    # ## #  #    #  #       #####
     ######  #    #       #  #                  #    #    #  ######  #  ###  #
     #    #  #    #  #    #  #    #             #    #    #  #    #  #    #  #
     #    #  #####    ####    ####              #    #    #  #    #   ####   ######

    # ADSC files begin with "{\nHEADER_BYTES"
    if("$format" == ADSC) then
	echo -n "Scanning $source ... "
	# shorthand
	set img = $source
	###############################################################################
	# Read in parameters from an image file
	#
	###############################################################################
	# $img should be set to the location of the ADSC image file
	# following variables will be inilialized using this file's header:
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# phi		- oscillation start (degrees)
	# osc		- oscillation range (degrees)
	# wavelength	- wavelength (according to the header)
	# overload	- maximum pixel value
	# Site		- the detector serial number (or text of site)
	#
	# framedir	- directory where this file exists
	# frameprefix	- image filename (minus batch number and underscore)
	# first		- batch number of this frame
	# last		- largest batch number with same prefix
	#
	# Width		- detector width (mm)
	# PIXEL		- pixel size (mm)
	#
	set GAIN   = 0.3
	unset mosflm_beam

	# get ADSC CCD frame header
	nawk 'BEGIN{RS="\f"} {print;exit}' $img >! ${tempfile}header
	set Site = `grep "DETECTOR_SN" ${tempfile}header | nawk -F "=" '{ print $2+0}'`
	if("$Site" == "411") then
	    # prior knowledge of SSRL beamline 1-5 (could also be read from input script)
	    set Site = "SSRL"
	    set POLARISATION = "SYNCHROTRON 0.92"
	    set DIVERGENCE   = "0.250 0.030"
	    set DISPERSION   = "0.0002"
	endif
	if(("$Site" == "402")||("$Site" == "401")) then
	    # prior knowledge of ALS beamline 5.0.2 (could also be read from input script)
	    set Site = "ALS"
	    set POLARISATION = "SYNCHROTRON 0.9"
	    set DIVERGENCE   = "0.10 0.02"
	    set DISPERSION   = "0.00025"
	endif
	if("$Site" == "442" ) then
            # prior knowledge of ALS beamline 8.3.1
            set Site = "ALS 8.3.1"
            set POLARISATION = "SYNCHROTRON 0.9"
            set DIVERGENCE   = "0.10 0.02"
            set DISPERSION   = "0.00025"
	    set PREAMBLE = "${PREAMBLE}nBACKSTOP RADIUS 2"
        endif
        if("$Site" == "926") then
            # prior knowledge of ALS beamline 8.3.1
            set Site = "ALS 8.3.1"
            set POLARISATION = "SYNCHROTRON 0.9"
            set DIVERGENCE   = "0.10 0.02"
            set DISPERSION   = "0.00025"
            set PREAMBLE = "${PREAMBLE}nBACKSTOP RADIUS 2"
	    set GAIN = 1.8
        endif
        if("$Site" == "907") then
            # prior knowledge of SIBYLS beamline
            set Site = "SIBYLS"
            set POLARISATION = "SYNCHROTRON 0.9"
            set DIVERGENCE   = "0.10 0.02"
            set DISPERSION   = "0.00025"
        endif
        if("$Site" == "428" || "$Site" == "444") then
            # prior knowledge of ESRF beamline
            set Site = "ESRF"
	    set mosflm_beam
            #set POLARISATION = "SYNCHROTRON 0.9"
            #set DIVERGENCE   = "0.10 0.02"
            #set DISPERSION   = "0.00025"
        endif
	set Site = ( $Site ADSC )

	# get the size of the detector face
	set PIXEL       = `grep "PIXEL_SIZE" ${tempfile}header | nawk -F "=" '$2+0>0{ print $2+0}' | tail -1`
	set temp        = `grep "SIZE2" ${tempfile}header | nawk -F "=" '$2+0>0{print $2+0}' | tail -1`
	set Width       = 188
	if(("$Site" =~ 44*)&&("$temp" == 2048)&&("$PIXEL" == "0.0512")) then
	    # fix brief bug in 8.3.1 history
	    set PIXEL = 0.1024
	    echo "PIXEL $PIXEL" >> ${tempfile}.preamble
	endif
	if(("$temp" != "")&&("$PIXEL" != "")) set Width = `echo "$temp $PIXEL" | nawk '{print $1*$2}'`

	# get beam center
	set x_beam      = `nawk '/^BEAM_CENTER_X/' ${tempfile}header | nawk -F "=" '{ print $2+0}'`
	set y_beam      = `nawk '/^BEAM_CENTER_Y/' ${tempfile}header | nawk -F "=" '{ print $2+0}'`
	
	# convert beam center from ADXV convention
	set beam_center = `echo "$Width $x_beam $y_beam" | nawk '{print $1-$3, $2}'` 
	# some beamlines put "denzo" beam center in headers
	if($?mosflm_beam) set beam_center = `echo $x_beam $y_beam`
	
	set distance    = `grep "DISTANCE" ${tempfile}header | nawk -F "=" '{ print $2+0}'`
	set two_theta   = `grep "TWOTHETA" ${tempfile}header | nawk -F "=" '{ print -$2+0}'`
        set phi0        = `grep "PHI" ${tempfile}header | nawk -F "=" '{ print $2+0}'`
        set osc         = `grep "OSC_RANGE" ${tempfile}header | nawk -F "=" '{ print $2+0}'`

	# predict twotheta from beam center?
	set temp        = `echo $beam_center $Width | nawk '{print $NF/2-$1}'`
	set temp        = `echo "$temp $distance" | nawk '{printf "%.1f", 180*atan2($1,$2)/3.1415927}'`
	set temp        = `echo "$temp" | nawk '{if($1*$1 < 16){$1=0}; print $1}'`
	if("$temp" != "0") then
#	    set two_theta = "$temp"
	    echo -n "2theta = $two_theta "
	endif
	set two_theta = `echo "$two_theta" | nawk '{print $1+0}'`

	set temp = `grep "CCD_IMAGE_SATURATION" ${tempfile}header | nawk -F "=" '{ print $2+0}'`
#	if("$temp" != "") set OVERLOAD = "$temp"
	set temp = `grep "WAVELENGTH" ${tempfile}header | nawk -F "=" '{ print $2+0}'`
	if("$temp" != "") set wavelength = "$temp"
	echo -n "$wavelength $ANG "

	# set last frame to last file in frame directory
	ls -lnL ${framedir} |&\
	nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
	nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
	nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
	cat >! ${tempfile}
	set LastImage = `nawk '{print; exit}' ${tempfile}`
	rm -f ${tempfile} >& /dev/null
#	set LastImage   = `ls -lnL ${framedir} |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& egrep "${framepattern}" |& tail -1`
	set last 	= `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
	echo -n "$first-$last "

	# guess high resolution limit from detector geometry
	#set temp = `echo "$Width / 2      " | bc`
	set temp = `echo $Width | nawk '{print $1/2}'`
	set edge_res = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
#	set temp = `echo "$Width" | nawk '{print $1/2}'`   # edge
	set temp = `echo "$Width" | nawk '{print $1/1.4142}'`   # corner
#	set temp = `echo "$Width" | nawk '{print $1/1.7}'`   # compromize
	set hires = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`

	# set up scanner dimensions
	set temp = `echo $Width | nawk '{printf "%.0f", $1 / 1.4142}'`
	set SCANNER	= "SCANNER omega 90 ROTATION horiz ANTI FAST horiz ORIGIN UR RECTANG TYPE ADSC"
	if(("$Site" == "406 ADSC")||("$Site" == "414 ADSC")||("$Site" == "910 ADSC")) then
	    # CHESS detectors and BIOCARS
	    set SCANNER = "SCANNER omega 90 ROTATION horiz CLOCK FAST horiz ORIGIN UR RECTANG TYPE ADSC"
	endif
	if("$Site" == "910 ADSC") set BAD_HEADER

	set LIMITS	= "LIMITS RMAX $temp YMAX $Width XMAX $Width xscan $Width yscan $Width"
	# X-Y scale does not vary on the CCD
	set fixyscale = yes

	# these variables are now out of scope
	unset x_beam
	unset y_beam

	unset img
	rm -f ${tempfile}header >& /dev/null
	rm -f ${tempfile}headertext >& /dev/null

	echo ""
	
	# skip rest of scans
	continue
    endif



          ####   #####    ####              #    #    #    ##     ####   ######
         #       #    #  #    #             #    ##  ##   #  #   #    #  #
          ####   #####   #                  #    # ## #  #    #  #       #####
              #  #    #  #                  #    #    #  ######  #  ###  #
         #    #  #    #  #    #             #    #    #  #    #  #    #  #
          ####   #####    ####              #    #    #  #    #   ####   ######

    # SBC files are in SMV format, but all keywords are different from ADSC
    if("$format" == SBC) then
	echo -n "Scanning $source ... "
	# shorthand
	set img = $source
	###############################################################################
	# Read in parameters from an image file
	#
	###############################################################################
	# $img should be set to the location of the SMV image file
	# following variables will be inilialized using this file's header:
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# phi		- oscillation start (degrees)
	# osc		- oscillation range (degrees)
	# wavelength	- wavelength (according to the header)
	# overload	- maximum pixel value
	# Site		- the detector serial number (or text of site)
	#
	# framedir	- directory where this file exists
	# frameprefix	- image filename (minus batch number and underscore)
	# first		- batch number of this frame
	# last		- largest batch number with same prefix
	#
	# Width		- detector width (mm)
	# PIXEL		- pixel size (mm)
	#
	set GAIN   = 1
	# get SMV frame header
	nawk 'BEGIN{RS="\f"} {print;exit}' $img >! ${tempfile}header
	set Site = "APS SBC"


	# get the size of the detector face
	set PIXEL       = `grep "SPATIAL_DISTORTION_INFO" ${tempfile}header | nawk '$4+0>0{ print $4+0}' | tail -1`
	set temp        = `grep "DETECTOR_DIMENSIONS" ${tempfile}header | nawk -F "=" '$2+0>0{print $2+0}' | tail -1`
	set Width       = `grep "DETECTOR_SIZE" ${tempfile}header | nawk '$2+0>0{print $2+0}' | tail -1`
	set Width       = `echo "$temp $PIXEL" | nawk '{print $1*$2}'`
#	set PIXEL       = `echo "$temp $Width" | nawk '{print $2/$1}'`

	# get beam center
	set x_beam      = `grep "BEAM_POSITION" ${tempfile}header | nawk -v pix=$PIXEL '{print $3*pix}'`
	set y_beam      = `grep "BEAM_POSITION" ${tempfile}header | nawk -v pix=$PIXEL '{print $2*pix}'`
	
	# convert beam center to mosflm convention
	set beam_center = ( $x_beam $y_beam )
	
	set distance    = `grep "GONIO_VALUES" ${tempfile}header | grep -v CRYSTAL | nawk '{ print $NF+0}'`
	set phi0        = `grep "ROTATION_START" ${tempfile}header | nawk -F "=" '{ print $2+0}'`
	set osc         = `grep "ROTATION" ${tempfile}header | nawk -F "=" '/_START/{start=$2+0} /_END/{end=$2+0} END{print end-start}'`

	set temp = `grep "WAVELENGTH" ${tempfile}header | nawk -F "[= ]" '{ print $NF+0}' | tail -1`
	if("$temp" != "") set wavelength = "$temp"
	echo -n "$wavelength $ANG "

	# set last frame to last file in frame directory
	ls -lnL ${framedir} |&\
	nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
	nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
	nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
	cat >! ${tempfile}
	set LastImage = `nawk '{print; exit}' ${tempfile}`
	rm -f ${tempfile} >& /dev/null
#	set LastImage   = `ls -lnL ${framedir} |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& egrep "${framepattern}" |& tail -1`
	set last 	= `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
	echo -n "$first-$last "

	# guess high resolution limit from detector geometry
        #set temp = `echo "$Width / 2      " | bc`
        set temp = `echo $Width | nawk '{print $1/2}'`
        set edge_res = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
#       set temp = `echo "$Width" | nawk '{print $1/2}'`   # edge
        set temp = `echo "$Width" | nawk '{print $1/1.4142}'`   # corner
#       set temp = `echo "$Width" | nawk '{print $1/1.7}'`   # compromize
        set hires = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
                                                                                                                  
	# set up scanner dimensions
	set temp = `echo $Width | nawk '{printf "%.0f", $1 / 1.4142}'`
	set SCANNER	= "DETECTOR SBC1 REVERSEPHI"
	set LIMITS	= ""
	set PREAMBLE = "${PREAMBLE}nPIXEL $PIXEL"

#	set SCANNER	= "SCANNER omega 90 ROTATION horiz ANTI FAST horiz ORIGIN UR RECTANG TYPE ADSC"
#	set LIMITS	= "LIMITS RMAX $temp YMAX $Width XMAX $Width xscan $Width yscan $Width"
	# X-Y scale does not vary on the CCD
	set fixyscale = yes

	# these variables are now out of scope
	unset x_beam
	unset y_beam

	unset img
	rm -f ${tempfile}header >& /dev/null

	echo ""
	
	# skip rest of scans
	continue
    endif



     #####     ##    #    #     #     ####       ####   #    #  #   #
     #    #   #  #    #  #      #    #          #       ##  ##  #   #
     #    #  #    #    ##       #     ####       ####   # ## #  #   #
     #####   ######    ##       #         #          #  #    #  #   #
     #   #   #    #   #  #      #    #    #     #    #  #    #   # #
     #    #  #    #  #    #     #     ####       ####   #    #    #

    # new Rigaku files are in SMV format, but all keywords are different from ADSC
    if("$format" == RAXIS_SMV) then
	set RAXIS_SMV
	echo -n "Scanning $source ... "
	# shorthand
	set img = $source
	###############################################################################
	# Read in parameters from an image file
	#
	###############################################################################
	# $img should be set to the location of the SMV image file
	# following variables will be inilialized using this file's header:
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# phi		- oscillation start (degrees)
	# osc		- oscillation range (degrees)
	# wavelength	- wavelength (according to the header)
	# overload	- maximum pixel value
	# Site		- the detector serial number (or text of site)
	#
	# framedir	- directory where this file exists
	# frameprefix	- image filename (minus batch number and underscore)
	# first		- batch number of this frame
	# last		- largest batch number with same prefix
	#
	# Width		- detector width (mm)
	# PIXEL		- pixel size (mm)
	#
	set LIMITS = ""
#	set size = `ls -lnL $source |& nawk '{print $5+0}'`

	# default: R-axis 4
	set Site    = "RAXIS4"
	set SCANNER = "DETECTOR RAXIS4"
	set GAIN    = 1
	set PIXEL = 0.100
	#set OVERLOAD = "262135"

	# get SMV frame header
	nawk 'BEGIN{RS="\f"} {gsub("="," = ");print;exit}' $img >! ${tempfile}header

	# check for explicit detector type
	set test = `grep "DETECTOR_DESCRIPTION" ${tempfile}header | nawk -F "=" '{ print $2}' | head -1 | awk '{print $1}'`
	if("$test" =~ Saturn*) then
	    set Site = "$test"
	    set SCANNER = "DETECTOR Saturn"
	endif
	if("$test" =~ Jupiter*) then
	    set Site = "$test"
	    set SCANNER = "DETECTOR Jupiter"
	endif

	# get the size of the detector face
	set PIXEL       = `grep "SPATIAL_DISTORTION_INFO" ${tempfile}header | nawk '$4+0>0{ print $4+0}' | tail -1`
	set temp        = `grep "DETECTOR_DIMENSIONS" ${tempfile}header | nawk -F "=" '$2+0>0{print $2+0}' | tail -1`
	set Width       = `grep "DETECTOR_SIZE" ${tempfile}header | nawk -F "=" '$2+0>0{print $2+0}' | tail -1`
#	set Width       = `echo "$temp $PIXEL" | nawk '{print $1*$2}'`
	set test        = `echo "$temp $Width" | nawk '$2+0>0 && $1+0>0{print $2/$1}'`
	if("$test" != "") set PIXEL = $test

	# get beam center
	set x_beam      = `grep "BEAM_POSITION" ${tempfile}header | nawk -F "=" '{print $2;exit}' | nawk -v pix=$PIXEL '{print $2*pix}'`
	set y_beam      = `grep "BEAM_POSITION" ${tempfile}header | nawk -F "=" '{print $2;exit}' | nawk -v pix=$PIXEL '{print $1*pix}'`
	
	# convert beam center to mosflm convention
	set beam_center = ( $x_beam $y_beam )
	
	set test = `nawk '/GONIO_NAMES/{for(i=2;i<=NF;++i)if(tolower($i)~"distan")di=i} /GONIO_VALUES / && di && NF>=di{print $di+0;exit}' ${tempfile}header `
	if("$test" != "") set distance = "$test"
	set test = `nawk '/GONIO_NAMES/{for(i=2;i<=NF;++i)if(tolower($i)~"2theta")ti=i} /GONIO_VALUES / && ti && NF>=ti{print $ti+0;exit}' ${tempfile}header `
	if("$test" != "") set twotheta = "$test"
	set phi0        = `nawk -F "=" '/^ROTATION /{print $2}' ${tempfile}header | nawk '{ print $1+0}'`
	set osc         = `nawk -F "=" '/^ROTATION /{print $2}' ${tempfile}header | nawk '{print $2-$1}'`

	set temp = `grep "WAVELENGTH" ${tempfile}header | nawk -F "[= ]" '$NF+0>0{ print $NF+0}' | tail -1`
	if("$temp" != "") set wavelength = "$temp"
	echo -n "$wavelength $ANG "

	# set last frame to last file in frame directory
	ls -lnL ${framedir} |&\
	nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
	nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
	nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
	cat >! ${tempfile}
	set LastImage = `nawk '{print; exit}' ${tempfile}`
	rm -f ${tempfile} >& /dev/null
#	set LastImage   = `ls -lnL ${framedir} |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& egrep "${framepattern}" |& tail -1`
	set last 	= `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
	echo -n "$first-$last "

	# guess high resolution limit from detector geometry
        #set temp = `echo "$Width / 2      " | bc`
        set temp = `echo $Width | nawk '{print $1/2}'`
        set edge_res = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
#       set temp = `echo "$Width" | nawk '{print $1/2}'`   # edge
        set temp = `echo "$Width" | nawk '{print $1/1.4142}'`   # corner
#       set temp = `echo "$Width" | nawk '{print $1/1.7}'`   # compromize
        set hires = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
                                                                                                                  

	# set up scanner dimensions
	set temp = `echo $Width | nawk '{printf "%.0f", $1 / 1.4142}'`
#	set SCANNER	= "DETECTOR RAXIS4"
	set LIMITS	= ""
#	set PREAMBLE = "${PREAMBLE}n"

	# X-Y scale does not vary?
	set test = `nawk '/^CCD/{print 1;exit}' ${tempfile}header`
	if("$test" == "1") then
	   # probably a CCD detector
	   set fixyscale = yes
	else
	   set fixyscale = no
	endif

	# these variables are now out of scope
	unset x_beam
	unset y_beam

	unset img
	rm -f ${tempfile}header >& /dev/null

	echo ""
	
	# skip rest of scans
	continue
    endif


     #####     ##    #    #     #     ####          #    #    #    ##     ####   ######
     #    #   #  #    #  #      #    #              #    ##  ##   #  #   #    #  #
     #    #  #    #    ##       #     ####          #    # ## #  #    #  #       #####
     #####   ######    ##       #         #         #    #    #  ######  #  ###  #
     #   #   #    #   #  #      #    #    #         #    #    #  #    #  #    #  #
     #    #  #    #  #    #     #     ####          #    #    #  #    #   ####   ######

#    if(($source == "$FirstImage")&&("$ext" == "osc")) then
#    if($source =~ *.osc) then
    # all RAXIS formats begin with "R-AXIS"
    if("$format" == RAXIS) then
	echo -n "Scanning $source ... "
	
	###############################################################################
	# Read in parameters from an raxisII image file
	#
	###############################################################################
	# $img should be set to the location of the raxis image file
	# following variables will be inilialized using this file's header:
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# phi		- oscillation start (degrees)
	# osc		- oscillation range (degrees)
	# wavelength	- wavelength (according to the header)
	# overload	- maximum pixel value
	# Site		- the detector serial number (or text of site)
	#
	# framedir	- directory where this file exists
	# frameprefix	- image filename (minus batch number and underscore)
	# first		- batch number of this frame
	# last		- largest batch number with same prefix
	#
	# Width		- detector size (mm)
	# PIXEL		- pixel size in mm (0.105)
	#
	set LIMITS = ""
	set GAIN   = 5
	set size = `ls -lnL $source |& nawk '{print $5+0}'`
	set type = `ood -cv $source |& nawk '{print $2 $3 $4 $5 $6 $7 $8; exit}'`
	set fixyscale = no

	# default: R-axis 4
	set Site    = "RAXISIV"
	set SCANNER = "SCANNER RAXISIV"
	set GAIN    = 1
	set PIXEL = 0.100
	#set OVERLOAD = "262135"

	if("$type" == "R-AXIS2") then
	    set Site	 = "RAXIS II"
	    set SCANNER	 = "SCANNER RAXIS"
	    set OVERLOAD = "262135"
	    set PIXEL    = "0.105"
	endif
	if(("$type" == "R-AXIS5")||($size > 30000000)) then
	    set Site    = "RAXISV"
	    # will this work with old version? 
	    # check if we have mosflm 6.10? 
	    set SCANNER = "SCANNER ROTATION vert anti FAST horiz ORIGIN lr RECT RAXISV"
	    set GAIN    = 1
#	    echo "PIXEL 0.1 0.1" >> ${tempfile}.preamble
#	    echo "SIZE 4000 4000" >> ${tempfile}.preamble
	    
            # header seems to be the same as RAXISII
            set PIXEL = 0.100
	    set OVERLOAD = "1100000"
	endif
	if("$Site" =~ RAXIS*) then
	    echo -n "$Site "

	    # use octal dump program to get header values
	    set temp     = `od -c -j 76 -N 20 $source | head -1 | nawk '{print substr($0, 1, 55)}'`
	    set temp     = `echo "$temp" | nawk 'BEGIN{RS=" "} NR>1 && /[PpCcIiFfRrHh12346]/ {printf "%s", $0}'`
	    if("$temp" =~ [PpCcIiFfRrHh][1-6]*) then
		set SG = `echo "$temp" | nawk '{print toupper($1)}'`
	    endif
	    
	    # get size of the detector face (maybe swap bytes latter)
    	    set h_size = `od -d -j 788 -N 8 $source | nawk '{print $2+$3; exit}'`
    	    set v_size = `od -d -j 768 -N 8 $source | nawk '{print $2+$3; exit}'`

	    if(("$h_size" > 10000)||("$h_size" < 1000)) then
		# swap bytes for 2-byte values
		set h_size  = `echo $h_size | nawk '{printf "%d", ($1%256)*256 + $1/256}'`
		set v_size  = `echo $v_size | nawk '{printf "%d", ($1%256)*256 + $1/256}'`
	    endif	    	    
	    
	    # now read monochromater info
	    set temp     = `od -c -j 296 -N 20 $source | head -1 | nawk 'BEGIN{RS=" "} /[a-z,A-Z]/ {printf "%s", $0}'`
	    set temp     = `echo $temp | nawk '{print toupper($1)}'`
	    if("$temp" =~ GRAPH*) then
		# graphite
		set POLARISATION = "MONOCHROMATOR"
	    else
		# unpolarized
		set POLARISATION = "MIRRORS"
	    endif

	    set phi = ""
	    
	    
	    # convert header into every possible byte-swapping convention
	    set best = "0.1 1234"
	    set address = 780
	    foreach swap ( 1234 4321 3412 2143 5143 3416 )
		set swap = `echo "$swap" | nawk '{print "$"substr($1,1,1)",$"substr($1,2,1)",$"substr($1,3,1)",$"substr($1,4,1)}'`
		
		set bytes = `od -vb -j $address -N 4 $source | nawk '{for(i=2;i<=5;++i){printf "%d ", 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)};exit}'`
		set bytes = `echo $bytes | nawk '{w=x=$2} $1+$2+$3+$4==0{--w;++x} {print $0, w,x-1}'`
		set vpix = `echo "$bytes" | nawk '{printf "%c%c%c%c", '$swap'}' | ood -f | nawk '{print $2+0;exit}'`

		set best = `echo 0.1 $vpix $best $swap | nawk '{diff=sqrt(($1-$2)^2); if(diff<$3){print diff, $5}else{print $3, $4}}'`
	    end
	    # choose the convention that gave the closest-to-expected result
	    set swap = `echo $best | nawk '$2~/[,]/{print $2}'`
	    
	    
	    # make sure its safe to try and read these
	    if("$swap" != "") then
		# extract floating-point variables
		echo -n "" >! ${tempfile}header_floats
		foreach address ( 524 528 344 556 776 780 540 544 292 52 56 60 64 68 72 88 )
		    od -vb -j $address -N 4 $source |\
		    nawk '{for(i=2;i<=5;++i){printf "%d ", 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)};exit}' |\
		    nawk '{w=x=$2} $1+$2+$3+$4==0{--w;++x} {print $0, w, x-1}' |\
		    nawk '{printf "%c%c%c%c", '$swap'}' | ood -f |\
		    nawk -v address=$address '{print address, $2+0;exit}' |\
		    cat >> ${tempfile}header_floats
		end
		
		set phi 	= `nawk '$1==524{print $2;exit}' ${tempfile}header_floats`
		set phiend 	= `nawk '$1==528{print $2;exit}' ${tempfile}header_floats`
		set distance    = `nawk '$1==344{print $2;exit}' ${tempfile}header_floats`
		set two_theta   = `nawk '$1==556{print $2;exit}' ${tempfile}header_floats`
		
		# R-axis has Y= fast axis and X= slow axis (mosflm knows this)
		set h_pixel 	= `nawk '$1==776{print $2;exit}' ${tempfile}header_floats`
		set v_pixel 	= `nawk '$1==780{print $2;exit}' ${tempfile}header_floats`
		set h_beam 	= `nawk '$1==540{print $2;exit}' ${tempfile}header_floats`
		set v_beam 	= `nawk '$1==544{print $2;exit}' ${tempfile}header_floats`
		 
		set wavelength  = `nawk '$1==292{print $2;exit}' ${tempfile}header_floats`
		
		set a 		= `nawk '$1==52{print $2;exit}' ${tempfile}header_floats`
		set b 		= `nawk '$1==56{print $2;exit}' ${tempfile}header_floats`
		set c 		= `nawk '$1==60{print $2;exit}' ${tempfile}header_floats`
		set alpha 	= `nawk '$1==64{print $2;exit}' ${tempfile}header_floats`
		set beta 	= `nawk '$1==68{print $2;exit}' ${tempfile}header_floats`
		set gamma 	= `nawk '$1==72{print $2;exit}' ${tempfile}header_floats`
		
		if("$fixmosaicity" != "yes") then
		    set mosaic  = `nawk '$1==88 && $2+0>0.1{print $2; exit}' ${tempfile}header_floats`
		endif
		rm -f ${tempfile}header_floats >& /dev/null
	    endif
	    
	    if("$phi" == "") then
		echo -n "unable to read header. "
	    else
		# calculate oscillation angle
		set phi0 = "$phi"
		#set osc  = `echo "$phiend - $phi" | bc`
		set osc  = `echo $phiend $phi | nawk '{print $1-$2}'`
	    
		# calculate beam center in mm
		set beam_center = `echo $v_beam $v_pixel $h_beam $h_pixel | nawk '{print $1*$2, $3*$4}'`
#		set yscale = `echo "$v_pixel $h_pixel" | nawk '{print $1 / $2}'`
		set PIXEL = "$h_pixel"
		set Width = `echo "$h_pixel $h_size" | nawk '{print $1*$2}'`

		# set high resolution limit and detector geometry
        	#set temp = `echo "$Width / 2      " | bc`
        	set temp = `echo $Width | nawk '{print $1/2}'`
        	set edge_res = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
#       	set temp = `echo "$Width" | nawk '{print $1/2}'`   # edge
        	set temp = `echo "$Width" | nawk '{print $1/1.4142}'`   # corner
#       	set temp = `echo "$Width" | nawk '{print $1/1.7}'`   # compromize
        	set hires = `echo "$wavelength $temp $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2, $3)/2))}'`
                                                                                                                  
		set temp = `echo $a | nawk '{printf "%d", $1}'`
		if($temp > 10) then
		    # don't read stupid cells
		    set CELL = `echo $a $b $c $alpha $beta $gamma`
		endif
	    endif
	    
	    # unset uneeded variables
	    unset phi
	    unset phiend
	    
	    unset h_beam
	    unset v_beam
	    unset h_pixel
	    unset v_pixel

	    unset a
	    unset b
	    unset c
	    unset alpha
	    unset beta
	    unset gamma
	else
	    set Site	= "RAXISIV"
	    set SCANNER	= "SCANNER RAXISIV"

	    echo -n "$Site "
	    
	    # how do you read these? 
	    set PIXEL = 0.100
	endif

	# set last frame to last file in frame directory
	ls -lnL ${framedir} |&\
	nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
	nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
	nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
	cat >! ${tempfile}
	set LastImage = `nawk '{print; exit}' ${tempfile}`
	rm -f ${tempfile} >& /dev/null
#	set LastImage = `ls -lnL ${framedir} |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& egrep "${framepattern}" |& tail -1`
	set last      = `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
	echo -n " $first-$last "

	rm -f $tempfile >& /dev/null

	echo ""
	
	# skip rest of scans
	continue
    endif




	 #    #    ##    #####              #    #    #    ##     ####   ######
	 ##  ##   #  #   #    #             #    ##  ##   #  #   #    #  #
	 # ## #  #    #  #    #             #    # ## #  #    #  #       #####
	 #    #  ######  #####              #    #    #  ######  #  ###  #
	 #    #  #    #  #   #              #    #    #  #    #  #    #  #
	 #    #  #    #  #    #             #    #    #  #    #   ####   ######

#    if($source =~ *[0-9][0-9][0-9].mar*) then
    if("$format" == MAR) then
	echo -n "Scanning $source ... "
	# shorthand
	set img = "$source"
	###############################################################################
	# Read in parameters from an image file
	#
	###############################################################################
	# $img should be set to the location of the MAR image file
	# following variables will be inilialized using this file's header:
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# phi		- oscillation start (degrees)
	# osc		- oscillation range (degrees)
	# wavelength	- wavelength (according to the header)
	# overload	- maximum pixel value
	# Site		- the detector serial number (or text of site)
	#
	# framedir	- directory where this file exists
	# frameprefix	- image filename (minus batch number and underscore)
	# first		- batch number of this frame
	# last		- largest batch number with same prefix
	#
	# Width		- detector size (mm)
	# PIXEL		- pixel size (mm)
	#
	# get variables from MAR frame header
	# get pixel size (in mm)
	set PIXEL       = `head -56 $img | nawk '/^PIXEL/{ print $3/1000, $NF/1000}'`
	if($#PIXEL != 2) then
	    echo "bad MAR header! "
	    continue
	endif

	set Site	= `head -56 $img | nawk '/^PROGRAM/{ print $2}'`
	set Width	= 345
	set temp 	= `head -56 $img | nawk '/^FORMAT/ && $2+0>0{ print $2}'`
	if("$temp" != "") set Width = `echo $temp $PIXEL | nawk '{print $1*$2}'`
	set Site        = `echo $Site $Width | nawk '{printf "%s %dmm", $1, $2}'`

	# convert beam center
	set temp        = `head -56 $img | nawk -v pixx=$PIXEL[1] -v pixy=$PIXEL[2] '/^CENTER/{print $3*pixx, $5*pixy}'`
	if($#temp == 2) then
	    set beam_center = `echo $temp`
	endif
	
	# get twotheta from image header
	set two_theta   = `head -56 $img | nawk '/^TWOTHETA/{ print $2+0}'`
	
	set distance    = `head -56 $img | nawk '/^DISTANCE/{ print $2+0}'`
	set phi0        = `head -56 $img | nawk '/^PHI/{print}' | nawk 'BEGIN{RS=" "} /START/{getline; print $0+0}'`
	set osc         = `head -56 $img | nawk '/^PHI/{print}' | nawk 'BEGIN{RS=" "} /OSC/{getline; print $0+0}'`
	
#	set OVERLOAD    = what?
	set wavelength  = `head -56 $img | nawk '/^WAVELEN/{ print $2+0}'`
	echo -n "$wavelength $ANG "

	# set last frame to last file in frame directory
	ls -lnL ${framedir} |&\
	nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
	nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
	nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
	cat >! ${tempfile}
	set LastImage = `nawk '{print; exit}' ${tempfile}`
	rm -f ${tempfile} >& /dev/null
#	set LastImage = `ls -lnL ${framedir} |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& egrep "${framepattern}" |& tail -1`
	set last      = `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
	echo -n "$first-$last "

	# get high resolution limit from frame header
	set temp = `head -56 $img | nawk '/^RESOL/&&$2+0>0.1{print $2+0}'`
	if("$temp" != "") set hires = "$temp"

	# set up scanner dimensions
	set SCANNER	= "SCANNER MAR"
	set LIMITS	= ""
	set PIXEL       = "$PIXEL[1]"


	echo ""
	
	# skip rest of scans
	continue
    endif




	 #    #    ##    #####            ####    ####   #####
	 ##  ##   #  #   #    #          #    #  #    #  #    #
	 # ## #  #    #  #    #          #       #       #    #
	 #    #  ######  #####           #       #       #    #
	 #    #  #    #  #   #           #    #  #    #  #    #
	 #    #  #    #  #    #           ####    ####   #####

    
    if("$format" == MARCCD) then
	echo -n "Scanning $source ... "
	# shorthand
	set img = "$source"
	###############################################################################
	# Read in parameters from an image file
	#
	###############################################################################
	# $img should be set to the location of the MAR image file
	# following variables will be inilialized using this file's header:
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# phi		- oscillation start (degrees)
	# osc		- oscillation range (degrees)
	# wavelength	- wavelength (according to the header)
	# overload	- maximum pixel value
	# Site		- the detector serial number (or text of site)
	#
	# framedir	- directory where this file exists
	# frameprefix	- image filename (minus batch number and underscore)
	# first		- batch number of this frame
	# last		- largest batch number with same prefix
	#
	# Width		- detector size (mm)
	# PIXEL		- pixel size (mm)
	#
	set Site = "MAR CCD"
	set fixyscale = yes

	# dump MARCCD header bytes (convert to decimal)
	od -bv -j 1024 -N 1024 $source |\
	nawk '{for(i=2;i<=NF;++i){print 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)}}' |\
	nawk 'NR%4==1{printf "\n%d ", NR+1023} {printf "%d ", $1}' |\
	nawk '/^1052 210 4 0 0/{little=1} /^1052 0 0 20 341/{big=1} \
	     little{print $1, $2+256*($3+256*($4+256*$5))} \
	        big{print $1, $5+256*($4+256*($3+256*$2))}' |\
	cat >! ${tempfile}header

	# dump header text too
	od -av -j 2048 -N 1024 $source  |\
	nawk '{for(i=2;i<=NF;++i){print $i}}' |\
	nawk '$1=="sp"{$1=" "} length($1)>1{print "";next} {printf "%s",$1}' |\
	nawk 'NF>0' |\
	cat >! ${tempfile}headertext

	set SN = `nawk '/Detector Serial/{print $NF}' ${tempfile}headertext`
	set test = `nawk '/Gain setting /{print $NF}' ${tempfile}headertext`
	if("$test" != "") set GAIN = "$test"
	
	# get pixel size (in mm)
	set PIXEL = `nawk '/^1796 / || /^1800 /{ print $2/1000000}' ${tempfile}header`
	if($#PIXEL != 2) then
	    echo "cannot read MARCCD header! "
	    set PIXEL = "0.079108"
	    rm -f ${tempfile}header >! /dev/null
	    continue
	endif
	# detector size (fast axis)
	set Width  = 162
	set temp = `nawk '/^1104 / && $2+0>0{ print $2}' ${tempfile}header`
	if("$temp" != "") then
	    set Width = `echo "$temp $PIXEL" | nawk '{print $1*$2}'`
	endif
	
	# get beam center
	set temp = `nawk '/^1668 / || /^1672 /{ print $2/1000}' ${tempfile}header`
	if(($#temp == 2)&&("$temp" != "0 0")) then
	    set beam_center = `echo $PIXEL $temp | nawk '{print $1*$3, $2*$4}'`
	    set beam_center = `echo $beam_center | nawk '{print $2,$1}'`
	    set test = `echo $beam_center $Width | nawk '{print (($1*$1 < 0.01*$3*$3) && ($2*$2 < 0.01*$3*$3))}'`
	    if($test) then
		# probably from ESRF, they use mm instead of pixels
		set beam_center = ( $temp )
	    endif
	else
	    echo -n "beam center missing! "
	    set beam_center = `echo "$Width" | nawk '{print $1/2, $1/2}'`
	endif
	
	# get twotheta from image header
	set two_theta   = `nawk '/^1692 /{ print $2/1000}' ${tempfile}header`
	
	set distance    = `nawk '/^1720 /{ print $2/1000}' ${tempfile}header`
	set phi0        = `nawk '/^1708 /{ print $2/1000}' ${tempfile}header`
	set phi_end     = `nawk '/^1740 /{ print $2/1000}' ${tempfile}header`
	set osc         = `nawk '/^1760 /{ print $2/1000}' ${tempfile}header`
	set test = `echo $osc | nawk '{print ($1<=0)}'`
	if ($test) then
	    set osc         = `echo "$phi0 $phi_end" | nawk '{print $2-$1}'`
	else
	    set phi_end     = `echo "$phi0 $osc" | nawk '{print $2+$1}'`
	endif
	
	set OVERLOAD    = `nawk '/^1128 /{ print $2}' ${tempfile}header`
	set wavelength  = `nawk '/^1932 /{ print $2/100000}' ${tempfile}header`
	echo -n "$wavelength $ANG "

	# set last frame to last file in frame directory
	ls -lnL ${framedir} |&\
	nawk -v first=`basename $FirstImage` '$NF==first{++p} /^\-/ && $5+0 > 800000 && p {print $NF}' |&\
	nawk -v template=$template 'BEGIN{gsub("[+]","\\+",template); n=split(template,w,"\043")}\
	    $1 ~ "^"w[1] && $1 ~ w[n]"$" {print substr($1,length(w[1])+1)+0, $1}' |\
	nawk 'NR>1 && $1 != last+1{print lastfile} {last=$1;lastfile=$2} END{print lastfile}' |\
	cat >! ${tempfile}
	set LastImage = `nawk '{print; exit}' ${tempfile}`
	rm -f ${tempfile} >& /dev/null
#	set LastImage = `ls -lnL ${framedir} |& nawk '/^\-/ && $5+0 > 800000 {print $NF}' |& egrep "${framepattern}" |& tail -1`
	set last      = `echo "$LastImage $template" | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
	echo -n "$first-$last "
	
	# calculate high resolution limit from frame size
	set edge_res = `echo "$wavelength $Width $distance" | nawk '{printf "%.1f\n", $1/(2*sin(atan2($2/2, $3)/2))}'`
	set hires = "$edge_res"

	set extras = ""
	if("$SN" == "15") set extras = "REVERSEPHI"

	# set up scanner dimensions
	set SCANNER	= "DETECTOR MARCCD $extras"
	set LIMITS	= ""
	set PIXEL       = "$PIXEL[1]"

	echo ""
	
	# skip rest of scans
	continue
    endif


     #        ####    ####   ######   #    #       ######
     #       #    #  #    #  #        #    #       #
     #       #    #  #       #####    #    #       #####
     #       #    #  #  ###  #        #    #       #
     #       #    #  #    #  #        #    #       #
     ######   ####    ####   #        #    ######  ######
    if(($source == "$lastlog")||($source =~ *.log)) then
	echo -n "Scanning $source ."
	###############################################################################
	# compute average parameters from the last mosflm run
	#
	#   Values for	beam_center, distance, mosaicity, missetting angles, 
	#		and CELL (if informative)
	#
	#
	###############################################################################
	# get beam center and distance
	nawk '/Processing Image/{print gather}       \
              /XTOFD/{getline; gather = $0} END{print gather}' $lastlog >! $tempfile
	# compute the average values
	
	# get beam center
	set temp = `nawk 'NF>6{++i; x+=$1; y+=$2} END{if(i) print x/i, y/i}' $tempfile`
	if($#temp == 2) then
	    # verify that both values are numbers
	    if(($temp[1] =~ [1-9]*)&&($temp[2] =~ [1-9]*)) set beam_center = `echo $temp`
	endif
	echo -n "."

	# get distance
	set temp = `nawk 'NF>6{++i;     dist+=$4} END{if(i) print   dist/i}' $tempfile`
	if($#temp == 1) then
	    if($temp[1] =~ [1-9]*) set distance = "$temp"
	endif

	# update twotheta
	set tilt = `nawk 'NF>6{++i; tilt+=$6} END{if(i) print tilt/i/100}' $tempfile`
	if("$tilt" != "") then
	    # avoid huge shifts?
	    set tilt = `echo "$tilt 0.1" | nawk '$1*$1>$2*$2{$1=$2*($1/sqrt($1*$1))} {printf "%.2f", $1}'`
	    set test = `echo $two_theta | nawk '{printf "%.0f", $1}'`
	    if( "$test" != 0 ) then
		set two_theta = `echo $two_theta $tilt | nawk '{print $1+$2}'`
	    endif
	endif
	rm -f $tempfile

	# read an estimated mosaicity
	if("$mosaic" !~ *[0-9]*) then
	    set temp = `nawk '/mosaicity has been estimated/ && $8+0>0.1 && $8+0<5{print $8}' $lastlog | head -1`
	    if("$temp" != "") then
		set mosaic = "$temp"
	    else
		if("$ESTIMATING" == "mosaic spread") then
		    echo "mosaic spread estimation failed."
		    set temp = 1
		    if($?osc) then
			set temp = $osc
		    endif
		    set mosaic = `echo $temp | nawk '$1+0<0.1{$1=1} {print $1/2}'`
		    set ESTIMATING = ""
		endif
	    endif
	endif

	# get mosaicity
	cat $lastlog |\
	nawk '/Mosaic spread/{getline; if($1 == "New"){print $NF}}' |\
	nawk '{avg += $1; ++n;v[n]=$1} \
	max+0<$1 {sec=max; max = $1}\
	END{if(n) {avg/=n;\
	    for(i=1;i<=n;++i){ms += (v[i]-=avg)^2};\
	print avg, sqrt(ms/n), max, sec}}' |\
	cat >! $tempfile
	# average
	set temp = `nawk '{print $1}' $tempfile`
	# average + 1sd
	set temp = `nawk '{print $1+$2}' $tempfile`
######### largest (refined value)
########set temp = `nawk '{print $3}' $tempfile`
######### 2nd largest
########set temp = `nawk '{print $NF}' $tempfile`
	if(($#temp == 1)&&("$fixmosaicity" != "yes")) then
	    if($temp[1] =~ [0-5].[0-9]*) set mosaic = "$temp"
#	    echo -n "mosaicity = $mosaic "
	endif
	rm -f $tempfile

	echo -n "."
	
	# see if this was an integration run
	# if log was postref only, CELL will be in matrix
	grep "Integrating Image" $lastlog >> /dev/null
	if(! $status) then
	    # get average cell parameters
	    nawk '/Processing Image/{print gather}       \
   /^          Real cell parameters/{getline; gather = $0}' $lastlog | \
	    nawk 'NF==6{++n; a+=$1; b+=$2; c+=$3;        \
	                   al+=$4; be+=$5; ga+=$6}       \
		  END{if(n) print a/n, b/n, c/n, al/n, be/n, ga/n}'  >! $tempfile
	
	    # put averaged cell into variable
	    set cell = `head -1 $tempfile`
	    rm -f $tempfile >& /dev/null

	    # check for valid CELL
	    foreach X ( $cell )
		if($X !~ [1-9]*) set $cell = ""
	    end
	    if(($#cell == 6)&&("$true_cell" != "yes")) then
		set CELL = `echo "$cell"`
	    endif
	endif

	echo -n "."
	
	# average the missetting angles (PSIX, PSIY, PSIZ) from the log.
	# Experience suggests this is appropriate
	cat $source |\
	nawk '/Processing Image/{f=$3} \
	      /Refined Orientation Angles/{getline; getline; Cx[f]=$1; Cy[f]=$2; Cz[f]=$3}  \
	      END { n=0; for(f in Cx){++n;} \
			 for(f in Cx){CX+=Cx[f]/n; CY+=Cy[f]/n; CZ+=Cz[f]/n; }; \
   		         printf "%12.6f %12.6f %12.6f", CX, CY, CZ }' >! $tempfile
	set missets = `cat $tempfile`
	rm -f $tempfile >& /dev/null

	# initial missetting angles (PSIX, PSIY, PSIZ)
	#set missets = `nawk '/Refined Orientation Angles/{getline; getline; missets=$0} /Processing Image/ && missets!=""{print missets; exit}' $source`
	if($reinput_missets == yes) echo -n " missets: $missets "

	# get quantum GAIN of scanner
	set temp = `grep GAIN $lastlog | nawk '{if($NF+0 > 0) print $NF+0}' | head -1`
	if($#temp == 1) then
	    if($temp[1] =~ [0-9]*) then
		set GAIN = "$temp"
		# get BGRATIO (for correcting GAIN estimate)
		set temp = `nawk '/^ BGRATIO/{ for(i=2;i<=NF;++i) {++n; sum+=$i}} END{if(n) printf("%.3f", (sum/n)*(sum/n))}' $lastlog`
		set temp = `echo $temp | nawk '$1+0 != 0'`
		if($#temp == 1) then
		    # gain correction must have been found
		    set temp = `echo $temp 1.1 0.9 | nawk '$1>=$2{$1=$2} $1<=$3{$1=$3} {print}'`
		    set temp = `echo "$GAIN $temp" | nawk '{printf "%0.3f", $1*$2}'`
		    echo -n "gain: $GAIN -> $temp "
#		    if("$ext" == "img") set GAIN = "$temp"
		    set GAIN = "$temp"
		endif
	    endif
	endif

        # figure out effective outer resolution limit from mosflm log.
        cat ${logfile}mosflm.log |\
        nawk 'h==0 && /Analysis as a function of resolution./{h=1;getline;\
                       print $3, $4, $5, $6, $7, $8, $9, $10} \
              /^  <I\/sigma>/{print $2, $3, $4, $5, $6, $7, $8, $9}' |\
        nawk 'NR==1{for(i=1;i<9;++i){res[i]=$i};++n} \
              NR!=1{for(i=1;i<9;++i){signal[i]+=$i;++count[i]}}\
              END{if(n) for(i=8;i>0;--i){print res[i], signal[i]/count[i]}}' |\
	sort -nr >! ${tempfile}res_limit
        set res_limit = `nawk '$NF > 0.1 {print $1+0} $NF<=0 {exit}' ${tempfile}res_limit | tail -1`

	# pick an optimistic, but reasonable outer limit 
	# (1.5x the reciprocal-space volume of res_limit)
	set inflation = 1.5
	if($?RES_TROUBLE) set inflation = 1.0
        set newRES = `echo $res_limit $inflation | nawk 'NF==2{printf "%.2f", ($2*($1^-3))^(-1/3)}'`
	if("$newRES" != "") echo -n "RES: $hires -> $newRES "

	# clip resolution extention at detector limit (if we know it) 
	set newRES = `echo $newRES $detector_res_limit | nawk 'NF==2 && $1<$2{$1=$2} {print $1}'`

	# clip resolution extension to not more than a 20% change
	set test = `echo $newRES $hires | nawk 'NF==2{print (sqrt(($1^-3 - $2^-3)^2)>0.2*($1^-3) )}'`
	if("$test" == "1") then
	    # calculated change is > 20%, clip change off at 20%
	    set newRES = `echo $newRES $hires 1.2 | nawk '$1<$2{print ($2^-3 * $3)^(-1/3)} $1>=$2{print ($2^-3 / $3)^(-1/3)}'`
	endif

	# see if it is appropriate to alter $hires (> 10% change in rs volume)
	set test = `echo $newRES $hires | nawk 'NF==2{print (sqrt(($1^-3 - $2^-3)^2)>0.1*($1^-3) )}'`
        if("$test" == "1") then
	    if("$res_choice" != "user" && "$res_choice" != "estimating") then
		# Elves chose resolution, and it looks like it should be changed
		set hires = $newRES
		set res_choice = mosflm
		unset LAST_RUN
	    endif
	endif
	# see if the whole purpose of this run was to estimate resolution
	if("$res_choice" == "estimating") then
	    # only do this once
	    set res_choice = mosflm
	    echo ""
	    echo ""

	    # we can afford to be a little more conservative at the beginning
	    set res_limit = `nawk '$NF < 2.0 {print $1+0}' ${tempfile}res_limit | head -1`
	    if("$res_limit" != "") then
		echo "modest resolution estimate is: $res_limit"
		set hires = $res_limit
	    else
		# what the hell?  no information on resolution estimate?
		echo "resolution estimation failed: assuming detector face limits"
	    endif
        endif
        rm -f ${tempfile}res_limit >& /dev/null


	echo ""
	
	# skip rest of scans
	continue
    endif





      ####   #       #####            ####    ####   #####      #    #####    #####
     #    #  #       #    #          #       #    #  #    #     #    #    #     #
     #    #  #       #    #           ####   #       #    #     #    #    #     #
     #    #  #       #    #               #  #       #####      #    #####      #
     #    #  #       #    #          #    #  #    #  #   #      #    #          #
      ####   ######  #####            ####    ####   #    #     #    #          #

    # if we got here, source must be something?
    if(-e "$source") then
#    if(`echo $oldscripts |& grep $source |& wc -l` != 0) then
	echo -n "Scanning $source "

	###############################################################################
	# Read in parameters from the last mosflm script
	#
	###############################################################################
	# if present, values will be returned in the following variables:
	# MOSFLM	- mosflm executable
	# SG		- space group
	# CELL		- cell dimensions (6)
	# hires		- high resolution limit
	# mosaic	- mosaicity
	
	# inmatrix	- mosflm orientation matrix file
	# outmatrix	- mosflm output matrix file
	
	# beam_center	- center of x-ray beam on detector (in mosflm's convention)
	# distance	- xtal-to-film distance (mm)
	# wavelength	- wavelength (according to the header)
	# GAIN  	- GAIN used
	# POLARISATION  - polarization parameters
	# OVERLOAD	- overloaded pixel value used
	#	
	# EXTRA_REFINE_CARDS  - any extra refinement keywords (multiline, "n"-delimited shell variable)
	# PREAMBLE            - any keywords not handled by Wedger (multiline, "n"-delimited shell variable)
	#
	
	# check that it's safe to read
	set safehead = `ood -cv $source | nawk '{for(i=2;i<=NF;++i) print $i}' | nawk '/\\n/{++n;c=0} {++c} c>1000{exit} END{print n+0}'`
	if($safehead == 0) then
	    echo "not text."
	    continue
	endif
	
	# preprocess script for convenient nawk-ing (no blank lines, no comments, 
	# no shell variables or unexpected characters )
	head -$safehead $source |\
	nawk '$0=="# skip next line"{getline;next} {print}' |\
	nawk '(NF > 0) && (! /^#/){for(i=1;i<=NF;++i){if($i !~ /[\$,]/) printf "%s", $i " "}; print ""}' |\
	nawk '{for(i=1;i<=length;++i){c=substr($0,i,1); \
	    if(c ~ /[ ,\t,\",\!,\047,\140]/){ c = " " }; \
	    if((c ~ /[ ,\t,a-z,A-Z,0-9,.,_,\/]/)||(c == "-")){printf c }else{break}}print ""}' |\
	cat >! $tempfile
	if($status) then
	    # something bad happened during the read
	    echo "unreadable! "
	    rm -f $tempfile
	    continue
	endif

	echo -n "."
	
	############################
	# File Names
	############################

	# get mosflm executable name
	set mosflm = ""
	set temp = `nawk '{for(i=1;i<=NF;++i){if($i ~ /mosflm/){print $i}}}' $tempfile`
	foreach file ( $temp )
	    set temp = `ls -lnL $file |& nawk ' /^-/ && $1 ~ /x/ &&($5 > 3000000){print $NF}'`
	    if(-e "$temp") then
		# try running it
		set MosflmVersion = `echo "GO" | $temp SUMMARY /dev/null |& head -10 |& nawk '/ Version/{ver = substr($0,index($0," Version")+8)+0} /A.G.W. Leslie/{print ver}'`
		rm -f mosflm.lp >& /dev/null
		if("$MosflmVersion" =~ [1-9]*) then
		    # new, viable ececutable found
		    set MOSFLM = "$temp"
		else
		    # no dice
		    set temp = ""
		    set MosflmVersion = ""
		endif
	    endif
	end
	
	# get last mtz file mentioned (in plain text)
	set temp = `nawk '{for(i=1;i<=NF;++i){if($i ~/.mtz$/){print $i}}}' $tempfile | tail -1`
	if($#temp == 1) then
	    if("$temp" =~ *.mtz) set mtzout = "$temp"
	endif
		

	# reset output matrix file name
	set temp = `nawk 'substr(toupper($1), 0, 4) ~ "NEWMAT" {print $2}' $tempfile | tail -1`
	if($#temp == 1) then
	    if(-e "$temp") set outmatrix = "$temp"
	endif
	
	# image filename parameters were pre-read at the beginnning of Wedger

	# from now on, everything is upperase
	nawk '{print toupper($0)}' $tempfile >! $tempfile.upper
	mv $tempfile.upper $tempfile 


	echo -n "."
	
	############################
	# Detector params
	############################

	# get SCANNER or SITE paramerers
	set temp = `egrep "^SCAN|^SITE|^DETECTOR" $tempfile |& tail -1`
	if("$temp" != "") set SCANNER  = "$temp"
	
	# get detector LIMIT paramerers
#	set temp = `nawk '/^LIMIT/ && $2 !~ /^EXCL/' $tempfile | tail -1`
	set temp = `nawk '/^LIMIT/' $tempfile | tail -1`
 	if(("$temp" != "")&&("$SCANNER" !~ "SITE*")) then
	    set LIMITS  = "$temp"
	endif

	# get upper resolution limit
#	set temp = `nawk '$1 ~ /^RESO/{for(i=2;i<=NF;++i){print $i}}' $tempfile | nawk '$1+0>0.3 && $1+0 < 15' | sort -nr | tail -1`
	set temp = `nawk '$1 ~ /^RESO/{for(i=2;i<=NF;++i){print $i}}' $tempfile | nawk '$1+0>0.3 && $1+0 < 15' | tail -1`
	if($#temp == 1) then
	    if("$temp" =~ [0-9]*) then
		set hires  = "$temp"
		set res_choice = script
	    endif
	endif
	# save unsuppoted resolution cards in preamble file
	nawk '$1 ~ /^RESO/ && $2 ~ /^EXCL|^CUT/' $tempfile >> ${tempfile}.preamble

	# get XTF distance
	set temp = `nawk '$1 ~ /^DIST/ && $2+0>10{print $2}' $tempfile |& tail -1`
	if($#temp == 1) then
	    if("$temp" =~ [1-9]*) set distance = "$temp"
	endif
	
	# get TWOTHETA angle
	set temp = `nawk '$1 ~ /^TWOTH/{print $2}' $tempfile |& tail -1`
	if($#temp == 1) then
	    if("$temp" =~ *[0-9]) set two_theta = "$temp"
	endif
	# get two-theta from denzo file (it's negative of cassette rotx)
	set temp = `grep "CASSETTE" $tempfile | nawk 'BEGIN{RS=" "} /^ROTX/{getline; if($1*$1 > 0.25) print -($1+0)}' | head -1`
	if($#temp == 1) then
	    if("$temp" =~ *[0-9]) set two_theta = "$temp"
	    
	    # and correct denzo's distance
	    set temp = `nawk -v angle=$two_theta '$1 ~ /^DISTA/{print $2*cos(angle*3.1415/180)}' $tempfile`
	    if($#temp == 1) then
		if("$temp" =~ [0-9]*) set distance = "$temp"
	    endif
	endif
	
	# get wavelength
	set temp = `nawk '$1 ~ /^WAVE/ && $2>0.1 && $2<3{print $2}' $tempfile |& tail -1`
	if($#temp == 1) then
	    if("$temp" =~ [0-3]*) set wavelength = "$temp"
	endif
	# get beam divergence
	set temp = `nawk '$1 ~ /^DIVERGE/{print $2, $3}' $tempfile |& tail -1`
	if($#temp > 0) then
	    if("$temp" =~ 0.*) set DIVERGENCE = "$temp"
	endif
	# get spectral dispersion
	set temp = `nawk '$1 ~ /^DISPER/ && $2+0>0{print $2}' $tempfile |& tail -1`
	if($#temp == 1) then
	    if("$temp" =~ 0.0*[0-9]) set DISPERSION = "$temp"
	endif
	# get beam center
	set temp = `nawk '$1 == "BEAM"' $tempfile |& tail -1`
	if($#temp > 3) then 
	    if("$temp[2]" =~ SWUNG*) set SWING = "SWUNG_OUT"
	    set temp = `echo BEAM $temp[3] $temp[4]`
	endif
	if($#temp == 3) then
	    if(("$temp[2]" =~ [1-9]*)&&("$temp[3]" =~ [1-9]*)) then
		set beam_center = `echo $temp[2] $temp[3]`
	    endif
	endif
	# get beam center from denzo files (beam center is REALLY important to get right)
	set temp = `nawk '/BEAM /{for(i=2;i<NF;++i) if(($i ~ /BEAM/)&&($(i+1) ~ /^[1-9]/)){if($(i-1)=="X"){X=$(i+1)} if($(i-1)=="Y"){Y=$(i+1)} }} END{if(X!="" && Y!="") print X, Y}' $tempfile`
	if($#temp == 2) then 
	    # must be two numbers
	    set DENZO_center = "$temp"

	    # fix bass-ackwards denzo MAR convention? 
	    set temp = `nawk '/^FORMAT/ && / MAR/' $tempfile |& head -1`
	    if("$temp" == "") set temp = `nawk '/^RADIAL OFFSET/ && /ANGULAR OFFSET/' $tempfile |& head -1`
	    if("$temp" != "") then
		# must be from a MAR frame, so convert it (later)
		if("$Site" =~ *mar*) then
		    set beam_center = `echo "$DENZO_center $Site" | nawk '{print $2, $NF-$1}'`
		    unset DENZO_center
		else
		    # leave $DENZO_center for later?
		endif
	    else
		# probably the correct beam center (raxis, ADSC)
		set beam_center = `echo "$DENZO_center"`
		unset DENZO_center
	    endif

	    # since this is a denzo file, certain keywords will be wrong...
	    foreach card ( profile background write fit box )
		grep -iv $card $tempfile >! ${tempfile}.filtered
		mv ${tempfile}.filtered $tempfile
	    end	    
	endif
	
	# get GAIN used
	set temp = `nawk '$1 == "GAIN"{if($2+0 > 0) print $2+0}' $tempfile |& tail -1`
	if($#temp == 1) then
	    if("$temp" =~ [0-9]*) set GAIN = "$temp"
	endif

	# get polarization
	set temp = `nawk '$1 ~ /^POLAR/' $tempfile |& tail -1`
	if($#temp == 2) then
	    if("$temp[$#temp]" =~ MONO*) then
		# graphite
		set POLARISATION = "MONOCHROMATOR"
	    endif
	    if(("$temp[$#temp]" =~ PIN*)||("$temp[$#temp]" =~ MIRR*)) then
		# no polarization
		set POLARISATION = "MIRRORS"
	    endif
	endif
	if(("$temp[$#temp]" =~ *[0-9]*)&&("$temp[$#temp]" !~ *[A-Z]*)) then
	    # probably "polarization synchrotron <x>"
	    set temp = `echo $temp[$#temp] |& nawk '{print $1+0}'`
	    set POLARISATION = "SYNCHROTRON $temp"
	endif
	
	# get polarization from denzo file
	set temp = `nawk '$1 ~ /^MONOCHR/{print $NF}' $tempfile |& tail -1`
	if("$temp" =~ [0-9,.]*) then
	    set POLARISATION = "SYNCHROTRON $temp"
	    set temp = `echo $temp | nawk '{print $1+0}'`
	    if("$temp" == 0) set POLARISATION = "MIRRORS"
	else
	    if("$temp" =~ FILT*) set POLARISATION = "MIRRORS"
	    if("$temp" =~ GRAPH*) set POLARISATION = "MONOCHROMATOR"
	endif

	# get OVERLOAD pixel value
	set temp = `nawk '$1 ~ /^OVER/{for(i=1;i<NF;++i){if($i ~ /CUT/) printf "%.0f\n", $(i+1)+0}}' $tempfile |& tail -1`
	if($#temp == 1) then
	    if($temp > 1000) set OVERLOAD = "$temp"
	endif

	# get SDCORR for scala? 
	set temp = `nawk '$1 ~ /^SDCORR/ && NF>3 && $2>0.5 && $NF+0<0.2 && $NF+0>0' $tempfile |& tail -1`
	if("$temp" != "") then
	    set SDCORR = `echo $temp | nawk '{print $2, $3, $4}'`
	    unset DEFAULT_SDCORR
	endif

	echo -n "."

	############################
	# Xtal params
	############################

	# get Space Group
	set temp = `nawk '$1 ~ /^SYMM/{print $2}' $tempfile |& tail -1`
	if($#temp == 1) then
	    # make sure variable has proper form
	    if("$temp" =~ [1-9]* && $?CLIBD) then
		# recognize numerical SG
		set SGnum = "$temp"
		set temp = `nawk -v num=$SGnum '$1==num && NF>5{print $4}' ${CLIBD}/symop.lib `
	    endif
	    if("$temp" =~ [PpCcIiFfRrHh][1-6]*) set SG = "$temp"
	else
	    # look for alternative keywords
	    set temp = `nawk '/^SPACE GR/{print $3}' $tempfile`
	    if($#temp == 1) then
		if("$temp" =~ [PpCcIiFfRrHh][1-6]*) then
		    set SG = "$temp"
		    set SG_choice = script
		endif
	    endif
	endif
	# get CELL parameters (six numbers > 10)
	set temp = `nawk '/CELL /{for(i=1;i<=NF;++i){if($i+0 > 10) printf $i+0 " "} print ""}' $tempfile |& tail -1`
	if($#temp == 6) then
	    foreach arg ( $temp )
		# make sure entries are numbers
		if($arg !~ [1-9]*) set temp = ""
	    end
	    if("$temp" != "")  set CELL = `echo $temp`
	endif
	
	# get mosaicity
	set temp = `nawk '$1 ~ /^MOSA/ && NF>1{print $2}' $tempfile |& tail -1`
	if($#temp == 1) then
	    # change even if "fixmosaicity" set, since reading from script is like a manual set
	    if("$temp" =~ [0-5]*) set mosaic = "$temp"
	endif
		
	
	############################
	# Refinement params
	############################

	#
	#
	# Postrefinement options
	set temp = `grep "POST" $tempfile | grep "SEGMENT" | nawk '{print $3}'`
	if($#temp == 1) then
	    if("$temp" =~ [1-9]*) then
		# this was a postrefinement script (in segments)
		set integrate = no
		set postref   = yes
		set mosflm_postref_segs = "$temp"
		
		# now look for width of segments
		set temp = `nawk '$1 ~ /^PROCESS/{print $3 - $2 + 1}' $tempfile | head -1`
		if($#temp == 1) then
		    if("$temp" =~ [1-9]*) set frames_per_segment = "$temp"
		endif
	    endif
	else
	    # this was an integration run
	    set temp = `grep "PROCESS" $tempfile | nawk '$2 !~ /^[0-9]/ && $4 !~ /^[0-9]/{print $4 - $2 + 1}' `
	    if($#temp == 1) then
		set integrate = yes
                
                # import processing limits from this script
                if($temp > 0) set number_of_frames = $temp
	    endif
	endif
	# import total number of frames?
	set temp = `nawk '/^PROCESS/{print $2; print $4}' $tempfile | sort -n | nawk '/[0-9]/' | nawk 'NR==1{f=$1} {l=$1} END{if(NR==2) print l-f+1}'`
	if($#temp == 1) then
	    if(("$number_of_frames" == "")&&($temp > 0)) set number_of_frames = $temp
	endif
	#
	#
	############################
	# Fancy features
	############################
	#
	set temp = `grep "POSTREF OFF" $tempfile `
	if($#temp) then
	    set postref = no
	else
	    set postref = yes
	endif
	
#	set temp = `grep "POSTREF" $tempfile | grep -i "USEBEAM" `
#	if($#temp) then
#	    set usebeam	= yes
#	else
#	    set usebeam	= no
#	endif
	
	set temp = `grep "POSTREF" $tempfile | grep -i "FIX" `
	if($#temp) then
	    set fixcell = yes
	else
	    set fixcell = no
	endif
	
	set temp = `grep "POSTREF" $tempfile | grep -i "BEAM 0" `
	if($#temp) then
	    set fixmosaicity = yes
	else
	    set fixmosaicity = no
	endif
	
	grep "REFI" $tempfile >& /dev/null
	if(! $status) then
	    set temp = `grep "REFI" $tempfile | grep -i "YSCALE" `
	    if($#temp) then
		set fixyscale = yes
	    else
		set fixyscale = no
	    endif
	endif
	
	# extract "ADD" oscillation and starting phi if frames are not different
	set temp = `nawk '$1 ~ /^IDEN/{print $2}' $source`
	if(("$temp" == "$frameprefix")||("$temp" == "")) then
	    # probably reprocessing same frames
	    # Look for "add" card in the script
	    set temp = `nawk '/ ADD / && /PROCES/{print substr($0, index($0, " ADD")+4)+0}' $tempfile |& head -1`
	    if("$temp" =~ [0-9]*) set add = "$temp"
	    set temp = `nawk '/ ANGLE /{print substr($0, index($0, " ANGLE")+6)}' $tempfile |& nawk '$1 !~ /A-Z/{print $1+0;exit}'`
	    if("$temp" =~ [0-9]*) set osc = "$temp"
	    set temp = `nawk '/ START /{print substr($0, index($0, " START")+6)}' $tempfile |& nawk '$1 !~ /A-Z/{print $1+0;exit}'`
	    if("$temp" =~ *[0-9]*) set phi0 = "$temp"
	else
	    # must not have processed these data yet
	    set NEW
	endif

	echo -n "."
	
	############################
	# Accumulate PREAMBLE list of MOSFLM keywords not handled by Wedger Elves (capitalized)
	############################
#	set PREAMBLE = "$PREAMBLE"`egrep "$PASSTHRU_CARDS" $tempfile | nawk 'BEGIN{ORS="n"} {print}'`
	egrep "$PASSTHRU_CARDS" $tempfile >> ${tempfile}.preamble
	# allow for new subkeywords too
	nawk '$1 ~ /^LIMIT/ && $2 ~ /^EXCLUDE/' $tempfile >> ${tempfile}.preamble

	############################
	# Accumulate list of "extra" refinement options not handled by Wedger Elves (capitalized)
	############################
#	nawk '{$0 = toupper($0)} /^POST/' $source | grep -iv " SEGM" | grep -iv " ADD" |\
	nawk '{$0 = toupper($0)} /^POST/' $source | grep -iv " SEGM" |\
	 grep -iv "FIX ALL" | grep -iv " OFF"   >! ${tempfile}.extra_refine_cards

	nawk '{$0 = toupper($0)} /^REFI/' $source | grep -iv "FIX YSCALE" |\
	grep -iv "RESID 100" >> ${tempfile}.extra_refine_cards
	
	# accumulate this stuff into one variable
#	set EXTRA_REFINE_CARDS = "$EXTRA_REFINE_CARDS"`nawk 'BEGIN{ORS="n"} {print}' $tempfile`
	

	# clean up
	rm -f ${tempfile} >& /dev/null
	
	echo "."
	
	# skip rest of scans
	continue
    endif

end

# process preamble file into a variable ( temporary file might get deleted )
set temp = `cat ${tempfile}.preamble |& wc -l`
if("$temp" > 0) then
    echo "Hang on ... "

    # standardize cards and remove completely identical entries
    cat ${tempfile}.preamble |\
    nawk '{for(i=1;i<=NF;++i){s = s " " $i} print substr(s,2); s=""}' |\
    nawk '{list[toupper($0)]==$0} END{for(card in list){print card}}' >! ${tempfile}
    mv ${tempfile} ${tempfile}.preamble

    # watch out for huge files
    set temp = `cat ${tempfile}.preamble | wc -c`
    if($temp > $MAXLINE) then
	echo "WARNING: too many passthru cards ... truncating list."
	nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}' ${tempfile}.preamble >! ${tempfile}
	mv ${tempfile} ${tempfile}.preamble 
    endif
    
    # import preamble file into a variable (check it later)
    set PREAMBLE = `nawk 'BEGIN{ORS="n"} NF != 0' ${tempfile}.preamble`
    rm -f ${tempfile}.preamble
endif

# process extra refine cards into a variable too
set temp = `cat ${tempfile}.extra_refine_cards |& wc -l`
if("$temp" > 0) then
    # remove completely identical entries
    cat ${tempfile}.extra_refine_cards |\
    nawk '{for(i=1;i<=NF;++i){printf "%s ", $i} print ""}' |\
    nawk '{list[toupper($0)]==$0} END{for(card in list){print card}}' >! ${tempfile}
    
    # watch out for huge files
    set temp = `cat ${tempfile} | wc -c`
    if($temp > $MAXLINE) then
	echo "WARNING: too many postref cards ... truncating list."
	nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}' $tempfile >! ${tempfile}.extra_refine_cards
	mv ${tempfile}.extra_refine_cards $tempfile
    endif
    
    # import refine cards file into a variable (get rid of blank lines)
    set EXTRA_REFINE_CARDS = `nawk 'BEGIN{ORS="n"} NF != 0' $tempfile`
endif

# clean up
rm -f ${tempfile}* >& /dev/null

goto ReturnGetParamsFromSources

exit





autoindex:
onintr
##########################################################################

   ##    #    #   #####   ####      #    #    #  #####   ######  #    #
  #  #   #    #     #    #    #     #    ##   #  #    #  #        #  #
 #    #  #    #     #    #    #     #    # #  #  #    #  #####     ##
 ######  #    #     #    #    #     #    #  # #  #    #  #         ##
 #    #  #    #     #    #    #     #    #   ##  #    #  #        #  #
 #    #   ####      #     ####      #    #    #  #####   ######  #    #

##########################################################################
set autoindexing
unset LAST_RUN

# check the mosaicity, if it has not been set, pick a reasonable value
if("$mosaic" == "auto") then
    set mosaic = `echo "$osc" | nawk '$1+0>0{print $1/2}'`
    if("$mosaic" == "") set mosaic = 1
    
    set temp = `echo "$MosflmVersion" | nawk '/[0-9]/{printf "%d", $1*100}'`
    if("$temp" > 619) set mosaic = "estimate"    
endif


set temp = "Yes"
if(! $?AUTO && ! $?HURRY) then
    # Brief report on intentions (in case user didn't read the first one carefully)

    cat << EOF

	About to autoindex: 
	$framedir/${template}

	using:       $MOSFLM v $MosflmVersion

	beam center: $beam_center
	distance:    $distance mm
	wavelength:  $wavelength $ANG
	cell:        $CELL
	space group: $SG

Is this correct? [$temp]
EOF
    echo -n "$PROMPT"
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
else
    # autoindexing in fully-automatic mode is suspicious, user might be doing this for every wedge (WRONG!)
    echo ""
    echo "REMEMBER: You should only autoindex once per crystal."
    echo "          Autoindexing two wedges from the same crystal might result in incompatible"
    echo "          cell axis assignments, requiring reindexing of one wedge before mergeing."
    echo ""
endif
if("$temp" !~ [Yy]*) then

    # ask user about parameters again
    set input = ""
    if(("$temp" !~ [Nn]*)||($#temp > 1)) set input = "$temp"
    goto Questionaire
endif

if("$number_of_frames" == "") set number_of_frames = `echo "$last $first" | nawk  '{print $1-$2+1}'`

# generate a mosflm "start" script
################################################################################################
echo "creating autoindex.com..."
if(-e autoindex.inp) mv autoindex.inp autoindex.inp.old
if("$PREAMBLE" != "") then
    cat << EOF-preamble >! autoindex.inp

# the following keywords were not understood by the Wedger elves, but passed on
# because they resemble mosflm commands.
# ----
`echo "$PREAMBLE" | nawk 'BEGIN{RS="n"} {print}'`
# ----
EOF-preamble
else
    echo ""  >! autoindex.inp
endif
# make other printing decisions now
set print_mosaic = 1
set print_swing = ""
set print_cell  = ""
set print_sg    = ""
set mosflmSG    = $SG
if("$SG" =~ P2*2*2* ) set mosflmSG = P222
if("$SG" =~ R* || "$SG" =~ H*) set mosflmSG = $SG_number
if("$mosaic" =~ *[0-9]*) set print_mosaic = "$mosaic"
set temp = `echo "$two_theta" | nawk '{printf "%d", $1+0}'`
if("$temp" != "0")     			set print_swing = "SWUNG_OUT "
#if($#CELL == 6)                         set print_cell  = "CELL     KEEP $CELL"
if($#CELL != 6)                         set print_cell  = "#CELL     KEEP 100 100 100 90 90 90"
if(("$SG" != "unknown")&&($#CELL == 6)) set print_sg    = "SYMMETRY      $mosflmSG"
if(("$SG" != "unknown")&&($#CELL == 6)) set print_cell  = "CELL     KEEP $CELL"
if("$SG" == "unknown")                  set print_sg    = "#SYMMETRY      P1"
set test = `echo $MosflmVersion | awk '{print ($1 >= 6.2)}'`
if("$test" && ("$SG" != "unknown")) then
    # this should not crash
    set print_sg    = "SYMMETRY      $mosflmSG"
endif
set print_overload = "OVERLOAD CUTOFF $OVERLOAD"
set test = `echo $OVERLOAD | nawk '{print ($1+0<1000)}'`
if($test) then
    set print_overload = ""
endif
set print_gain = "GAIN $GAIN"
set test = `echo $GAIN | nawk '{print ($1+0<=0)}'`
if($test) then
    set print_gain = ""
endif

cat << EOF_auto >> autoindex.inp
# Detector parameters (range, quantum gain, etc.)
$SCANNER
$print_overload
$print_gain
$LIMITS

# Beam parameters (i.e. (delta-lambda)/lambda, H,V divervence in degrees)
WAVELENGTH    $wavelength
DISPERSION    $DISPERSION
DIVERGENCE    $DIVERGENCE
POLARISATION  $POLARISATION

# Alignment parameters
DISTANCE      $distance
BEAM          ${print_swing}$beam_center
TWOTHETA      $two_theta
#
NEWMATRIX  auto.mat

# Crystal parameters
${print_cell}
${print_sg}
RESOLUTION $hires
MOSAIC     $print_mosaic

# frame filename breakdown
DIRECTORY    $framedir
IDENTIFIER   $frameprefix
EXTENSION    $ext
$TEMPLATE
#
FINDSPOTS MINX 0.1 MINY 0.1 MAXX 5 MAXY 5 SPLIT 0.2 0.2
#
EOF_auto
unset print_swing
unset print_cell
unset print_sg

if("$Site" =~ "4*ADSC*") then
    # fix background stripe problem with ADSC frames
    cat << EOF-adsc >> autoindex.inp
# make sure background stripe is above "window pane"
FINDSPOTS YOFFSET 3
EOF-adsc
endif

if(! -e dps_index.com) then
echo "creating dps_index.com"
cat << EOF-script >! dps_index.com
#! /bin/csh -f
#
#	script for autoindexing mosflm spot output with dps_index
#	without the need for a GUI
#
########
# 
# use the most recently-created .spt file by default
set spotfile  = \`ls -1rt *.spt | tail -1\`
set outmatrix = dps.mat
set tempfile  = dps_temp

# camera settings (not available in *.spt file)
set wavelength  = ""
set distance    = ""
set two_theta    = 0
set beam_center = ""

# crystal parameters (overridden by keywords in script)
set CELL        = ""
set SG          = ""
set max_cell    = 300
set hiRES       = 1
set loRES       = 1000

goto Setup
Help:
############################################################
cat << EOF
usage: dps_index.com mosflm.spt 1.0A 100mm P212121
  or
usage: dps_index.com mosflm.spt mosflm.com P212121

where:
mosflm.spt  - the "spot" file (picked with mosflm)
1.0A        - the x-ray wavelength
100mm       - the xtf distance
mosflm.com  - a mosflm script containing CELL, DIST, WAVE, etc., 
P212121     - space group to select (optional)
3-20A	    - resolution range to use (optional)
50sig	    - I/sigma cutoff to use (default: 0)
300	    - maximum cell edge (default: \$max_cell)

EOF
exit 9
Return_from_Setup:

if("\$wavelength" == "") goto Help
if("\$distance" == "") goto Help

############################################################
# retrieve useful parameters from the mosflm spot file
echo "\$0 \$*"
echo "using \${spotfile} (\$frames images)"
set rotation    = \`nawk 'NR==1{rot=\$5} NR==2{print (360-rot+180*\$1)%360;exit}' \$spotfile\`
set ysign       = \`nawk 'NR==2{print 1-(\$1*2);exit}' \$spotfile\`
set raster      = \`nawk '{print \$3;exit}' \$spotfile\`
set yscale      = \`nawk '{print \$4;exit}' \$spotfile\`
set beam_center = \`nawk 'NR==3 && NF==2{print;exit}' \$spotfile\`
set beamstop    = \`echo \$beam_center \$raster \$yscale | nawk '{printf "r %d s %d", \$1/\$3,\$2*\$4/\$3}'\`
set sscale      = \`echo \$ysign \$yscale | nawk '{print \$1/\$2}'\`
set mode        = automatic

# are these important?
set phi0        = \`nawk 'NR==4{printf "%.1f", \$4-\$3}' \${spotfile}\`
set phiend      = \`nawk 'NR==4{printf "%.1f", \$4+\$3}' \${spotfile}\`


# report values input into dps_index
echo "wavelength:  \$wavelength"
echo "beam center: \$beamstop"
echo "distance:    \$distance"
echo "2theta:      \$two_theta"
echo "sscale:      \$sscale"
echo "rotation:    \$rotation"
echo "resolution:  \$loRES \$hiRES"
echo "sigma cut:   \$cutoff"
if("\$CELL" != "") then
    echo "Cell: \$CELL"
    set CELL = "target_cell \$CELL"
    set mode = "target_cell"
else
    echo "Cell:      < \$max_cell"
endif
if("\$SG" != "") then
    echo "Space Group: \$SG"
else
    if("\$wrongSGs" != "") echo "Space Group: anything but \$wrongSGs"
endif
echo ""

# convert the mosflm spot file into a DPS peaks file
cat \$spotfile |\\
nawk -v cutoff=\$cutoff 'BEGIN{PI=2*atan2(1,0); print "DPS-PF A2.0"}\\
  NR==1{xwidth = \$3; ywidth = \$3/\$4;}\\
  NF>5 && \$1!="-99.00" && \$1!="-999.00" && \$6+0>0{\\
    if(\$5/\$6<cutoff) next; \\
    print \$1/xwidth, \$2/ywidth,\$4*PI/180}' |\\
cat >! peaks.file

set temp = \`head -1 \$spotfile\`
if("\$temp" =~ DPS-PF*) then
    cp \$spotfile peaks.file
endif

# now do DPS indexing
foreach round ( 1 2 3 )
dps_index << EOF | tee \${tempfile}.log
mode \$mode
\$CELL
\$target_sym
resolution \$loRES \$hiRES
cell \$max_cell
wavelength \$wavelength
rastersize \$raster
distance \$distance
twotheta \$two_theta
beamstop \$beamstop
film_rotation \$rotation
sscale \$sscale
PEAKS peaks.file \$phi0 \$phiend
omfile auto.om
EOF
if(! -e PEAKS_WITH_PHIS) then
    exit 9
endif
# keep re-cycling peak file
mv PEAKS_WITH_PHIS peaks.file

set RMS = \`nawk '/RMS/{printf "%d", \$NF}' \${tempfile}.log\`
rm -f \${tempfile}.log
if(\$RMS < 3) break
end

# score different lattice possibilities
dps_bravais << EOF | tee \${tempfile}.log
mode bravais
omfile auto.om
EOF

# organize possibilities in terms of space groups
cat \${tempfile}.log |\\
nawk -v library=\$CLIBD/symop.lib '/^Lattice:/{\\
	solution=\$2; crys_sys=\$4; score=\$6; source="|";\\
	sys = substr(\$4,1,1); lattice = substr(\$4,2); \\
	getline;getline;getline;getline; cell=substr(\$0,10);\\
	if(sys=="a") sys = "TRICL"; \\
	if(sys=="m") sys = "MONOC"; \\
	if(sys=="o") sys = "ORTHO"; \\
	if(sys=="t") sys = "TETRA"; \\
	if(sys=="h") sys = "TRIGO"; \\
	if(sys=="c") sys = "CUBIC"; \\
	while(getline < library){ \\
	    if(\$5 ~ /^PG/ && ! /m/ && ! /bar/ && \$1 < 500){\\
		SYS=substr(\$6,1,5)\\
		if(substr(\$4,1,1)==lattice && (SYS==sys || (SYS=="HEXAG" && sys=="TRIGO"))){\\
		    print \$1, substr(\$5,3), \$4, crys_sys, \$6, solution, score, cell, source;\\
		}\\
	    }\\
	}; close(library);}' |\\
sort +0nr -1 +6n -7  |\\
nawk '! seen[\$3]{print; seen[\$3]=1}' |\\
nawk '{a=\$8; b=\$9; c=\$10; A=\$11; B=\$12; G=\$13;latt=\$5}\\
    \$5 == "MONOCLINIC" { A=90; ; G=90}\\
    \$5 == "ORTHORHOMBIC" {A=90; B=90; G=90}\\
    \$5 == "TETRAGONAL" || \$5 == "TRIGONAL" || \$5 == "HEXAGONAL" {\\
	a=b=(a+b)/2; A=90; B=90; G=120;}\\
    \$5 == "TETRAGONAL" {G=90}\\
    \$5 == "CUBIC" {a=b=c=(a+b+c)/3; A=90; B=90; G=90}\\
    {print \$0, a, b, c, A, B, G}' |\\
cat >! \${tempfile}.sg
# format: SG_num PG SG crys_sys lattice solution penalty cell source newcell

# clear undesirable SG choices from the list of possibilities
echo " \$wrongSGs LIST " |\\
nawk 'BEGIN{RS=" "} NF==1' |\\
cat - \${tempfile}.sg |\\
nawk 'NF==1{bad[\$1]=1} \\
           list && ! bad[\$3] && ! bad[\$4] && ! bad[\$5] {print}\\
         /LIST/{list=1}' |\\
cat >! \${tempfile}filtered
mv \${tempfile}filtered \${tempfile}.sg
# format: SG_num PG SG crys_sys lattice solution penalty cell source newcell

# automatically pick space group with good fit
if("\$SG" == "") then
    # choose one...
    set solution = \`nawk '\$7<1{print \$6; exit}' \${tempfile}.sg\`
    if("\$solution" == "") then
	set solution = \`nawk '{print \$6}' \${tempfile}.sg | tail -1\`
    endif
    set SG = \`nawk -v solution=\$solution '\$6==solution{print \$3}' \${tempfile}.sg | tail -1\`
    echo "selected \$SG as a representative of the point group"
endif
set solution = \`nawk -v SG=\$SG '\$3==SG{print \$6;exit}' \${tempfile}.sg\`

bravais_to_mosflm \$solution \${tempfile}.log /dev/null \${outmatrix} 0.0 \${wavelength} no_update

condense_bravais \${tempfile}.log bravais.sum
set CELL = \`nawk 'NF==6{print;exit}' \${outmatrix}\`
if(\$#CELL != 6) then
    # do it ourselves...
    cat \${tempfile}.log |\\
    nawk -v solution=\$solution '/Lattice/ && \$2==solution{\\
	getline; mid=\$0; getline; last=\$0; getline; \\
	print \$0; print mid; print last; \\
	getline; print}' |\\
    nawk -v wave=\$wavelength 'NF==3{printf "%12.8f%12.8f%12.8f\\n", \$1*wave, \$2*wave, \$3*wave}' |\\
    cat >! \${outmatrix}
    cat \${tempfile}.sg |\\
    nawk -v SG=\$SG '\$3==SG{\\
	    printf "%12.3f%12.3f%12.3f\\n", 0, 0, 0;\\
	    printf "%12.7f%12.7f%12.7f\\n", 1, 0, 0;\\
	    printf "%12.7f%12.7f%12.7f\\n", 0, 1, 0;\\
	    printf "%12.7f%12.7f%12.7f\\n", 0, 0, 1;\\
	    printf "%12.4f%12.4f%12.4f%12.4f%12.4f%12.4f\\n", \$15, \$16, \$17, \$18, \$19, \$20;\\
	    printf "%12.3f%12.3f%12.3f\\n", 0, 0, 0; exit}' |\\
    cat >> \${outmatrix}
    set CELL = \`nawk 'NF==6{print;exit}' \${outmatrix}\`
endif


echo "SYMM \$SG"
echo "CELL \$CELL"
echo "MATRIX \${outmatrix}"

# clean up
exit
rm -f peaks.file
rm -f PEAKS_WITH_PHIS
rm -f auto.om
rm -f \${tempfile}.log
rm -f \${tempfile}.sg
rm -f bravais.sum
rm -f b_to_m.in
rm -f b_to_m.out
rm -f analyse.out
exit
############################################################


Setup:

nawk 'BEGIN{exit}' >& /dev/null
if(\$status) alias nawk awk
set wrongSGs
set userSG
set cutoff = 0

# scan the command line for files
set i = 0
while( \$i < \$#argv )
    @ i = ( \$i + 1 )
    @ nexti = ( \$i + 1 )
    @ lasti = ( \$i - 1 )
    if(\$nexti > \$#argv) set nexti = \$#argv
    if(\$lasti < 1) set lasti = 1
    set arg = "\$argv[\$i]"
    set ARG = \`echo "\$arg" | nawk '{print toupper(\$1)}'\`
    
    if("\$arg" =~ *.spt) then
	if(! -e "\$arg") then
	    echo "WARNING: \$arg does not exist! "
	    continue
	endif
	set spotfile = "\$arg"
	
	continue
    endif
    
    if(-e "\$arg") then
	# assume this is the mosflm.com file
	set temp = \`nawk '/^WAVE/ && \$2+0>0.1 && \$2+0<10{print \$2}' \$arg\`
	if("\$temp" != "") set wavelength = "\$temp"
	set temp = \`nawk '/^DIST/ && \$2+0>10 && \$2+0<1000{print \$2}' \$arg\`
	if("\$temp" != "") set distance = "\$temp"
	set temp = \`nawk '/^TWOTHETA/ && \$2+0>-90 && \$2+0<90{print \$2}' \$arg\`
	if("\$temp" != "") set two_theta = "\$temp"

	# get (and check) space group
	set temp = \`nawk '/^SYMM/ && \$2 ~ /^[PpCcIiFfRrHh][1-6]/{print \$2}' \$arg\`
	set temp = \`nawk -v SG=\$temp '\$4==SG{print \$4;exit}' \${CLIBD}/symop.lib\`
	if("\$temp" != "") set SG = "\$temp"

	# get unit cell
	set temp = \`nawk '/CELL /{for(i=1;i<=NF;++i){if(\$i+0 > 10) printf \$i+0 " "} print ""}' \$arg |& tail -1\`
	if(\$#temp == 6) then
	    foreach param ( \$temp )
		# make sure entries are numbers
		if(\$param !~ [1-9]*) set temp = ""
	    end
	    if("\$temp" != "")  set CELL = \`echo \$temp\`
	endif

	# get upper resolution limit
	set temp = \`nawk '\$1 ~ /^RESO/{for(i=2;i<=NF;++i){print \$i}}' \$arg | nawk '\$1+0>0.3 && \$1+0 < 15' | tail -1\`
	if(\$#temp == 1) then
	    if("\$temp" =~ [0-9]*) set hiRES  = "\$temp"
	endif
	continue
    endif
    
    # now read things that aren't files

    # check for space groups
    if("\$ARG" =~ [PCIFHR][1-6]*) then
	set temp = "\$ARG"
	if("\$arg" =~ [PCIFHR][1-6]*) set temp = "\$arg"
	set temp = \`nawk -v SG=\$temp '\$4 == SG {print \$4;exit}' \$CLIBD/symop.lib\`
	if("\$temp" == "") then
	    # check for "pseudo-spacegroup" language
	    #set temp = \`echo "\$ARG" | nawk 'toupper(\$1) ~ /[PC]2212|[PC]2122|P21221|P22121/'\`
	    # these are okay too, reindexing engine will understand
	endif
	if("\$temp" != "") then
	    if(\$?NO) then
		# user doesn't want this space group
		set wrongSGs = ( \$wrongSGs \$temp )
		# check and see if \$SG is in \$wrongSGs
		foreach wrongSG ( \$wrongSGs )
		    if("\$SG" == "\$wrongSG") set SG = ""
		end
		continue
	    endif
	    # user prefers this space group
	    set userSG = "\$temp"
	    continue
	endif
    endif
    
    # allow disqualification of point groups
    if("\$ARG" =~ PG[1-6]*) then
	# see if this is really a point group
	set temp = \`nawk -v PG=\$ARG '\$5 == PG && ! /m/ && ! /bar/ {print \$4;exit}' \$CLIBD/symop.lib\`
	if("\$temp" != "") then
	    if(\$?NO) then
		# user doesn't want this point group
		set wrongSGs = ( \$wrongSGs \$ARG )
		
		# check and see if \$SG is in \$wrongSGs
		foreach wrongSG ( \$temp )
		    if("\$SG" == "\$temp") set SG = ""
		end
		continue
	    endif
	    # user prefers this point group? 
	    set SG = "\$temp[1]"
	    continue
	endif
    endif
    
    # allow disqualification of lattice types
    if(("\$ARG" =~ *IC)||("\$ARG" =~ *ONAL)) then
	# see if this is really a crystal system
	set temp = \`nawk -v sys=\$ARG '\$6 == sys && ! /m/ && ! /bar/ {print \$4;exit}' \$CLIBD/symop.lib\`
	if("\$temp" != "") then
	    if(\$?NO) then
		# user doesn't want these space groups
		set wrongSGs = ( \$wrongSGs \$ARG )
		
		# check and see if \$SG is in \$wrongSGs
		foreach wrongSG ( \$temp )
		    if("\$SG" == "\$wrongSG") set SG = ""
		end
		continue
	    endif
	    # user prefers this crystal system? 
	    set SG = "\$temp[1]"
	    continue
	endif
    endif
    
    # allow disqualification of a bravais lattice
    if(("\$arg" =~ [chotma][PICFR])) then
	# see if it's really a bravais lattice
	cat \${CLIBD}/symop.lib |\\
	nawk -v brav=\$arg 'BEGIN{sys=substr(brav,1,1);  type = substr(brav,2);\\
	if(sys=="a") sys = "TRICL"; \\
	if(sys=="m") sys = "MONOC"; \\
	if(sys=="o") sys = "ORTHO"; \\
	if(sys=="t") sys = "TETRA"; \\
	if(sys=="h") sys = "TRIGO"; \\
	if(sys=="c") sys = "CUBIC";}\\
	\$5 ~ /^PG/ && ! /m/ && ! /bar/ {\\
	    SYS=substr(\$6,1,5); TYPE=substr(\$4,1,1);\\
	    if(TYPE==type && (SYS==sys || (SYS=="HEXAG" && sys=="TRIGO"))){\\
		    print \$4}}' |\\
	cat >! \${tempfile}brav
	set temp = \`cat \${tempfile}brav\`
	rm -f \${tempfile}brav >& /dev/null
	if("\$temp" != "") then
	    if(\$?NO) then
		# user doesn't want these space groups
		set wrongSGs = ( \$wrongSGs \$arg )
		
		# check and see if \$SG is in \$wrongSGs
		foreach wrongSG ( \$temp )
		    if("\$SG" == "\$wrongSG") set SG = ""
		end
		continue
	    endif
	    # user prefers this crystal system? 
	    set SG = "\$temp[1]"
	    continue
	endif
    endif
    
    if("\$arg" =~ [0-9]*) then
	# we have a number
	if(("\$arg" =~ *A)||("\$argv[\$nexti]" == "A")) then
	    # user-preferred resolution limits
	    set temp = \`echo "\$arg" | nawk 'BEGIN{FS="-"} \$1+0 > 0.1{print \$1+0} \$2+0 > 0.1{print \$2+0}'\`
	    if(\$#temp != 1) then
		set temp = \`echo \$temp | nawk '\$1>\$2{print \$1, \$2} \$2>\$1{print \$2, \$1}'\`
		if(\$#temp == 2) then
		    # a range 3-10A is a resolution
		    set hiRES = \`echo "\$temp[2]" | nawk '{print \$1+0}'\`
		    set loRES = \`echo "\$temp[1]" | nawk '{print \$1+0}'\`
		    continue
		endif
	    else
		# single 1.1A is a wavelength
		set wavelength = \`echo "\$arg" | nawk '{print \$1+0}'\`
		continue
	    endif
	endif
	
	if(("\$arg" =~ *mm)||("\$argv[\$nexti]" == "mm")) then
	    # distance is expressed in mm
	    set distance = \`echo "\$arg" | nawk '{print \$1+0}'\`
	    continue
	endif
	
	if(("\$arg" =~ *sig)||("\$argv[\$nexti]" == "sig")) then
	    # sigma cutoff for spot use
	    set cutoff = \`echo "\$arg" | nawk '{print \$1+0}'\`
	    continue
	endif
	
	# interpret free integers as max cell edge?
	set int = \`echo "\$arg" | nawk '{printf "%d", \$1+0}'\`
	if("\$arg" == "\$int") then
	    set max_cell = \$int
	endif
    endif
    
    
    # flags and switches
    if("\$ARG" == "CELL") then
	if(\$?NO) set CELL = ""
	continue
    endif
    if("\$ARG" == "SG") then
	if(\$?NO) set SG = ""
	continue
    endif

    unset NO
    if("\$ARG" == NO) set NO
    if("\$ARG" == NOT) set NO
end
# override any misc space-group settings with command-line space group
if("\$userSG" != "") then
    set SG = "\$userSG"
    set wrongSGs = ""
endif

# get the number of images that were peak-picked into this spotfile
set frames = \`nawk '\$NF=="-99.0" || \$NF=="-999.0"' \$spotfile | wc -l\`
set spots = \`nawk 'NF>5 && \$1!="-99.00" && \$1!="-999.00"' \$spotfile | wc -l\`

set target_sym
if("\$SG" != "") then
    # set up target lattice/symm
    set target_sym = \`nawk -v SG=\$SG '\$4==SG{print "target_sym", substr(\$4,1,1), \$6;exit}' \${CLIBD}/symop.lib\`
endif

goto Return_from_Setup
EOF-script
chmod a+x dps_index.com
endif

PickIndexer:
onintr

# check for DPS-in-the-background version of Mosflm
set temp = `echo "$MosflmVersion" | nawk '$1+0>=6.11'`
if("$temp" != "") then
    # a pity that v6.10 crashes with this...
    set background_DPS
endif

# check to see if dps_index is available
set temp = `which dps_index |& nawk 'NF==1 && /dps_index$/'`
if(("$temp" != "")&&(! $?background_DPS)) then
    # this will do...
    set DPS_INDEX
endif

# background is preferable, if DPS indexing can be used
if(($?background_DPS)||($?DPS_INDEX)) then
    set temp = "No"
    echo "Do you want to use the graphics for indexing? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
        echo $temp
    else
        echo -n "$BELL"
	set in = ( $< )
        if("$in" != "") set temp = ( $in )
    endif    
    if(("$temp" =~ [Nn]*)&&($#temp <= 1)) then
	# user is okay with background indexing
	goto Index_again
    endif
    # don't use these then...
    unset background_DPS
    unset DPS_INDEX
    if("$temp" =~ [Yy]*) then
	# don't know why you'd want to do this...
	goto Manual_Index
    else
	# strange answer, send to interpreter
	set input = "$temp"
	goto Questionaire
    endif
endif

# warn about bad indexing situation
set test = `echo $MosflmVersion | awk '{print ($1+0<6)}'`
if(("$test" == "1")&&($number_of_frames < $autoindexing_frames)) then
set temp = "No"
cat << EOF
WARNING: MOSFLM Version $MosflmVersion requires several images
         to index successfully.
	 Recommend you download MOSFLM 6.x or higher, from:
	 ftp://ftp.mrc-lmb.cam.ac.uk/pub/mosflm/
	 wait for some more, widely-separated frames, 
	 or (if you have it) try indexing with denzo.

Do you have ipmosflm 6.x or higher ? [$temp]
EOF
    echo -n "$PROMPT"
    if($?AUTO) then
        echo $temp
    else
        echo -n "$BELL"
	set in = ( $< )
        if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) then
	echo "Okay, starting over... "
	set input = "new executable"
	goto Questionaire
    else
	if(("$temp" !~ [Nn]*)||($#temp > 1)) then
	    # strange answer, send to interpreter
	    set input = "$temp"
	    goto Questionaire
	endif
	# user does not have mosflm 6
    endif
    
    # if mosflm 6 isn't available, try for denzo
    if((-e /usr/local/lib/cr_info)||(-e ~/cr_info)||(-e ./cr_info)) then
	set temp = "Yes"
	echo "Do you want us to try using denzo (you need a $Site licence)? [$temp]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $temp
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	endif
	if("$temp" =~ [Yy]*) goto denzo
	if(("$temp" !~ [Nn]*)||($#temp > 1)) then
	    # strange answer, send to interpreter
	    set input = "$temp"
	    goto Questionaire
	endif
    endif

    echo "Going ahead with indexing in Mosflm $MosflmVersion ... "    
endif

# decide if we need to do an interactive mosflm run
if(("$MosflmVersion" =~ 6*)||($#CELL != 6)||("$SG" == "unknown")) then
    echo ""
    if("$SG" == "unknown") then
	echo "WARNING: non-interactive indexing cannot determine your space group exactly."
	echo "         (but, the elves can pick a close one, and reindex later.)"
    else
	echo "NOTE: non-interactive indexing without a cell is not recommended by AGWL."    
	echo "      (but it does seem to work eventually)."    
    endif
    set Interactive = "PLOT"
    set temp = "No"    
endif
if("$MosflmVersion" =~ 6*) then
    echo ""
    echo "DPS indexing in MOSFLM Version 6.x is very cool,"
    echo "but can only be done in the graphics window! "
    set Interactive = "PLOT"
    if(! $?AUTO) set temp = "Yes"
    set message = "use the superior indexing algorithm"
else
    set message = "autoindex INTERactively"
endif
if("$Interactive" == "PLOT") then
    echo "Do you want to $message (requires graphics)? [$temp]"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo $temp
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if("$temp" =~ [Yy]*) goto Manual_Index
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
	# unexpected answer, send to interpreter
	set input = "$temp"
	goto Questionaire
    endif
    
    # risky indexing without SG, go for broke...
    if("$SG" == "unknown") set autoindexing_frames = 18
endif

# pick frames for mosflm
Index_again:
################################################################################################
if(! $?AUTO) onintr Manual_Index
echo ""
echo "examining frames named ${framedir}/${template} ..."

# build a table of phi values for frames with this name
touch ${tempfile}.phi_list
# get any frames with the right name
#set temp = `ls -1 $framedir |& egrep "${framepattern}"`
# get frames from the wedge only
set first_frame = `echo "$template $first" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`

#set frames = `ls -1 $framedir |& egrep "$framepattern" |& nawk -v first_frame=$first_frame '$0==first_frame,NR<0' | head -$number_of_frames`
set frames = `ls -1 $framedir |& egrep "$framepattern" |& nawk -v first_frame=$first_frame '$0==first_frame,NR<0'`
foreach frame ( $frames )
    set number = `echo $frame $template | nawk '{n=split($1,a,"[\057]"); print substr(a[n],index($2,"\043"))+0}'`
    set phi = ""
    #save phi value
    set img = $framedir/$frame
    if("$Site" =~ *ADSC* || "$Site" =~ *SBC*) then
	set phi = `nawk 'BEGIN{RS="\f"} {print;exit}' $img | egrep "PHI|ROTATION_START" | nawk -F "=" '{print $NF+0; exit}'`
    endif
    if($?RAXIS_SMV) then
	set phi = `nawk 'BEGIN{RS="\f"} {print;exit}' $img | egrep "^ROTATION=" | nawk -F "=" '{print $2+0; exit}'`
    endif
    if(("$Site" =~ *RAXIS*)&&("$swap" != "")&&(! $?RAXIS_SMV)) then
	# get phi value from header
	od -vb -j 524 -N 4 $img |\
	nawk '{for(i=2;i<=5;++i){printf "%d ", 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)};exit}' |\
	nawk '{w=x=$2} $1+$2+$3+$4==0{--w;++x} {print $0, w,x-1}' |\
	nawk '{printf "%c%c%c%c", '$swap'}' | ood -f |\
	nawk '{print $2+0;exit}' |\
	cat >! ${tempfile}phi
	set temp = `nawk '$1>-370 && $1<800 {print $1;exit}' ${tempfile}phi`
	rm -f ${tempfile}phi >& /dev/null
	
	if("$temp" != "") set phi = $temp
    endif
    if("$SCANNER" =~ *MARCCD*) then
	od -bv -j 1024 -N 1024 $img |\
	nawk '{for(i=2;i<=NF;++i){print 64*substr($i,1,1)+8*substr($i,2,1)+substr($i,3,1)}}' |\
	nawk 'NR%4==1{printf "\n%d ", NR+1023} {printf "%d ", $1}' |\
	nawk '/^1052 210 4 0 0/{little=1} /^1052 0 0 20 341/{big=1} \
	     little{print $1, $2+256*($3+256*($4+256*$5))} \
	        big{print $1, $5+256*($4+256*($3+256*$2))}' |\
	nawk '/^1708 /{ print $2/1000}' |\
	cat >! ${tempfile}phi
	set temp = `nawk '$1>-370 && $1<800 {print $1;exit}' ${tempfile}phi`
	rm -f ${tempfile}phi >& /dev/null	
	if("$temp" != "") set phi = $temp
    endif
    if("$phi" == "") then
	# guess
	#set phi = `echo "(( $number - $first ) * $osc) + $phi0" | bc`
	set phi = `echo $number $first $osc $phi0 | nawk '{print (($1-$2)*$3)+$4}'`
    endif
#    nawk '{print ($1 + (360*(1+int($1*$1/360)))) % 360}' >> ${tempfile}.phi_list
    echo "$number $phi" >> ${tempfile}.phi_list
end
# sort in order of increasing phi
#sort -n +1 ${tempfile}.phi_list >! $tempfile
#mv $tempfile ${tempfile}.phi_list

# make up a list of $autoindexing_frames widely-separated images
cat ${tempfile}.phi_list |\
nawk -v n=$autoindexing_frames '{phi[$1] = ($2+360000)%360} NR==1{selected[1]=$1}\
END{for(i=2;i<=n;++i){ best_score = 0; \
    for(image in phi) { score=1;\
	for( j in selected ){\
	    dist = ((360000 + phi[image] - phi[selected[j]]) % 180);\
	    if(dist>90)dist=180-dist;\
	    score *= dist;\
	}\
	if(score > best_score){\
	    best_score = score;\
	    best = image;}}\
  selected[i] = best;}\
for(i in selected){print selected[i]}\
}' >! $tempfile 
set index_images = `sort -un $tempfile`
rm -f $tempfile >& /dev/null

cat ${tempfile}.phi_list |\
nawk -v n=2 '{phi[$1] = ($2+360000)%360} NR==1{selected[1]=$1}\
END{for(i=2;i<=n;++i){ best_score = 0; \
    for(image in phi) { score=1;\
	for( j in selected ){\
	    dist = ((360000 + phi[image] - phi[selected[j]]) % 180);\
	    if(dist>90)dist=180-dist;\
	    score *= dist;\
	}\
	if(score > best_score){\
	    best_score = score;\
	    best = image;}}\
  selected[i] = best;}\
for(i in selected){print selected[i]}\
}' >! $tempfile 
set best_two_index_images = `sort -un $tempfile`
rm -f $tempfile >& /dev/null


# run multiframe, MOSFLM autoindexing
################################################################################################
#echo ""
echo -n "autoindexing on frames $index_images "
echo "" >! autoindex.frames
set FLAGS = ""
if($?background_DPS) then
    # anything fancier?
    set FLAGS = "DPS"
    if(($#CELL == 6)&&("$SG" != "unknown")) then
	#set FLAGS = "DPS PREREFINE" 
    endif
endif
# will this usually work better?
set FLAGS = "$FLAGS THRESH 5"

if("$Site" =~ *RAXIS* || $?BAD_HEADER) then
    foreach img ( $index_images )
	set temp = `egrep "^$img " ${tempfile}.phi_list |& nawk -v osc=$osc '{print $2, $2+osc}'`
	echo "AUTOINDEX $FLAGS IMAGE $img PHI $temp" >> autoindex.frames
    end
else
    echo "AUTOINDEX $FLAGS IMAGE $index_images" >> autoindex.frames
endif
if("$fixcell" == "yes") then
    echo "AUTOINDEX $FLAGS FIXCELL UNFIXDIST" >> autoindex.frames
endif

rm -f ${tempfile}.phi_list >& /dev/null

if((($#CELL != 6)||("$SG" == "unknown"))&&(! $?background_DPS)) then
    # must need to pick these ourselves
    echo "CELL 10 10 10 10 10 10" >> $tempfile
    echo "SYMM P1"                >> $tempfile
    cat autoindex.frames          >> $tempfile
    mv $tempfile autoindex.frames
endif

# fix up long lines
cat autoindex.frames |\
nawk '{for(i=1;i<=NF;++i){l+=length($i)+1; if(l>79){l=0;print"-"} printf "%s ", $i}; print ""}' |\
cat >! $tempfile
mv $tempfile autoindex.frames

# write a short script for doing this
cat << EOF-autoindex >! autoindex.com
#! /bin/csh -fe
#
#   Wedger Elves example background autoindexing script
#
${MOSFLM} HKLOUT  auto.mtz   \
         SPOTOD  auto.spotod \
         SUMMARY ${logfile}autoindex.xlog    \
         COORDS  auto.coords << eof-ipmosflm
#
GENFILE auto.gen
#
EOF-autoindex
cat autoindex.inp     >> autoindex.com
if("$mosaic" == "estimate") echo "MOSAIC $mosaic" >> autoindex.com
#echo "RESOLUTION 3.0" >> autoindex.com
cat autoindex.frames  >> autoindex.com
cat << EOF-autoindex  >> autoindex.com
#
go
#
eof-ipmosflm

EOF-autoindex
chmod a+x autoindex.com



# try to run LABELIT
set index_files = ""
foreach num ( $best_two_index_images )
    set file = `echo "$template $num" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
    set index_files = ( $index_files "${framedir}/$file" )
    if($#index_files == 2) break
end
labelit.screen $index_files |& tee ${logfile}labelit.log | nawk '/^:)/{printf "."}'
set labelit_solution = `nawk '/^:)/{print $2}' ${logfile}labelit.log | tail -1`
if("$labelit_solution" != "") then
    set labelit_mat  = `echo $labelit_solution | nawk '{printf "index%02d.mat",$1}'`
    if(-e "$labelit_mat") then
	echo "ran LABELIT on $index_files"
	cp $labelit_mat auto.mat
	set inmatrix = auto.mat
	set CELL = `nawk 'NF == 6' auto.mat |& nawk '{for(i=1;i<=NF;++i) if($i+0 > 10) printf $i+0 " "}'`
	set beam_center = `nawk '/^:)/{print $4,$5}' ${logfile}labelit.log | tail -1`
	set sg = `nawk '/^:)/{print $3}' ${logfile}labelit.log | tail -1`
	if ("$SG_choice" == "auto" || "$SG" == "unknown") then
	    set SG = $sg
	endif
	echo " done! "
	unset autoindexing
	goto ProcessInput
    endif
else
    # forget we ever tried this?
    rm -f ${logfile}labelit.log
endif



if(-e ${logfile}autoindex.log) mv ${logfile}autoindex.log ${logfile}autoindex.log.old >& /dev/null
# run it (do a timeout?)
./autoindex.com | tee ${logfile}autoindex.log | nawk '/Finding spots/{++frames; printf "."} frames>100{exit}'
if($status) rm -f auto.mat >& /dev/null

if($?DPS_INDEX) echo " peak-picking done."

# now check and see if dps_index is available
DPS_index:
if($?DPS_INDEX) then
    # select most-recent spot file
    set spotfile  = `ls -1rt *.spt | tail -1`
    
    # determine I/sig cutoff to get target number of spots
    cat $spotfile |\
    nawk 'NF>5 && $1!="-99.00" && $1!="-999.00"{print $5/$6}' |\
    sort -nr | head -750 |\
    tail -1 >! ${tempfile}cutoff
    set cutoff = `cat ${tempfile}cutoff`
    rm -f ${tempfile}cutoff
    
    if($#CELL == 6) then
	# target_cell for dps_index
	#echo "CELL $CELL" >! ${tempfile}.cell
	set max_cell = `echo $CELL | nawk '{print $1;print $2;print $3}' | sort -nr | nawk '{printf "%d", $1*1.2; exit}'`
    else
	set max_cell = ""
    endif    
    
    echo -n "running dps_index.com "
    rm -f dps.mat >& /dev/null
    ./dps_index.com $spotfile ${wavelength}A ${distance}mm ${tempfile}.cell ${cutoff}sig $SG $max_cell no $wrongSGs | tee -a ${logfile}autoindex.log | nawk '/Generating direct/{printf "."}'
    if((! $status)&&(-e dps.mat)) then
	echo " done."
	cp dps.mat auto.mat
	
	# don't let the error detector below see this
	grep -v ERROR ${logfile}autoindex.log >!  ${tempfile}
	mv ${tempfile} ${logfile}autoindex.log
    else
	echo " failed."
	rm -f auto.mat >& /dev/null
	grep -i error ${logfile}autoindex.log
	echo "see ${logfile}autoindex.log"
    endif
    rm -f ${tempfile}.cell >& /dev/null
endif

###########################################################################
# organize cell and SG data (from background)

# convert the dps_index log (if its there)
cat ${logfile}autoindex.log  |\
nawk '/^Lattice/{\
	solution=$2; crys_sys=$4; score=$NF*1; \
	getline;getline;getline;getline; cell=substr($0,10);\
	print solution, crys_sys, score, cell, "DPS";}' |\
cat >! ${tempfile}.bravlist
# format: solution crys_sys score cell

# also convert mosflm DPS log
cat ${logfile}autoindex.log  |\
nawk '$3 ~ /^[amothc][PCIFR]$/{\
        crys_sys = $3; solution=$1; score=$2/100;\
        sys = substr(crys_sys,1,1); lattice = substr(crys_sys,2); \
        cell = $4 " " $5 " " $6 " " $7 " " $8 " " $9; \
        print solution, crys_sys, score, cell, "DPS";}' |\
cat >> ${tempfile}.bravlist
# format: solution crys_sys score cell


# now also convert the REFIX indexing log
cat ${logfile}autoindex.log  |\
nawk '$2 ~ /^[amothc][PCIFR]$/{\
	crys_sys = $2; solution=$1; score=$3/100;\
	sys = substr(crys_sys,1,1); lattice = substr(crys_sys,2); \
	cell = $4 " " $5 " " $6 " " $7 " " $8 " " $9; \
	if($4+0>0) print solution, crys_sys, score, cell, "REFIX";}' |\
cat >> ${tempfile}.bravlist
# format: solution crys_sys score cell

# expand this information, using the space group library
cat ${tempfile}.bravlist |\
nawk '! seen[$1]{print; seen[$1]=1}' |\
nawk -v library=$CLIBD/symop.lib '{\
	solution=$1; crys_sys=$2; score=$3; source=$NF;\
	sys = substr($2,1,1); lattice = substr($2,2); \
	cell = $4 " " $5 " " $6 " " $7 " " $8 " " $9; \
	if(sys=="a") sys = "TRICL"; \
	if(sys=="m") sys = "MONOC"; \
	if(sys=="o") sys = "ORTHO"; \
	if(sys=="t") sys = "TETRA"; \
	if(sys=="h") sys = "TRIGO"; \
	if(sys=="c") sys = "CUBIC"; \
	while(getline < library){ \
	    if($5 ~ /^PG/ && ! /m/ && ! /bar/ && $1 < 500){\
		SYS=substr($6,1,5)\
		LAT=substr($4,1,1)\
		if((LAT==lattice || (LAT~/[HR]/ && lattice~/[HR]/)) && (SYS==sys || (SYS=="HEXAG" && sys=="TRIGO"))){\
		    print $1, substr($5,3), $4, crys_sys, $6, solution, score, cell, source;\
		}\
	    }\
	}; close(library);}' |\
sort +0nr -1 +6n -7  |\
nawk '! seen[$3]{print; seen[$3]=1}' |\
nawk '{a=$8; b=$9; c=$10; A=$11; B=$12; G=$13;latt=$5}\
    $5 == "MONOCLINIC" { A=90; ; G=90}\
    $5 == "ORTHORHOMBIC" {A=90; B=90; G=90}\
    $5 == "TETRAGONAL" || $5 == "TRIGONAL" || $5 == "HEXAGONAL" {\
	a=b=(a+b)/2; A=90; B=90; G=120;}\
    $5 == "TETRAGONAL" {G=90}\
    $5 == "CUBIC" {a=b=c=(a+b+c)/3; A=90; B=90; G=90}\
    {print $0, a, b, c, A, B, G}' |\
cat >! ${tempfile}.SG.full
# format: SG_num PG SG crys_sys lattice solution penalty cell source newcell
rm -f ${tempfile}.bravlist

# SG.list now contains a list of all space groups 
# sorted by symmetry and indexing score

# now clear unwanted SGs from the list of possibilities
echo " $wrongSGs LIST " |\
nawk 'BEGIN{RS=" "} NF==1' |\
cat - ${tempfile}.SG.full |\
nawk 'NF==1{bad[$1]=1} \
           list && ! bad[$3] && ! bad[$4] && ! bad[$5] {print}\
         /LIST/{list=1}' |\
cat >! ${tempfile}.SG.filtered
# format: SG_num PG SG crys_sys lattice solution penalty cell source newcell

# pick a default solution
set solution = `nawk -v cut=$autoindexing_cutoff '$7<cut{print $6; exit}' ${tempfile}.SG.filtered`
if("$solution" == "44") then
    # reach a little further?
    set solution = `nawk -v cut=1 '$7<cut{print $6; exit}' ${tempfile}.SG.filtered`
endif
# Elves pick for the space group:
set bestSG = `nawk -v solution=$solution '$6==solution{print $3}' ${tempfile}.SG.full | tail -1`

if("$SG" != "unknown") then
    # space group is known
    set solution = `nawk -v SG=$SG '$7<1 && $3==SG{print $6; exit}' ${tempfile}.SG.full`
    set bestSG = "$SG"
endif

if(("$bestSG" == "")||(! -e auto.mat)) then
    # there are no solutions...
    set bestSG = "none of them"
    rm -f auto.mat >& /dev/null
    echo " failed."
    grep -i error ${logfile}autoindex.log
    # now what?
endif

onintr
Ask_about_SG:
#if(("$SG" == "unknown")||($#CELL != 6)) then
if("$SG" == "unknown") then
    # user did not indicate a space group earlier

    # present options to user
    echo ""
    echo ""
    echo "example      distortion"
    echo "space group  of cell  unit cell"
    nawk '$7<3' ${tempfile}.SG.filtered |\
    sort +0nr -1 +5n -6 |\
    nawk '{line[$4]=$0} END{for(sys in line) print line[sys]}' |\
    sort -nr |\
    nawk '{printf "%-11s  %5.3f  %8.2f %8.2f %8.2f %5.1f %5.1f %5.1f\n%20s%8.2f %8.2f %8.2f %5.1f %5.1f %5.1f\n",\
      $3, $7, $8, $9, $10, $11, $12, $13, "", $15, $16, $17, $18, $19, $20}'

    set temp = "$bestSG"
    echo "What is your space group? [$temp]"
    echo -n "$PROMPT"
    if(! $?AUTO) then
	echo -n "$BELL"
	set in = ( $< )
	if("$in" == "") then
	    # interactive user, but they just hit "Enter"
	    set SG_choice = auto
	else
	    set temp = ( $in )
	    # user just typed something in
	    set SG_choice = user
	endif
    else
	echo "$temp"
	# auto mode, SG choice is automatic
	set SG_choice = auto
    endif
    if("$temp" == "none of them") then
	# user didn't like any of the choices
	set SG = "unknown"
	set temp = ""
    endif
    if("$temp" =~ [PpCcIiFfRrHh][1-6]*) then
	set SG = `nawk -v SG=$temp '$4==toupper(SG){print $4;exit}' ${CLIBD}/symop.lib`
	set SG_number = `nawk -v SG=$temp '$4==toupper(SG){print $1;exit}' ${CLIBD}/symop.lib`
    else
	if(($#temp > 1)&&(! $?AUTO)) then
	    # go to the open interpreter
	    set input = ( $temp )
	    rm -f ${tempfile}.SG.full ${tempfile}.SG.filtered >& /dev/null
	    goto Questionaire
	endif
    endif
    if("$SG" != "unknown") then
	# dont change cell (can affect indexing search)
	#set CELL = `nawk -v SG=$SG '$3==SG{print $15, $16, $17, $18, $19, $20}' ${tempfile}.SG.full`
	# now go back and use this cell and SG
	echo "indexing again, with $SG"
	#echo " and cell: $CELL"
	echo "SYMM $SG_number"   >> autoindex.inp
	if("$CELL" != "unknown") echo "CELL $CELL" >> autoindex.inp
	if($?DPS_INDEX) goto DPS_index
	goto Index_again
    endif
    # no space group was given
    if(("$SG" == "unknown")&&("$temp" != "")) then
	# no space group was given
	set SG = "unknown"
	echo 'Sorry, "'$temp'" is not in the space group library.'
	goto Ask_about_SG
    endif
    # user said "none of them", so we go on to failure mode below.
endif
rm -f ${tempfile}.SG.full ${tempfile}.SG.filtered >& /dev/null

# check to make sure indexing succeeded
if(-e auto.mat) then
    # make sure this looks like a real matrix
    set cell = `nawk 'NF == 6' auto.mat |& nawk '{for(i=1;i<=NF;++i) if($i+0 > 10) printf $i+0 " "}'`

    # and make sure mosflm was reasonably happy
    grep ERROR ${logfile}autoindex.log
    if((! $status)||($#cell != 6)) then
	# probably bad.
	mv auto.mat bad.mat >& /dev/null
    else
	set CELL = ( $cell )
    endif
endif

if(! -e auto.mat) then
    echo "$BELL   autoindexing failed. "
#    nawk '/ERROR/{print; getline; print; getline; print; getline; print}' ${logfile}autoindex.log
    
    # don't give up, try more images
    if(($#index_images < 20)&&($#index_images < $number_of_frames)) then
	@ autoindexing_frames = ($autoindexing_frames + 2)
	
	# one of these might be better
	if("$fixcell" == "yes") then
	    set fixcell = "no"
	    echo "trying again with free cell"
	else
	    set fixcell = "yes"
	    echo "trying again with cell fixed at $CELL"
	endif
	goto Index_again
    else
	# this ain't hapening
	onintr
	
	# curse these spots
	rm -f *.spt >& /dev/null
	rm -f autoindex.frames >& /dev/null

	# ask about denzo if old-style indexing isn't working
    	if(("$MosflmVersion" !~ [678]*)&&((-e /usr/local/lib/cr_info)||(-e ~/cr_info)||(-e ./cr_info))) then
	    echo "NOTICE:"
	    echo "MOSFLM Version $MosflmVersion does not index nearly as well as version 6.x, or above."
	    echo ""
    
	    set temp = "Yes"
	    echo "Do you want us to try using denzo (you need a $Site licence)? [$temp]"
	    echo -n "$PROMPT"
	    if($?AUTO) then
		echo $temp
	    else
		echo -n "$BELL"
		set in = ( $< )
		if("$in" != "") set temp = ( $in )
	    endif
	    if("$temp" =~ [Yy]*) goto denzo
	    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
		# strange answer, send to interpreter
		set input = "$temp"
		goto Questionaire
	    endif
	endif

	goto Manual_Index
    
    endif
endif

# if auto.mat exists, it is good.

if(! $?DPS_INDEX) echo " done! "
onintr
unset autoindexing
if("$strategize" == "done") set strategize = yes
unset Convergeing
set NEW
echo ""

# read an estimated mosaicity
if("$mosaic" !~ *[0-9]*) then
    set temp = `nawk '/mosaicity has been estimated/ && $8+0>0.1 && $8+0<5{print $8}' ${logfile}autoindex.log | head -1`
    if("$temp" != "") then
	set mosaic = "$temp"
	echo "mosaicity estimated at: $mosaic"
    endif
endif


# clean up
rm -f autoindex.frames >& /dev/null
rm -f auto.mtz >& /dev/null
rm -f auto.spotod >& /dev/null
rm -f auto.coords >& /dev/null
rm -f auto.mtz >& /dev/null
#rm -f *.spt >& /dev/null

set inmatrix = "auto.mat"

set integrate = "no"
set postref = "yes"
# probably should refine mosflm cell
#set fixcell = "yes"
set fixyscale = "yes"

# alert user that we are ready
if(! $?AUTO) echo -n "$BELL"

goto ProcessInput
exit




Manual_Index:
onintr
###########################################################################

 #####   #####    ####              #    #    #  #####   ######  #    #
 #    #  #    #  #                  #    ##   #  #    #  #        #  #
 #    #  #    #   ####              #    # #  #  #    #  #####     ##
 #    #  #####        #             #    #  # #  #    #  #         ##
 #    #  #       #    #             #    #   ##  #    #  #        #  #
 #####   #        ####              #    #    #  #####   ######  #    #

###########################################################################
#
#   Interactive MOSFLM indexing (much better in version 6! )
#
###########################################################################

if("$MosflmVersion" =~ [678]*) then
    cat << EOF
####################################################################################
WHAT TO DO NEXT:

1) Say "Yes" to the question below.

2) the big Mosflm graphics window should come up.

3) Click on "Autoindex" and follow the directions you see.

4) If nothing too scary happens Click on "Predict"

5) If you see little boxes around your spots, You WIN! (auto.mat is your new matrix)
   You might also want to take this opportunity to define your backstop shadow
   using the "KEYWORDED INPUT" button and typing something like:
   "BACKSTOP CENTER $beam_center RADIUS 3"

6) "Exit" Mosflm, and come back here.

IF SOMETHING GOES WRONG:
1) Click on "Read Image" to read in another image far away (in PHI) from the current one.

2) Click on "Find Spots".  The spots picked here will be added to a cumulative list.

3) repeat 1) and 2) for 2 or 3 (maybe more) images.

4) now click on "Autoindex" 
   (using spots from several images can index almost anything)

####################################################################################
EOF
else


    cat << EOF

####################################################################################
WHAT TO DO NEXT:

1) Say "Yes" to the question below.

2) the big Mosflm graphics window should come up.  (if not, read the errors and
   make sure CCP4 is set up)

3) Click on "Find Spots" (and follow the instructions you see)

4) Click on "Read Image" and type in an image far from the last one.

5) Do 3) and 4) for 4 or so images, as widely separated in PHI as possible! 

6) Click on "Autoindex"  (make sure you FIX either the cell or the distance)

7) Cross your fingers.

8) If nothing too scary happens Click on "Predict"

9) If you see little boxes around your spots, You WIN! (auto.mat is your new matrix)

10) Exit Mosflm, and come back here.

IF SOMETHING GOES WRONG:
1) download a more recent version of ipmosflm from:
   netscape ftp://ccp4a.dl.ac.uk/pub/ccp4/
   the new DPS indexing is vastly superior to the one in this version.

####################################################################################
EOF

endif

set temp = "Yes"
if($?AUTO) set temp = "No"
echo "launch mosflm and do some autoindexing now? [$temp]"
echo -n "$PROMPT"
if(! $?AUTO) then
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
else
    echo "$temp"
endif
if("$temp" =~ [Yy]*) goto LAUNCH
if(("$temp" !~ [Nn]*)||($#temp > 1)) then
    # strange answer, send to interpreter
    set input = "$temp"
    goto Questionaire
endif

# see if denzo might run
if((-e /usr/local/lib/cr_info)||(-e ~/cr_info)||(-e ./cr_info)) then
    set temp = "Yes"
    if($?AUTO) set temp = "No"
    echo "Try using denzo? [$temp]"
    echo -n "$PROMPT"
    if(! $?AUTO) then
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    else
	echo "$temp"
    endif
    if("$temp" =~ [Yy]*) goto denzo
    if(("$temp" !~ [Nn]*)||($#temp > 1)) then
	# strange answer, send to interpreter
	set input = "$temp"
	goto Questionaire
    endif
endif

# Last chance
set temp = "quit"
echo "What do you want to do? [$temp]"
echo -n "$PROMPT"
if($?AUTO) then
    echo $temp
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
if("$temp" !~ [Qq]*) then
    set input = "$temp"
    goto Questionaire
endif

Noautoindex:
# you never know...
onintr
# user doesn't seem to want to do anything
cat << EOF
####################################################################################
####################################################################################
####################################################################################

You can still use the file autoindex.inp as a guide for setting up autoindexing.

####################################################################################

1) start Mosflm by typing: 
$MOSFLM   

2) enter your crystal/beam/camera paramters by typing:
MOSFLM> @autoindex.inp

3) Enter the name of an image you want to start with
MOSFLM> image $FirstImage

4) and then type:
MOSFLM> go

   the big Mosflm graphics window should come up.  (if not read the errors and
   make sure CCP4 is set up)

5) if you have Mosflm 6.xx, skip to step 10) (below).

6) Click on "Find Spots" (and follow on-screen instructions)

7) Click on "Read Image" and type in an image far from the last one.

8) Do 6) and 7) for 4 or so images, as widely separated in PHI as possible! 

9) Click on "Autoindex" (make sure you FIX either the cell or the distance)

10) Click on "Predict"

11) If you see little boxes around your spots, You WIN!

12) Start postrefining or integrating, (or just exit and run $0 again)


Good luck.
EOF
goto Cleanup


LAUNCH:
if(! $?DISPLAY) then
    # woops! this isn't going to work!
    if($?REMOTEHOST) setenv DISPLAY ${REMOTEHOST}:0
    if(! $?DISPLAY)  setenv DISPLAY :0
endif

set phiend = `echo $phi0 $osc | nawk '{print $1 + $2}'`
set first_frame = `basename $FirstImage`
if("$TEMPLATE" != "") set first_frame = "$first"

# sometimes it is better to let MOSFLM read the header
set philist = ""
if($?BAD_HEADER) set phillist = "PHI $phi0 to $phiend"

# write the interactive autoindexing script
cat << EOF-autoindex >! autoindex.com
#! /bin/csh -fe
#
#   Wedger Elves example interactive indexing script
#
${MOSFLM} HKLOUT  auto.mtz   \
         SPOTOD  auto.spotod \
         SUMMARY ${logfile}autoindex.xlog    \
         COORDS  auto.coords << eof-ipmosflm 
#
GENFILE auto.gen
#
EOF-autoindex
cat autoindex.inp     >> autoindex.com
cat << EOF-autoindex  >> autoindex.com
RESOLUTION 3
SYMM 0
#
#IMAGE $first_frame PHI $phi0 to $phiend
IMAGE $first_frame $philist
#
go
#
eof-ipmosflm

EOF-autoindex
chmod a+x autoindex.com

# run it (output to screen)
./autoindex.com
if(($status)||(! -e auto.mat)) then
    echo ""
    echo "AAAAACK!  What happened? "
    echo ""
    echo "Let's try that again, shall we? ... "
    if("$MosflmVersion" =~ [678]*) then
	echo ""
	echo "Try DPS indexing off of more than one frame this time. "
	echo ""
    endif
    
    goto Manual_Index
endif
echo ""
echo "There, now wasn't that fun? :)"
echo ""

set sg = "$SG"
# if ".sav" file was selected, it should be newer than the matrix
set savfile = `ls -1rt *.sav *.mat |& tail -1`
if("$savfile" !~ *.sav) set savfile = ""

if(("$sg" == "unknown")&&(-e "$savfile")) then
    # get the chosen space group from the savfile
    set sg = `nawk '/^SYMM/{print $2}' $savfile`
    if("$sg" != "") then
	# get SG name from CCP4 library
	set sg = `nawk -v num=$sg '$1 == num {print $4;exit}' $CLIBD/symop.lib | head -1`
    endif
    if("$sg" == "") set sg = "$SG"
endif

if("$sg" == "unknown") then
    # grab a reasonable space group from the logfile
    set sg = `nawk 'NF==10 && $1+0>0 && $2 < 25' mosflm.lp |& head -1 |& nawk '{print $NF}' |& nawk 'BEGIN{FS=","} {print $NF}'`
endif

set temp = "$sg"
echo "What space group did you pick? [$temp]"
echo -n "$PROMPT"
echo -n "$BELL"
set in = ( $< )
if("$in" != "") set temp = ( $in )
if("$temp" =~ [PpCcIiFfRrHh][1-6]*) then
    set SG = "$temp[1]"
    set SG_choice = user
endif

unset autoindexing
set NEW
if("$strategize" == "done") set strategize = yes

mv mosflm.lp ${logfile}autoindex.log >& /dev/null
mv *spot temp     >& /dev/null

# what to do with the ".sav" file.
# too much or too little information?
if(-e "$savfile") then
    egrep -v "$PASSTHRU_CARDS" $savfile >! ${tempfile}sav
    grep "BACK" $savfile >> ${tempfile}sav
    # OR
    egrep -v "DISTO|RAST|ADCOFF|MATRIX|RESO|GENF|PROFILE|SEPARATION" $savfile >! ${tempfile}sav
    
    mv $savfile ${savfile}.old
    mv ${tempfile}sav $savfile
endif

set inmatrix = auto.mat
set oldscripts = "$savfile"
set lastlog = ${logfile}autoindex.log

set sources  = "$lastlog $oldscripts $inmatrix"
goto GetParamsFromSources

set inmatrix = auto.mat
set lastlog = ${logfile}autoindex.log
goto FindMATRIX

exit




denzo:
################################################################################################

 #####   ######  #    #  ######   ####
 #    #  #       ##   #      #   #    #
 #    #  #####   # #  #     #    #    #
 #    #  #       #  # #    #     #    #
 #    #  #       #   ##   #      #    #
 #####   ######  #    #  ######   ####

################################################################################################
#
#   Sometimes, you do need an expensive program
#
################################################################################################
set denzo = denzo
set xfile = auto.x

# first of all, make sure there is a cr_info file in the right place
if((! -e /usr/local/lib/cr_info)&&(! -e ~/cr_info)&&(! -e ./cr_info)) then
    echo "no cr_info files found."
    echo "  Denzo will not run without a cr_info file, appropriate "
    echo "  for your machine and detector, in: "
    echo "     /usr/local/lib/"
    echo "     ~/cr_info"
    echo " or  ./cr_info"
    if($?AUTO) goto Cleanup
    goto Index_again
endif

# get most recent spot pick.
set spotfile = `ls -1rt *.spt |& grep "$frameprefix" |& tail -1`

if(! -e "$spotfile") then
    # no spots picked yet, force mosflm to pick some
    echo "picking spots in $FirstImage ... "
${MOSFLM} HKLOUT  pick.mtz	    \
         SPOTOD  pick.spotod   \
         SUMMARY pick.xlog    \
         COORDS  pick.coords << eof-ipmosflm >&! ${logfile}pick.log
#
GENFILE pick.gen
#
@autoindex.inp
RESOLUTION 3
#
# make up a cell so mosflm will run
CELL KEEP 10 10 10 90 90 90
SYMM P1

AUTOINDEX IMAGE $first PHI 0 1 FIXCELL
# this will fail miserably,  but it will pick spots
go
#
eof-ipmosflm

    set spotfile = `ls -1rt *.spt |& grep "$frameprefix" |& tail -1`
    if(! -e "$spotfile") then
	echo "spot picking failed.  Dagnabbit! "
	echo "look at ${logfile}pick.log to see why. "
	goto Cleanup
    endif 
else
    echo -n "using spots in $spotfile ... "
    cat $spotfile | wc -l
endif

# clean up after spot picking
rm -f pick.* >& /dev/null
rm -f auto.mat >& /dev/null
rm -f ${logfile}pick.log >& /dev/null

# convert the mosflm spots (mm) to denzo format (pixels)
################################################################################################
cat $spotfile |\
nawk '\
NR==1{\
    pixelwidth = $3; ratio = $4;\
    printf "      7777%7.1f    0.0          1          1\n", $1;\
}\
NR==4,$1=="-99.00"{\
    if($1 > 0) printf "%10d%7.1f%7.1f          1          1\n", $NF, $1/pixelwidth, $2/(pixelwidth/ratio);\
}' >! ${tempfile}
nawk '$1 == "7777"' ${tempfile} >! peaks.file
nawk '$1 != "7777" && NF==5' ${tempfile} | sort -n +1 >> peaks.file
rm -f ${tempfile}

if("$Site" =~ *mar*) then
    # Denzo has a different origin for MAR
    cat peaks.file |\
    nawk 'NR == 1{edge = $2} \
     edge != 0{printf "%10d%7.1f%7.1f          1          1\n", $1, edge-$3, $2}' |\
    cat >! ${tempfile}
    mv ${tempfile} peaks.file
endif
    
DENZOagain:
# make denzo's autoindexing file
################################################################################################
echo "creating auto.dat for denzo"

if("$Site" =~ *ADSC*) then
    set denzostuff = "$beam_center "
    cat << EOF-adsc >! auto.dat
format ccd adsc unsupported-q4

[values good for ADSC Q4]
error density 0.12
error positional 0.04
error systematic 5.0 partiality 0.1 
film rotation 90.0

crossfire y   .004 x  -.004 xy  -.019
cassette rotx    $two_theta roty    -.07 rotz     .00
EOF-adsc
endif

if("$Site" == "RAXIS II") then
    set denzostuff = "$beam_center "
    echo "format raxis" >! auto.dat
endif

if("$Site" == "RAXIS IV") then
    set denzostuff = "$beam_center "
    echo "format raxis4 100" >! auto.dat
endif

if("$Site" =~ *mar*) then

    # make proper format card for denzo
    head -30 $FirstImage |\
    nawk '/^PROGRAM/{type = $2} \
     /^FORMAT/{w=$2; if($0 ~ /PCK/) comp = "marpck"} \
     /^PIXEL/{pixel = $3} \
     END{print "format", type, w*pixel/1000 "mm", pixel, comp}' |\
     cat >! auto.dat

    # need to (temporarily) change the beam center too
    set denzostuff = `echo "$beam_center $Site" | nawk '{print $NF-$2, $1}'`
endif

# beam center defined above
set temp = `echo $POLARISATION | nawk '/MONO/{print "graphite"} ! /MONO/{print $NF+0}'`
set denzostuff = "$denzostuff $temp"
set temp = `nawk -v wl=$wavelength 'BEGIN{print 3147.7 * ( wl )^(-3.014)}'`
set denzostuff = "$denzostuff $temp"
set temp = `echo $distance | nawk -v angle=$two_theta '{print $1/cos(angle*3.1415/180)}'`
set denzostuff = `echo $denzostuff $temp`

set print_sg    = ""
if("$SG" != "unknown") set print_sg    = "space group $SG"

cat << EOF >> auto.dat

box print 2 2
spot radius 0.3 
background radius 0.3
mosaicity 0.5
overlap spot

wavelength $wavelength
monochromator $denzostuff[3]
air absorption length $denzostuff[4]

overload value $OVERLOAD
distance $denzostuff[5]
profile fitting radius 20.0

${print_sg}
resolution limits 25. $hires
x beam   $denzostuff[1]  y beam   $denzostuff[2]
cassette rotx `echo $two_theta | nawk '{print -$1}'`

TITLE 'autoindex $FirstImage'
raw data file '$FirstImage'
oscillation start $phi0 range $osc
film york output file 'auto.x'
sector 1  

longest vector 300
peak search file 'peaks.file'
write predictions
fix all
go go
fit cell
fit x beam y beam
fit crystal rotx roty rotz
fit distance

go go go go go go go go go go
go go go go go go go go go go
fit all
go go go go go go go go go go
go go go go go go go go go go
go go go go go go go go go go
go go go go go go go go go go
go go go go go go go go go go
go go go go go go go go go go
go go go go go go go go go go
go go go go go go go go go go
calculate go
exit

EOF
unset print_sg

FindDENZO:
if(! $?AUTO) onintr NoDenzoSolutions
# hunt for denzo that will give an acceptable autoindexing solution
################################################################################################

# don't risk reading an inappropriate auto.x
if(-e "$xfile") then
    # probably iterating here, back it up
    mv $xfile ${xfile}.old
endif

set bad_denzo = 0

# look for aliases
if(! -e "$xfile") then

    if(! -e "$denzo") then
	foreach filename ( $denzo denzo )
	    if(! -e "$denzo") then
		set temp = `which $filename |& grep -v ' not in ' |& tail -1`

		foreach word ( $temp )
		    if((-e "$word")&&(! -e "$denzo")) then
			set denzo = `ls -ln $word |& nawk '$1 ~ /x/ && $5 > 500000 && ! /^d/ {print $NF}'`
		    endif
		end
	    endif
	end
    endif

    if(-e "$denzo") then
	# see if this denzo file will autoindex for us
	echo -n "trying $denzo ... "
	mv ${logfile}denzo.log ${logfile}denzo.log.old >& /dev/null
	$denzo < auto.dat >&! ${logfile}denzo.log
	# verify that preds were tolerably close
	set temp = `nawk '/ chi/ && / x / && / y /{printf "%d\n", substr($0,index($0," x ")+3)+ substr($0,index($0," y ")+3)}' ${logfile}denzo.log | tail -1`
	if((-e "$xfile")&&("$temp" != "")) then
	    if($temp < 6) then
		echo "indexed. "
	    else
		echo "bad solution. chi^2 ~ $temp"
		mv $xfile not_so_good.$temp.$xfile
		@ bad_denzo = ($bad_denzo + 1)
	    endif
	else
	    if(-e "$xfile") rm -f $xfile  >& /dev/null
	    echo "bust."
	endif		
    endif
else
    echo "found ${xfile}!  Will use it to get orientation in denzo.mat ..."
endif

# look in directories
if(! -e "$xfile") then
    echo "Looking for denzo ... "
    
    # look down a list of standard places for the executable
    foreach place ( ./ ../ ../../ ../../../ /programs/HKL/newest/ /programs/HKL/1.9.1/ /usr/local/newest/ /programs/HKL/ /programs/denzo/ /programs/ /usr/local/bin/ /usr/local/ )

	# stop looking once autoindexing has been done
	if((! -e "$xfile")&&(-e "$place")) then
    
	    # look for executable files named "denzo" in $place
    	    foreach file ( `ls -lnL ${place} |& sort -4n |& nawk ' /^-/ && $1 ~ /x/ && ($NF ~ "denzo"){print $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'` )


    		if((! -e "$xfile")&&(-e "${place}/${file}")) then
		    # see if this denzo file will autoindex for us
		    set denzo = `echo ${place}/${file} |& nawk 'BEGIN{RS="/";ORS="/"} (NF>0 || NR==1)' |& head -1`

		    echo -n "trying $denzo ... "
		    mv ${logfile}denzo.log ${logfile}denzo.log.old >& /dev/null
		    $denzo < auto.dat >&! ${logfile}denzo.log
		    # verify that preds were tolerably close
		    set temp = `nawk '/ chi/ && / x / && / y /{printf "%d\n", substr($0,index($0," x ")+3)+ substr($0,index($0," y ")+3)}' ${logfile}denzo.log | tail -1`
		    if((-e "$xfile")&&("$temp" != "")) then
			if($temp < 6) then
			    echo "indexed. "
			else
			    echo "bad solution. chi^2 ~ $temp"
			    mv $xfile not_so_good.$temp.$xfile
			    @ bad_denzo = ($bad_denzo + 1)
			endif
		    else
			if(-e "$xfile") rm -f $xfile  >& /dev/null
			echo "bust."
		    endif		
		endif

	    end
	endif
    end
endif

# get agressive, use "find"
if(! -e "$xfile") then
    echo "looking harder ... "

    foreach place ( ../../../ /programs/ /usr/local/bin/ /usr/local/  )
	# look for files of right type
	if((! -e "$xfile")&&(-e "$place")) then
	    # look for links first
	    set temp = `find $place -name denzo -type l -perm -1 -print |& nawk '! /^find:/' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'`
	    foreach file ( `ls -lnL $temp |& sort -4n |& nawk '! /^d/ && $5 > 100000 && /denzo/ {print $NF}' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'` )
		if((! -e "$xfile")&&(-e "$file")) then
		    # see if this denzo file will autoindex for us
		    set denzo = "$file"

		    echo -n "trying $denzo ... "
		    mv ${logfile}denzo.log ${logfile}denzo.log.old >& /dev/null
		    $denzo < auto.dat >&! ${logfile}denzo.log
		    # verify that preds were tolerably close
		    set temp = `nawk '/ chi/ && / x / && / y /{printf "%d\n", substr($0,index($0," x ")+3)+ substr($0,index($0," y ")+3)}' ${logfile}denzo.log | tail -1`
		    if((-e "$xfile")&&("$temp" != "")) then
			if($temp < 6) then
			    echo "indexed. "
			else
			    echo "bad solution. chi^2 ~ $temp"
			    mv $xfile not_so_good.$temp.$xfile
			    @ bad_denzo = ($bad_denzo + 1)
			endif
		    else
			if(-e "$xfile") rm -f $xfile  >& /dev/null
			echo "bust."
		    endif		
		endif
	    end
	    # then look at actual files
	    foreach file ( `find $place -name \*denzo\* -type f -size +1000 -perm -1 -print |& nawk '! /^find:/' |& nawk -v L=$MAXLINE '{l+=length($0)} l<L{print}'` )
		if((! -e "$xfile")&&(-e "$file")) then
		    set denzo = "$file"

		    echo -n "trying $denzo ... "
		    mv ${logfile}denzo.log ${logfile}denzo.log.old >& /dev/null
		    $denzo < auto.dat >&! ${logfile}denzo.log
		    # verify that preds were tolerably close
		    set temp = `nawk '/ chi/ && / x / && / y /{printf "%d\n", substr($0,index($0," x ")+3)+ substr($0,index($0," y ")+3)}' ${logfile}denzo.log | tail -1`
		    if((-e "$xfile")&&("$temp" != "")) then
			if($temp < 6) then
			    echo "indexed. "
			else
			    echo "bad solution. chi^2 ~ $temp"
			    mv $xfile not_so_good.$temp.$xfile
			    @ bad_denzo = ($bad_denzo + 1)
			endif
		    else
			if(-e "$xfile") rm -f $xfile  >& /dev/null
			echo "bust."
		    endif		
		endif
	    end
	endif
    end
endif

NoDenzoSolutions:
onintr

if((! -e "$xfile")&&($?AUTO)) then
    if("$bad_denzo" > 0) then
	# might as well charge ahead
	set temp = `ls -1 not_so_good* | nawk 'BEGIN{RS="."} /[0-9]/' | sort -n | head -1`
	set xfile = `ls -1 not_so_good* | egrep "\.$temp\."`
	if(-e "$xfile") goto Done_With_Denzo
    else
	echo ""
	echo "We couldn't find any denzo's that would run.  You probably don't have a license here."
	if($MosflmVersion !~ [678]*) then
	    echo "Next time, try entering a CELL and Space Group, and you might be suprised at how"
	    echo "well mosflm can index too! "
	else
	    echo "Next time, try the new, interactive DPS indexing in Mosflm Version 6."
	    echo "It is just as good as denzo. "
	endif
	echo ""
	echo "Out of options. Sorry!  "
	goto Cleanup
    
    endif
endif

# whimper pitifully
while(! -e "$xfile")
    set temp = ""
    echo ""
    echo "WARNING: can't find a denzo that will autoindex."
    if($bad_denzo) then
	echo "  Although $bad_denzo gave poor solutions. $BELL "
	echo "Are you sure the beam center/etc. was right? [No]"
	echo -n "$PROMPT"
	set temp = "$<"
	if("$temp" !~ [Yy]*) goto Questionaire
    endif
    
    echo "Where is denzo [forget it]?"
    if(! $?AUTO) then
	echo -n "$PROMPT"
    	set temp = "$<"
    else
	set temp = ""
    endif
    if(("$temp" == "")||("$temp" =~ forget*)) then
	# prevent an infinite loop
	if($?AUTO) goto Noautoindex
	goto autoindex
    endif

    # something was entered
    if($#temp > 1) then
	# must mean something other than a filename
	set input = "$temp"
	goto Questionaire
    endif
    # single word given
    set denzo = "$temp"
#    set bad_denzo = 0

    echo -n "trying $denzo ... "
    mv ${logfile}denzo.log ${logfile}denzo.log.old >& /dev/null
    $denzo < auto.dat >&! ${logfile}denzo.log
    if(-e "$xfile") then
	# verify that preds were tolerably close
	set temp = `nawk '/ chi/ && / x / && / y /{printf "%d\n", substr($0,index($0," x ")+3)+ substr($0,index($0," y ")+3)}' ${logfile}denzo.log | tail -1`
	if(("$temp" != "")&&($temp < 6)) then
	    echo "thanks! "
	else
	    echo "sorry, bad solution. chi^2 ~ $temp"
	    mv $xfile not_so_good.$temp.$xfile
	    endif
    else
	echo -n "nope."
	if(! -e "$denzo") then
	    echo "  $denzo doesn't exits."
	else
	    echo "  didn't work."
	endif
    endif
end

################################################################################################
# X file has been produced!
################################################################################################

# get refined parameters from .x file (SG should be same one we put in)
set temp = `nawk '/cell/{for(i=1;i<=NF;++i){if($i ~ /[0-9]/)printf "%12.4f",$i}} END{print ""}' $xfile`
if($#temp == 6) set CELL = `echo $temp`
#set SG = `nawk '/space group/{print toupper( $NF )}' $xfile`

# get new beam center

set temp = `nawk '/beam /{for(i=2;i<NF;++i) if(($i ~ /beam/)&&($(i+1) ~ /^[1-9]/)){if($(i-1)=="x"){X=$(i+1)} if($(i-1)=="y"){Y=$(i+1)} }} END{if(X!="" && Y!="") print X, Y}' $xfile`
if($#temp == 2) then 
    # must be two numbers
    set beam_center = `echo $temp`
endif

# get XTF distance
set temp = `nawk '$1 ~ /^DISTA/{print $2}' $xfile`
if($#temp == 1) then
    if("$temp" =~ [1-9]*) set distance = $temp
endif

# logfile should contain this text if autoindexing succeeded

# get distortion indicies from denzo log
nawk '/^ Lattice   /,/triclinic/' ${logfile}denzo.log |\
nawk '\
/primitive cubic/       {L="P213    "} \
/I centred cubic/       {L="I213    "} \
/F centred cubic/       {L="F23     "} \
/primitive rhombohedral/{L="R32     "} \
/primitive hexagonal/   {L="P31     "} \
/primitive tetragonal/  {L="P41     "} \
/I centred tetragonal/  {L="I41     "} \
/primitive orthorhombic/{L="P212121 "} \
/C centred orthorhombic/{L="C2221   "} \
/I centred orthorhombic/{L="I212121 "} \
/F centred orthorhombic/{L="F222    "} \
/primitive monoclinic/  {L="P21     "} \
/C centred monoclinic/  {L="C2      "} \
/primitive triclinic/   {L="P1      "} \
L != ""{print L substr($0,25)+0; L=""; ++i}' >! ${tempfile}.spacegroups

# pick highest symmetry space group with distortion < 1%
set sg = `nawk -v accept=1 '$2 < accept && ! done {print $1;done=1}' ${tempfile}.spacegroups`

if(("$SG" != "$sg")&&("$sg" != "")) then
    # denzo seems to disagree with our space group
    if("$SG_choice" == "auto") then
	# space group started out "unknown" so this one might be ever better
	set SG = "$sg"
    endif

    echo -n "space group ${sg} looks best to me.  "
    if("$SG" != "unknown") echo -n "$SG will be used."
    echo ""
    
    # if SG is "unknown",  thes user had no idea what SG is
    if("$SG" == "unknown") then
	# better than nuthn' 
	set SG = "$sg"
	set SG_choice = auto
    endif
        
    # go back and re-autoindex with this space group (and refined parameters)
    if("$SG_choice" == "auto") then
	# maybe alter auto.dat? 
	goto DENZOagain
    endif
endif

# if all else fails, just use P1
if(("$SG" == "unknown")||("$SG" == "")) set SG = P1

# clean up denzo files
rm -f $spotfile >& /dev/null
#rm -f peaks.file >& /dev/null
rm -f hklpredictions >& /dev/null
rm -f fort* >& /dev/null
rm -f ${tempfile}.spacegroups >& /dev/null
#mv ${tempfile}.spacegroups denzo.spacegroups


Done_With_Denzo:
# convert orientation to a mosflm matrix
################################################################################################

	    
# extract the unitary matrix
head -24 $xfile |& nawk 'NF == 6{printf "%12.8f%12.8f%12.8f\n", $4, $5, $6}' >! ${tempfile}.umat

# make sure this new matrix is unitary
cat ${tempfile}.umat |\
nawk '{++i; for(j=1;j<4;++j){mat[i,j]=$j+0}}     \
    END{det += mat[1,1]*((mat[2,2]*mat[3,3])-(mat[2,3]*mat[3,2]))  \
	det -= mat[1,2]*((mat[2,1]*mat[3,3])-(mat[2,3]*mat[3,1]))  \
	det += mat[1,3]*((mat[2,1]*mat[3,2])-(mat[2,2]*mat[3,1]))  \
	printf "%.4f", det}' >&! $tempfile
set det = `cat $tempfile`
rm -f $tempfile >& /dev/null
rm -f ${tempfile}.umat >& /dev/null

if("$det" == "1.0000") then
    # now go on and check this new matrix in the usual way ...

    set integrate = "no"
    set postref = "yes"
    set fixcell = "yes"
    set fixyscale = "yes"

    unset autoindexing
    set NEW
    if("$strategize" == "done") set strategize = yes

    set inmatrix = auto.x
    set oldscripts = "$xfile auto.dat"

    set sources  = "$inmatrix $oldscripts"
    goto GetParamsFromSources

else
    echo "WARNING: auto.x is not a valid matrix ... ignoring it."
    rm -f auto.mat
    if($?AUTO) goto Noautoindex
    goto autoindex
endif

exit






Strategy:
echo -n "strategizing ... "
if(! $?AUTO) then
    onintr SkipStrategy
    echo -n "(Ctrl-C to skip) "
endif
echo ""
##########################################################################

  ####    #####  #####     ##     #####  ######   ####    #   #
 #          #    #    #   #  #      #    #       #    #    # #
  ####      #    #    #  #    #     #    #####   #          #
      #     #    #####   ######     #    #       #  ###     #
 #    #     #    #   #   #    #     #    #       #    #     #
  ####      #    #    #  #    #     #    ######   ####      #

##########################################################################
# reset resolution limit to edge of detector (if possible)
set strat_res = $hires
if($?edge_res) then
    set strat_res = `echo "$edge_res $hires" | nawk '$1+0>$2+0{print $1+0} $1+0<=$2+0{print $2+0}'`
endif
if("$res_choice" != "auto") set strat_res = $hires
set phi_end = `echo "$phi0 $osc  $last $first" | nawk '{print $1+$2*($3-$4+1)}'`
set strat_range = `echo "$phi0 $phi_end" | nawk '{printf "start %d end %d", $1-10, $2+10}'`

#echo "creating strategy.com..."
set print_swing = ""
set print_cell  = ""
set print_sg    = ""
set mosflmSG = $SG
if("$SG" =~ P2*2*2*) set mosflmSG = P222
if("$SG" =~ R* || "$SG" =~ H*) set mosflmSG = $SG_number
set temp = `echo "$two_theta" | nawk '{printf "%d", $1+0}'`
if("$temp" != "0")     set print_swing = "SWUNG_OUT "
if($#CELL == 6)        set print_cell  = "CELL          $CELL"
if("$SG" != "unknown") set print_sg    = "SYMMETRY      $mosflmSG"

# get a separation, any separation, from some old log
set separation = `nawk '/have been set to/ && /mm.$/{print $(NF-1), $NF+0}' ${logfile}/* |& tail -1 | nawk 'NF==2'`
if("$separation" == "") set separation = "1 1"

set first_frame = `echo "$template $first" | nawk 'BEGIN{FS="\043"} {print $1 "%0" NF-1 "d" $NF}' | nawk '{printf $1,$2}'`
if("$TEMPLATE" != "") set first_frame = "$first"

set print_overload = "OVERLOAD CUTOFF $OVERLOAD"
set test = `echo $OVERLOAD | nawk '{print ($1+0<1000)}'`
if($test) then
    set print_overload = ""
endif
set print_gain = "GAIN $GAIN"
set test = `echo $GAIN | nawk '{print ($1+0<=0)}'`
if($test) then
    set print_gain = ""
endif

cat << EOF-stratstart >! strategy.com.start
#! /bin/csh -fe
#
#   Wedger Elves example STRATEGY session
#
${MOSFLM} HKLOUT strategy.mtz	    \
         SPOTOD  strategy.spotod   \
         SUMMARY ${logfile}strategy.xlog    \
         COORDS  strategy.coords << eof-ipmosflm
#
GENFILE strategy.gen
#
# the following keywords were not understood by the Wedger elves, but passed on
# because they resemble mosflm commands.
# ----
`echo "$PREAMBLE" | nawk 'BEGIN{RS="n"} {print}'`
# ----

# Detector parameters (range, quantum gain, etc.)
$SCANNER
$print_overload
$print_gain
$LIMITS

# Beam parameters (i.e. (delta-lambda)/lambda, H,V divervence in degrees)
WAVELENGTH    $wavelength
DISPERSION    $DISPERSION
DIVERGENCE    $DIVERGENCE
POLARISATION  $POLARISATION

# Alignment parameters
DISTANCE      $distance
BEAM          ${print_swing}$beam_center
TWOTHETA      $two_theta
MATRIX        $inmatrix
#

# Crystal parameters
${print_cell}
${print_sg}
RESOLUTION    $strat_res
MOSAIC        $mosaic

# Frame filename breakdown
DIRECTORY     $framedir
IDENTIFIER    $frameprefix
EXTENSION     $ext
$TEMPLATE
#
#
# un-comment the following lines to run strategy interactively
#IMAGE $first_frame
#GO
#
EOF-stratstart
unset print_swing
unset print_cell
unset print_sg

if("$mosaic" == "estimate") then
    echo "IMAGE $first_frame" >> strategy.com.start
    echo "go" >> strategy.com.start
endif

cat << EOF-stratopts >! strategy.com.end
# current strategy
#strategy start $phi0 end $phi_end speedup 1
strategy start $phi0 end $phi_end
go
start $phi0 end $phi_end
go
stats
end

# calculate best oscillation widths
SEPARATION $separation
testgen start $phi0 end $phi_end minosc $osc overlap 3
go

# best "next" strategy (given that "current" data are already collected)
strategy start $phi0 end $phi_end PARTS 2 
run
strategy auto
go
stats
end

# best, overall strategy
strategy auto
go
stats
end

# best, overall strategy for anomalous
strategy auto anomalous
go
stats
end

# calculate best oscillation widths
SEPARATION $separation
testgen start 0 end 180 minosc 0.01 overlap 3
go

EOF-stratopts


# now create an executable com file
if(-e strategy.com) mv strategy.com strategy.com.old
cat strategy.com.start  >! strategy.com
cat strategy.com.end |\
nawk '/current strategy/,/already collected/' >> strategy.com
echo "eof-ipmosflm" >> strategy.com
chmod a+x strategy.com

# run the strategy
./strategy.com >! ${logfile}strategy.log

# print out reports of strategy run

# read an estimated mosaicity
if("$mosaic" !~ *[0-9]*) then
    set temp = `nawk '/mosaicity has been estimated/ && $8+0>0.1 && $8+0<5{print $8}' ${logfile}strategy.log | head -1`
    if("$temp" != "") then
	set mosaic = "$temp"
	echo "mosaicity estimated at: $mosaic"
    endif
endif

# sumarize current wedge for user
cat ${logfile}strategy.log |\
nawk -v res=$strat_res '/These segments contain / && /of the unique data/{complete = $4+0} \
      /ANOMALOUS DATA/ {getline; getline; getline; anom = $5+0} \
      END{printf "This wedge will be %.1f%% complete to %.1f A and contain %.1f%% of anomalous data.\n", complete, res, anom}'

cat ${logfile}strategy.log |\
nawk '/TESTGEN OPTION/,/IMPORTANT/' |\
nawk '/minimum percentage/ && /oscillation angle above/ && $9+0>1{print $9, $3}' |\
sort -n | tail -1 |\
nawk -v osc="${osc}$DEG" '{printf "WARNING! with %s oscillations you will have %s overlaps when phi = %s\n", osc,$1,$2+0}'


##########################################################################
##########################################################################
# do best "complement wedge" if completeness is not already >99%
#set temp = `nawk '/These segments contain / && /unique/{printf "%d\n", $4+0}' ${logfile}strategy.log | head -1`

#if($temp < 99 ) then

# now create an executable com file
cat strategy.com.start >! strategy.com
cat strategy.com.end |\
nawk '/already collected/,/overall strategy/' >> strategy.com
echo "eof-ipmosflm" >> strategy.com
chmod a+x strategy.com

# run the strategy
./strategy.com |& head -1000 >&! ${logfile}temp
if(! $status) then
    # completed okay
    cat ${logfile}temp |\
    nawk '/Run number  2/{getline; wedge = substr($0, 11, 15); getline; \
	  print "Adding another wedge from " wedge " will give you " $4 " completeness."}' 

    # save for posterity
    cat ${logfile}temp >> ${logfile}strategy.log
endif


##########################################################################
##########################################################################
# best, overall strategy

# now create an executable com file
cat strategy.com.start >! strategy.com
cat strategy.com.end |\
nawk '/overall strategy/,/\n/' >> strategy.com
echo "eof-ipmosflm" >> strategy.com
chmod a+x strategy.com

# run the strategy
./strategy.com >! ${logfile}temp

grep " cusp" ${logfile}temp >& /dev/null
if(! $status) then
    set temp = ""
    if("$SG" == "P1") set temp = " in P1, using only phi axis"
    echo "WARNING! impossible to collect 100% complete data${temp}! "
    set temp = `nawk '/[abc]-axis/ && /cusp/{for(i=1;i<=NF;++i)if($i ~ /axis/) print $i}' ${logfile}temp | tail -1`
    if("$temp" != "") echo "$temp is too close to phi-axis"
    set temp = `nawk '/axis/ && /cusp/ && $(NF-1)+0>1{printf "%d\n", $(NF-1)+1}' ${logfile}temp | tail -1`
    if("$temp" != "") echo "try tilting the crystal at least $temp degrees, and index again"
endif

cat ${logfile}temp |\
nawk '/Optimum rotation gives / && /unique/{complete = $4; getline; getline; \
  print "A wedge" tolower($0), "would be", complete, "complete."}' |\
head -1 | tee ${tempfile}
set best_strategy = `nawk '{print $4-5, $6+5}' ${tempfile}` 
if($#best_strategy < 2) set best_strategy = ( 0 0 )
rm -f ${tempfile}

cat ${logfile}temp |\
nawk '/Optimum rotation gives / && /anomalous/{complete = $4; getline; getline; \
  print "A wedge" tolower($0), "would contain", complete, "of anomalous pairs."}' |\
head -1 

cat ${logfile}temp |\
nawk '/TESTGEN OPTION/,/IMPORTANT/' |\
nawk '/minimum percentage/ && /oscillation angle above/ && $9+0>1{print $9, $3}' |\
sort -n | tail -1 |\
nawk -v osc="${osc}$DEG" '{printf "with %s oscillations you will have %s overlaps when phi = %s\n", osc,$1,$2+0}'

cat ${logfile}temp | \
nawk '/TESTGEN OPTION/,/IMPORTANT/' |\
nawk ' ! /[^0-9 .-]/ && NF>3{print $1, $4}' |\
nawk 'BEGIN{minosc=99999} $2<minosc{minosc=$2;minphi=$1} $2>maxosc{maxosc=$2;maxphi=$1} \
      END{maxphi2=maxphi+180; if(maxphi2>360) maxphi2=maxphi2%360\
	  minphi2=minphi+180; if(minphi2>360) minphi2=minphi2%360\
	  print "oscillation can be as much as", maxosc, "at phi =", maxphi, maxphi2;\
          print "             but no more than", minosc, "at phi =", minphi, minphi2;}'

cat ${logfile}temp >> ${logfile}strategy.log

# back up last stragegy script
if(-e strategy.com.old) mv strategy.com.old strategy.com.older
mv strategy.com strategy.com.old

##########################################################################
##########################################################################
# TESTGEN for best, overall strategy

# now create an executable com file
cat strategy.com.start >! strategy.com
cat << EOF-testgen >> strategy.com
SEPARATION $separation
testgen start $best_strategy[1] end $best_strategy[2] minosc 0.01 overlap 3
go
eof-ipmosflm
EOF-testgen
chmod a+x strategy.com

# run the strategy
./strategy.com >! ${logfile}temp

# come up with a full data-collection strategy (with oscillation widths)
echo "recommend: "
echo "  start   osc frames  wedge  size" | tee strategy.txt

cat ${logfile}temp |\
nawk '/Suggested data collection strat/,/IMPORTANT/' |\
nawk '! /[a-z]/ && NF>3{printf "%.0f %.0f %s\n", $1, $2, $4}' |\
nawk '{for(phi=$1;phi<$2;++phi){print phi, $3}}' |\
nawk 'NR==1{last=$1} $1<last{$1+=360} NF==2{print $0, "";last=$1}' |\
nawk '$2>1{$2=1} {print}' |\
nawk -v crit=1.8 'NR==1{lastosc=$2} {phi=$1;osc=$2;ratio=osc/lastosc} ratio<1{ratio=1/ratio} \
   ratio<crit{osc=lastosc} {lastosc=osc; print phi, osc, $2, ratio}' |\
nawk '$2 != lastosc{print lastphi+1; printf "%s %s ", $2, $1} {lastosc=$2;lastphi=$1}\
   END{print lastphi}' |\
nawk 'NF>2{print $1, $2, $3, sprintf("%.0f", ($3-$2+$1)/$1)}' |\
nawk 'NR==1{first=$2}\
    {printf "%7.1f %5.1f %6d  %5.1f %5.1f\n", $2, $1, $4, $4*$1, $4*$1+$2-first}' |\
cat > /dev/null


cat ${logfile}temp |\
nawk '/Suggested data collection strat/,/IMPORTANT/' |\
nawk '! /[a-z]/ && NF>3{print $4}' |\
cat >! ${tempfile}minosc
set minosc = `sort -nr ${tempfile}minosc | tail -1`
rm -f ${tempfile}minosc >& /dev/null
cat ${logfile}temp |\
nawk '/Suggested data collection strat/,/IMPORTANT/' |\
nawk -v minosc=$minosc '! /[a-z]/ && NF>3{printf "%.0f %.0f %s\n", $1, $2, minosc}' |\
nawk '{for(phi=$1;phi<$2;++phi){print phi, $3}}' |\
nawk 'NR==1{last=$1} $1<last{$1+=360} NF==2{print $0, "";last=$1}' |\
nawk '$2>1{$2=1} {print}' |\
nawk -v crit=1.8 'NR==1{lastosc=$2} {phi=$1;osc=$2;ratio=osc/lastosc} ratio<1{ratio=1/ratio} \
   ratio<crit{osc=lastosc} {lastosc=osc; print phi, osc, $2, ratio}' |\
nawk '$2 != lastosc{print lastphi+1; printf "%s %s ", $2, $1} {lastosc=$2;lastphi=$1}\
   END{print lastphi}' |\
nawk 'NF>2{print $1, $2, $3, sprintf("%.0f", ($3-$2+$1)/$1)}' |\
nawk 'NR==1{first=$2}\
    {printf "%7.1f %5.2f %6d  %5.1f %5.1f\n", $2, $1, $4, $4*$1, $4*$1+$2-first}' |\
cat | tee -a strategy.txt
echo ""

# make whole script for user's benifit
cat strategy.com.start strategy.com.end >! strategy.com
echo "eof-ipmosflm" >> strategy.com
chmod a+x strategy.com




# add some xloggraph plots to ${logfile}strategy.html
echo "<html><pre>" >! ${logfile}strategy.html

foreach strategy ( `nawk '/ ===> strategy/{++line; print line}' ${logfile}strategy.log` )

    set keyword = `nawk -v strategy=$strategy '/ ===> strategy/{++line} line==strategy{$1="";print;exit}' ${logfile}strategy.log`
    # make an xloggraph header for it
    cat << EOF >> ${logfile}strategy.html
 : $keyword :
<applet width=" 700" height=" 300" code="JLogGraph.class"
codebase="${CBIN}"><param name="table" value="
 \$TABLE : $keyword :
 \$GRAPHS:completeness vs phi:A:1, 2:
 :multiplicity vs phi:A:1, 3:
 :new observations vs phi:A:1, 4:
 :completeness/range vs phi:A:1, 5: \$\$
phi completeness(%) multiplicity new(%) completeness(%)/range \$\$
 \$\$
EOF
    cat ${logfile}strategy.log |\
    nawk -v strategy=$strategy '/ ===> strategy/{++line} line==strategy{print}' |\
    nawk '/These segments contain/{total=$8}\
       /^ Angle /{for(i=1;i<=4;++i){phi[i]= $(3*i-1) " " $(3*i+1);\
     if(! seen[phi[i]]){seen[phi[i]]=1; ++n; range[n]=phi[i]; \
          start[range[n]]=$(3*i-1); stop[range[n]]=$(3*i+1)}}}\
     /Number    /{for(i=1;i<=4;++i)  fraction[phi[i]]=$(i+1)/total*100}\
     /%age unique/{for(i=1;i<=4;++i) complete[phi[i]]=$(i+2)}\
     /Mean multip/{for(i=1;i<=4;++i)    multi[phi[i]]=$(i+2)}\
   /  D     angle/{for(i=1;i<=4;++i){phi[i]= $(3*i) " " $(3*i+2)};getline;\
      while(NF!=0){for(i=1;i<=4;++i){new[phi[i]]=new[phi[i]]+$(i+1)/total*100};getline}}\
 /COMPLETE option/{for(i=1;i<=n;++i){\
     print start[range[i]], complete[range[i]], multi[range[i]], new[range[i]], fraction[range[i]], "";\
     print  stop[range[i]], complete[range[i]], multi[range[i]], new[range[i]], fraction[range[i]], "";\
     } n=0; for(i in seen) seen[i]=0}' |\
    nawk 'NR==1{last=$1} $1<last{$1+=360} NF>3{print;last=$1}' |\
    nawk '{printf "%6s %6s %6s %6s %6s \n",$1,$2,$3,$4,$5}' |\
    cat >> ${logfile}strategy.html

    echo '$$' >> ${logfile}strategy.html
    echo '"><b>For inline graphs use a Java browser</b></applet>' >> ${logfile}strategy.html
end

# show testgen data too
foreach strategy ( `nawk '/ ===> testgen/{++line; print line}' ${logfile}strategy.log` )

    set keyword = `nawk -v strategy=$strategy '/ ===> testgen/{++line} line==strategy{$1="";print;exit}' ${logfile}strategy.log`
    
    cat ${logfile}strategy.log |\
    nawk -v strategy=$strategy '/ ===> testgen/{++line} line==strategy{print}' |\
    nawk '/Current values:/' >> ${logfile}strategy.html
    
    cat << EOF >> ${logfile}strategy.html
$keyword :
<applet width=" 700" height=" 300" code="JLogGraph.class"
codebase="${CBIN}"><param name="table" value="
 \$TABLE : $keyword :
 \$GRAPHS:maximum osc vs phi:N:1, 2:
  :overlaps vs phi:N:1, 3:
  :fulls vs phi:A:1, 4: \$\$
phi max_osc overlaps(%) fulls(%) \$\$
 \$\$
EOF
    cat ${logfile}strategy.log |\
    nawk -v strategy=$strategy '/ ===> testgen/{++line} line==strategy{print}' |\
    nawk '/Suggested data collection strat/,/IMPORTANT/{print} \
	  /minimum percentage overlaps/{print}' |\
    nawk '/minimum percentage overlaps/{printf "%.0f %.0f 1 %f OVLAP\n", $3, $3+5, $9+0}\
	! /[a-z]/ && NF>3{printf "%.0f %.0f %s %s %s\n", $1, $2, $4, $5, $6}' |\
    nawk '{for(phi=$1;phi<=$2;++phi){if(ovlap[phi]=="") ovlap[phi]=$4;\
	   if($NF != "OVLAP") print phi, $3, ovlap[phi], $5, ""}}' |\
    nawk 'NR==1{last=$1} $1<last{$1+=360} NF>3{print;last=$1}' |\
    nawk '{printf "%6s %6s %6s %6s \n",$1,$2,$3,$4}' |\
    cat >> ${logfile}strategy.html 

    echo '$$' >> ${logfile}strategy.html
    echo '"><b>For inline graphs use a Java browser</b></applet>' >> ${logfile}strategy.html
end

#unset strat_res
unset phi_end
echo "for details, see ${logfile}strategy.log and ${logfile}strategy.html"


# Clean up a bit ...
rm -f strategy.com.start >& /dev/null
rm -f strategy.com.end >& /dev/null

rm -f strategy.mtz >& /dev/null
rm -f strategy.xlog >& /dev/null
rm -f ${logfile}temp >& /dev/null
rm -f ${tempfile}max_osc >& /dev/null

echo ""

SkipStrategy:
onintr

goto ReturnFromStrategy



























exit
scale_and_merge:
###############################################################################

  ####    ####     ##    #       ######
 #       #    #   #  #   #       #
  ####   #       #    #  #       #####
      #  #       ######  #       #
 #    #  #    #  #    #  #       #
  ####    ####   #    #  ######  ######

###############################################################################
# perform a complimentary scaling step here.  So user can see Rmerge, etc.
#
###############################################################################

# figure out asu
if(! $?ASU) then
    # ASU is not set, so we need to calculate a "reasonable" one from Vm
    if(! $?Vm) set Vm = 2.4
    set ASU_per_CELL = `nawk -v SG=$SG '$4==SG{print $2;exit}' $CLIBD/symop.lib | head -1`

    # calculate cell volume
    echo $CELL |\
    nawk 'NF==6{s=3.1415926535897899419/180; A=cos(s*$4); B=cos(s*$5); G=cos(s*$6); \
     skew = 1 + 2*A*B*G - A*A - B*B - G*G ; if(skew < 0) skew = -skew;\
     printf "%.3f\n", $1*$2*$3*sqrt(skew)}' |\
    cat >! ${tempfile}volume
    set CELLvolume = `cat ${tempfile}volume`
    rm -f ${tempfile}volume >> /dev/null
    
    # now set ASU to best number of AA, given the Vm
    set temp = `echo "$CELLvolume $ASU_per_CELL " | nawk '{print $1/$2}'`
    set ASU = `echo "$temp $Vm" | nawk '{printf "%d", $1 / $2 / 120}'` 
#    set ASU = `echo "$temp $Vm" | nawk '{print $1 / $2 / 128}'` 

    if($?Chain) then
	# protein size known, how many in ASU? 

	# decide to round up or down
	@ temp = ( $ASU % $Chain )
	if($temp >= ($Chain / 2) ) then
	    set temp = 1
	else
	    set temp = 0
	endif
	
	@ Number_of_chains = ( ( $ASU / $Chain ) + $temp  )
	if($?debug) echo "ASU will be $Number_of_chains chains ($Chain amino acids each)"
	@ ASU = ( $Number_of_chains * $Chain )
    endif
endif

# figure out outer resolution limit from mosflm log.
cat ${logfile}mosflm.log |\
nawk 'h==0 && /Analysis as a function of resolution./{h=1;getline;\
               print $3, $4, $5, $6, $7, $8, $9, $10} \
      /^  <I\/sigma>/{print $2, $3, $4, $5, $6, $7, $8, $9}' |\
nawk 'NR==1{for(i=1;i<9;++i){res[i]=$i};++n} \
      NR!=1{for(i=1;i<9;++i){signal[i]+=$i;++count[i]}}\
      END{if(n) for(i=8;i>0;--i){print res[i], signal[i]/count[i]}}' |\
sort -nr >! ${tempfile}res_limit
set res_limit = `nawk '$NF > 0.5 {print $1+0} $NF<=0 {exit}' ${tempfile}res_limit | tail -1`
rm -f ${tempfile}res_limit >& /dev/null


# reset high resolution limit to this 0.5-sigma cutoff
if("$res_limit" =~ *[0-9].[0-9]* && "$res_choice" != "user") then
    echo "Merging will be limited to $res_limit $ANG (I/sig drops to 0.5 there)."
    set merge_res = $res_limit
endif
if(! $?merge_res) set merge_res = $hires
if("$merge_res" == "") set merge_res = $hires

# figure out how to use scale_partials, etc. from mosflm log
grep "Because the fraction of fully recorded reflections is less than" ${logfile}mosflm.log >& /dev/null
if($status) then
    # mosflm didn't feel the need to use partials, so neither will we
    set scale_partials = "#"
else
    # mosflm used partials in refinement, so we will use them in scaling
    set scale_partials = ""
endif
# see if we have way too many partials
set temp = `echo "$osc $mosaic" | nawk '{printf "%d", 2*$2/$1}'`
set extra_partials
if($temp > 4) then
    set extra_partials = "partials maxwidth $temp"
endif

##############################################################################
#
# Go unwrap scaling scripts
#
echo "Unwrapping ${mergescript}, autoscala and SGsearch.com"
goto Unwrap_Scale_Scripts
Return_Unwrap_Scale_Scripts:
echo ""
#
##############################################################################
set temp2 = ""
set Rmerge = 100

# bail now if CCP4 is not set-up
if($?NO_CCP4) then
    echo "Wedger Elves can go no further without the help of CCP4"

    goto Cleanup
endif

# ask user if we should run merge.com
set temp = "Yes"
if($?NOSCALE) set temp = "No"
if($?SMOOTH_RUNS) set temp2 = " again"
echo "Scale and merge ${mtzout}${temp2}? [$temp]?"
echo -n "$PROMPT"
if($?AUTO) then
    echo "$temp"
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
    # complex answer, send it to the parser
    set input = "$temp"
    goto Questionaire
endif
if("$temp" =~ [Nn]*) goto AUTOscala


Run_mergescript:

if("$SG_choice" == "auto") then
    # as long as we aren't sure about SG, don't pay attention to these
    unset SGsearched
    if(! $?HURRY) unset SD_CORRECTED
endif

echo "running $mergescript ... "
echo ""
echo You can watch the output in `pwd`/${logfile}merge.log
if(-e ${logfile}merge.log) mv ${logfile}merge.log ${logfile}merge.log.old
if(! $?AUTO) onintr AUTOscala
echo "Cycle shift"
./$mergescript $SG | tee ${logfile}merge.log |\
   nawk '/Cycle/{printf "%s %s: ", $2,$3} /mum shift/{print $7}'
#  nawk '/Cycle/{cycle=$3} /mum shift/{shift[cycle]=$7;\
#	slope=0;for(i=cycle;(i>cycle-10 && i>0);--i){wrong+=(shift[i-1]>shift[i])}\
#	print cycle,shift[cycle],shift[cycle]/shift[cycle-1],slope}'
onintr

# check the output
set lastcycle = `nawk '/Cycle/ && int($3+0) == $3{print $3}' ${logfile}merge.log | tail -1`
set maxcycle = `nawk '/^cycles/ && int($2+0) == $2{print $2}' $mergescript`
if("$maxcycle" == "") set maxcycle = 200
if("$lastcycle" == "") set lastcycle = $maxcycle
set test = `grep 'TRUNCATE:  Normal termination' ${logfile}merge.log`

if(("$test" != "")&&(-e "${mergefile}")&&($lastcycle < $maxcycle)) then
    echo ""
    echo "$mergefile contains your scaled and merged data."
    cat ${logfile}merge.log |\
    nawk '$3 == "Dmin(A)" {graph=1; title=$0} \
       graph==1 && $1+0>0{if(title){print title; title=""}; print}\
       $1=="Overall:"{print; graph=0}' |\
    nawk '/Dmin/{idx=index($0,"Mn");printf "%7s %5s %5s %5s %8s\n", $3, $4, $5, $7, $13} \
          $1+0!=0{printf "%7.2f %5.3f %5.3f %5.3f %8.1f\n", $3, $4, $5, $7, substr($0,idx,7)} \
        /Overall/{printf "Overall %5.3f %5.3f %5.3f %8.1f\n", $2, $3, $5, substr($0,idx,7)}' |\
    tee ${tempfile}reslimit |\
    nawk 'NR<3{print; next} /Overall/{if(cut!=outer) print cut; print outer; print} $NF+0>2.8{cut=$0} {outer=$0}' 

    # store the I/sig of the current outer resolution bin
    set outer_sig = `nawk '$1+0>0{printf "%d\n", 10*$NF}' ${tempfile}reslimit | tail -1`

    # interpolate a good resolution cutoff
    cat ${tempfile}reslimit |\
    nawk -v goal=1.5 '$1+0>0 && lastres+0>0 && $NF+0>1.0 && $NF+0<10 && (lastsig-$NF)^2>0 {\
	newres = $1+(goal-$NF)*(lastres-$1)/(lastsig-$NF);\
	newrad = 1/sqrt($1)+(goal-$NF)*(1/sqrt(lastres) - 1/sqrt($1))/(lastsig-$NF); newrad=1/(newrad)^2\
	print $0, newres} {lastres=$1;lastsig=$NF}' |&\
    cat >! ${tempfile}cutoff
    
    set best_res = `nawk '$NF+0>0.1{printf "%.2f\n", $NF}' ${tempfile}cutoff | tail -1`
    rm -f ${tempfile}reslimit ${tempfile}cutoff
    

    # some kind of sanity check on best_res ?
    set test = `echo $best_res $merge_res | nawk 'NF==2{print ($1 > $2)}'`
    if("$test" == "1" && $outer_sig > 30) then
	# we are trying to decrease resolution with good outer signal.  WTF?
	# chose a best_res that is slightly beyond the current merge_res
	set best_res = `echo $merge_res | nawk '$1+0>0.1{printf "%.2f\n", (1.2*($1^-3))^-(1/3)}'`
    endif

    # truncate any wild swings (more than doubling reciprocal space volume)
    set ridiculous_res = `echo "$merge_res" | nawk '$1+0>0.1{printf "%.2f\n", (2.0*($1^-3))^-(1/3)}'`
    set test = `echo $best_res $ridiculous_res | nawk 'NF==2{print ($1 < $2)}'`
    if("$test" == "1") then
	# this would be dangerous.  Instead, integrate at 2x volume and merge again...
	set best_res = $ridiculous_res
    endif

    # pick an integration resolution that is slightly beyond best_res
    set dream_res = `echo "$best_res" | nawk '$1+0>0.1{printf "%.2f\n", (1.5*($1^-3))^-(1/3)}'`

    # clip resolution extention at detector limit (if we know it) 
    set best_res = `echo $best_res $detector_res_limit | nawk 'NF==2 && $1<$2{$1=$2} {print $1}'`
    set dream_res = `echo $dream_res $detector_res_limit | nawk 'NF==2 && $1<$2{$1=$2} {print $1}'`

    # make sure we dont oscillate with a truncate failure
    if("$res_choice" == "truncate") then
	# merge_res was chosen because truncate wouldn't run at anything higher
	set test = `echo $best_res $merge_res | nawk '{print ($1 < $2)}'`
	if($test) set best_res = $merge_res
    endif

    
    # print out completeness (since this IS the real completeness)
    echo "stats nbin 100" |\
     mtzdump HKLIN $mergefile |&\
    nawk '/PARTIAL FILE STATISTICS/,/No. of reflections/' |\
    nawk '$1==4 && NF>3{res=$(NF-2)+0; if(substr($0,28)+0!=0)miss+=substr($0,20)}\
      /partial statistics for resolution bin/{sum+=$NF; \
	print res,100*(sum-miss)/sum}' |\
    sort -n |\
    nawk -v ANG="$ANG" 'NR==1 || $2>90{\
	printf "%.1f%% complete to %.2f %s\n",$2,$1,ANG}\
	$2>90{exit}'


    if ("$best_res" != "") then
        # is this "better" than before?

	echo ""
	set answer = "Yes"
	# don't bother if resolution change is small
	set test = `echo $best_res $merge_res | nawk 'NF==2{print (sqrt(($1^-3 - $2^-3)^2)>0.1*($1^-3) )}'`
	if("$test" == "0") set answer = "No"
	# see if we are extending or retracting resolution limit
	set extending = `echo $hires $best_res | nawk '{print ($1>$2)}'`
        if ("$res_choice" == "truncate" && $extending) set answer = "No"
        if ("$res_choice" == "user") set answer = "No"
        echo "$best_res $ANG looks like a good resolution cutoff."
        echo "shall we use it? [$answer]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $answer
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set answer = ( $in )
        endif
	if("$answer" =~ [Yy]*) then
	    # go ahead and update resolution cutoffs
            set hires = "$dream_res"
	    set merge_res = "$best_res"
	    set SAVE_hires = "$best_res"
	    set res_choice = merge
	    if(! $?AUTO) set res_choice = user
	    set test = `echo $mtz_res $best_res | nawk '{print ($1>$2)}'`
	    if($extending && $test) then
		# need to run mosflm again
		goto PrintIntentions
	    endif
	    goto Unwrap_Scale_Scripts
	endif
    endif

    
    # average sdfac from fulls and partials (compromise)
    cat ${logfile}merge.log |\
    nawk '/Final assessment of SDcorrection multipliers/{getline;getline;getline;getline;\
          while(NF>2){if($2 != 1.0000){++n; print; sum+=($2+$5)/2}; getline}; if(n) printf "%.2f\n", sum/n}' |\
    cat >! ${tempfile}
    set temp = `tail -1 ${tempfile} | nawk '$1+0 > 0.5{print $1}'`
    rm -f ${tempfile}
    
    # now update our SDCORR card
    if("$temp" != "") then
	set SDCORR = `echo "$temp $SDCORR" | nawk '{print $1, $3, $4}'`
	unset DEFAULT_SDCORR
    endif
    
    set Rmerge = `nawk '/Overall:/{printf "%d", $2*100}' ${logfile}merge.log`

    if(! $?SMOOTH_RUNS) then
	# only do this once
    
	# look for breaks in continuity of scales
	cat ${logfile}merge.log |\
	nawk '/ Scales v rotation range/,/Total/' |\
	nawk 'NF>2 && ! /[a-z]/' |\
	nawk '{if(S+0!=0 && $6+0!=0){jump=$6/S; if(jump<1)jump=1/jump;\
	       print $4, jump}else{print $4, 1}; S=$6}' |\
	nawk '$2 > 1.2{print $1-1; print $1} NR==1{print $1} {b=$1} END{print b}' |\
	nawk '{++n; printf "RUN " n " " $1;getline; print " to " $1}' |\
	cat >! ${tempfile}.runs
    
	# see if it's safe to run smooth scaling
	set temp = `cat ${tempfile}.runs | wc -l`
	if($temp >= $number_of_frames) set temp = 999
	if("$temp" < 10) then
	    echo ""
	    if("$temp" == 1) then
		echo "Recomend smooth scales next time."
	    else
		echo "Recomend smoothing scales in $temp segments."
	    endif
	    echo "scales rotation spacing 5 bfactor on"  >> ${tempfile}.runs
	else
	    # too many runs
	    rm -f ${tempfile}.runs
	    echo "scaling was noisy. "
	    echo "you should xloggraph "`pwd`"/${logfile}merge.log"

	    # is this a good idea?
	    echo "maybe try smoothing them out? "
	    set SMOOTH_RUNS = "scales rotation spacing 5 bfactor on"
	endif
    
	# regenerate merge.com with new scaling parameters
	if(-e ${tempfile}.runs) then
	    set SMOOTH_RUNS = `nawk '{printf "%s%%", $0}' ${tempfile}.runs`
	    rm -f ${tempfile}.runs >& /dev/null
	endif
	if($?SMOOTH_RUNS) goto Unwrap_Scale_Scripts
    endif
else
    echo "FAILED! "
    echo ""
    # do something about this?

    # check for sorting bug
    grep "You must either scale down the data or change VRSET" ${logfile}merge.log
    if(! $status) then
	if("$VRSET" == "#") then
	    # we know how to handle this! 
	    set VRSET = ""
	    echo "try adding VRSET -9e+38 to $mergescript"
	    goto Unwrap_Scale_Scripts
	else
	    # VRSET does not work...
	    # slight decrease in resolution cutoff
	    set res_choice = vrset
	    set hires = `echo "$merge_res" | nawk '{printf "%.2f", $1 * 1.1}'`
	    echo "try reducing the resolution to $hires $ANG"

	    # need to run mosflm again
	    goto PrintIntentions
	endif
    endif

    egrep "CCP4_QOPEN: can.t open H" ${logfile}merge.log
    if(! $status && "$VRSET" == "") then
	# VRSET does not work
	set VRSET = "##"
	
	# slight decrease in resolution cutoff
	set hires = `echo "$merge_res" | nawk '{printf "%.2f", $1 * 1.05}'`
	echo "try reducing the resolution to $hires $ANG"
    endif


    # check for overly ambitious resolution cutoff
    grep "Data beyond useful resolution limit" ${logfile}merge.log >& /dev/null 
    if(! $status && $lastcycle < $maxcycle) then
	# we know how to handle this! 
	cat ${logfile}merge.log |\
	nawk '/Wilson Plot/,/TRUNCATE/' |\
	nawk 'NF==10 && ! /[a-z]/{print $6}' |\
	tail -1 >! ${tempfile}res
	set newRES = `cat ${tempfile}res`
	rm -f ${tempfile}res
	
	# now check against old high-res limit
	set test = `echo "$merge_res $newRES" | nawk '{printf "%d", 100*($2-$1)}'`
	if("$test" < 5) then
	    # slight decrease in resolution cutoff
	    set merge_res = `echo "$merge_res" | nawk '{printf "%.2f", $1 * 1.05}'`
	else
	    # use the reso from last good bin in truncate
	    set hires = "$newRES"
	    set merge_res = "$newRES"
	endif
	set res_choice = truncate
	echo "reducing resolution to $merge_res $ANG"
	goto Unwrap_Scale_Scripts
    endif

    if("$merge_tie" == "#") then
        set merge_tie = ""
        echo "lets try forcing consistent scales..."

        # regenerate merge.com with new scaling parameters
        goto Unwrap_Scale_Scripts
    endif

    if("$merge_damp" == "#") then
	set merge_damp = ""
	echo "lets try a damping function in scaling..."

	# regenerate merge.com with new scaling parameters
        goto Unwrap_Scale_Scripts
    endif

    if(! $?SMOOTH_RUNS) then
        set SMOOTH_RUNS = "scales rotation spacing 5 bfactor on"
        # hope that this helps?
        echo "lets use smooth scales this time..."
	set merge_damp = "#"
	set merge_tie = "#"

        # regenerate merge.com with new scaling parameters
        goto Unwrap_Scale_Scripts
    endif

    if("$SMOOTH_RUNS" =~ RUN*) then
        set SMOOTH_RUNS = "scales rotation spacing 5 bfactor on"
        # hope that this helps?
        echo "maybe all those subruns were a bad idea..."
	set merge_damp = "#"
	set merge_tie = "#"

        # regenerate merge.com with new scaling parameters
        goto Unwrap_Scale_Scripts
    endif

    if("$SG_choice" == "auto") then
	# we kind of need this to work...

	# regenerate merge.com with new scaling parameters
#	goto Unwrap_Scale_Scripts
    endif

    echo "you should examine $mergescript and the end of ${logfile}merge.log"

    set Rmerge = 100

    goto Cleanup
endif
echo ""
#
#
# go to Space Group Search if SDs have already been corrected, or if
# the Rmerge totally sucks (wrong space group)
if(($?SD_CORRECTED)||($Rmerge > 35)) goto SG_search











AUTOscala:
########################################################################################

   ##    #    #   #####   ####    ####    ####     ##    #         ##
  #  #   #    #     #    #    #  #       #    #   #  #   #        #  #
 #    #  #    #     #    #    #   ####   #       #    #  #       #    #
 ######  #    #     #    #    #       #  #       ######  #       ######
 #    #  #    #     #    #    #  #    #  #    #  #    #  #       #    #
 #    #   ####      #     ####    ####    ####   #    #  ######  #    #

########################################################################################
#
#	Optimize the SDCORR parameters
#
########################################################################################
onintr
cat << EOF

Sigma corrections:

    Mosflm has calculated a standard deviation (sigma) for every observed 
    intensity in ${mtzout}, based on the counting statistics of the spot 
    measurement.  However, crystal absorption and other systematic errors 
    have not been accounted for.
    
    To make your final sigmas realistic (very important for modern phasing
    and refinement programs), you need to estimate the contribution of 
    systematic errors, and correct Mosflm's sigmas accordingly in scala:
    
    in ${mergescript}: SDCORR Sdfac SdB Sdadd
    
    where: newsigma = Sdfac * sqrt(oldsigma**2 + SdB*Ihl' + (Sdadd*Ihl)**2)
                      for each spot          (see your scala documentation)
    
    Wedger Elves can try a series of SDCORR parameters and then report 
    to you which set results in a "new sigma" which matches the average 
    scatter (disagreement) of symmetry-equivalent spots.
    
EOF
set temp = "Yes"
if($?NOSCALE) set temp = "No"
if($?SD_CORRECTED) set temp = "No"
if($?HURRY) set temp = "No"
echo "Optimize SDCORR in ${mergescript}? [$temp]?"
echo -n "$PROMPT"
if($?AUTO) then
    echo "$temp"
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
    set input = "$temp"
    goto Questionaire
endif
if("$temp" =~ [Nn]*) goto SG_search


# get SDFAC from last scala run (if it's there)
if(-e "${logfile}merge.log") then
    # average sdfac from fulls and partials (compromise)
    cat ${logfile}merge.log |\
    nawk '/Final assessment of SDcorrection multipliers/{getline;getline;getline;getline;\
          while(NF>2){if($2 != 1.0000){++n; print; sum+=($2+$5)/2}; getline}; if(n) printf "%.2f\n", sum/n}' |\
    cat >! ${tempfile}
    set temp = `tail -1 ${tempfile} | nawk '$1+0>0.5 && $1+0<3{print $1}'`
    rm -f ${tempfile}
    
    # now edit the mergeing script
    if("$temp" != "") then
	cat ${mergescript} |\
	nawk -v sdfac=$temp 'toupper($0) ~ /^SDCORR/{print "SDCORR", sdfac, $3, $4} toupper($0) !~ /^SDCORR/' |\
	cat >! ${tempfile}mergescript
	mv ${tempfile}mergescript ${mergescript}
	chmod a+x ${mergescript}
    endif
endif


#echo "while you wait, you might want to read the SCALA manual."
echo ""
echo "Optimizing ${mergescript}'s SDCORR parameters with autoscala: "
if(! $?AUTO) onintr Skip_AUTOscala
./autoscala summary=no ${mergescript} | tee ${logfile}autoscala.log
Skip_AUTOscala:
onintr
rm -f ${mergescript}_test >& /dev/null

# retrieve SDCORR card from optimized script
set temp = ""
if(-e ${mergescript}_best) then
    set temp = `nawk 'toupper($0) ~ /^SDCORR/ && NF==4 && $2+0>0.5 {print $2, $3, $4}' ${mergescript}_best | tail -1`
endif
if("$temp" != "") then
    mv ${mergescript}_best ${mergescript}
    chmod a+x ${mergescript}

    set SDCORR = "$temp"
    unset DEFAULT_SDCORR
else
    # huh?
    echo "Woops! that didn't work! "
    echo "sticking with old SDCORR"
    rm -f ${mergescript}_best >& /dev/null
endif
set SD_CORRECTED
#
#
# now run it again, to update the log
echo "running the new $mergescript with SDCORR $SDCORR ... "
echo ""
echo You can watch the output in `pwd`/${logfile}merge.log
if(-e ${logfile}merge.log) mv ${logfile}merge.log ${logfile}merge.log.old
if(! $?AUTO) onintr SG_search
./$mergescript | tee ${logfile}merge.log | nawk '/Cycle/{printf "%s %s: ", $2,$3} /mum shift/{print $7}'
onintr

# check the output
set temp = `grep 'TRUNCATE:  Normal termination' ${logfile}merge.log`

if(("$temp" != "")&&(-e "${mergefile}")) then

    # get average sdfac from fulls and partials (again)
    cat ${logfile}merge.log |\
    nawk '/Final assessment of SDcorrection multipliers/{getline;getline;getline;getline;\
          while(NF>2){if($2 != 1.0000){++n; print; sum+=($2+$5)/2}; getline}; if(n) printf "%.2f\n", sum/n}' |\
    cat >! ${tempfile}
    set temp = `tail -1 ${tempfile} | nawk '$1+0 > 0.5{print $1}'`
    rm -f ${tempfile}
    
    # now update the SDCORR card (again)
    if("$temp" != "") then
	set SDCORR = `echo "$temp $SDCORR" | nawk '{print $1, $3, $4}'`
    endif
    
    echo -n "final SDCORRections are: SDCORR $SDCORR"
    echo ""
    set temp = `echo $SDCORR | nawk '$1>2 || $3>0.1 {print}'`
    rm -f ${tempfile}
    
    # warn user of unreasonable SDcorrection
    if("$temp" != "") then
	echo "WARNING: SDCORR $SDCORR"
	echo "seems high."
	echo "X-ray data don't usually have this much systematic error. "
	echo "So, this could be due to a correctable mistake."
	echo "I.E. wrong space group, poor partials, incorrect quantum gain. etc."
	echo "look at the manuals for SCALA and MOSFLM to find out more."
	echo ""
    endif

    echo "$mergefile contains your scaled and merged data."
    cat ${logfile}merge.log |\
    nawk '$3 == "Dmin(A)" {graph=1; title=$0} \
       graph==1 && $1+0>0{if(title){print title; title=""}; print}\
       $1=="Overall:"{print; graph=0}' |\
    nawk '/Dmin/{idx=index($0,"Mn");printf "%7s %5s %5s %5s %8s\n", $3, $4, $5, $7, $13} \
          $1+0!=0{printf "%7.2f %5.3f %5.3f %5.3f %8.1f\n", $3, $4, $5, $7, substr($0,idx,7)} \
        /Overall/{printf "Overall %5.3f %5.3f %5.3f %8.1f\n", $2, $3, $5, substr($0,idx,7)}' |\
    nawk 'NR<3{print; next} /Overall/{if(cut!=outer) print cut; print outer; print} $NF+0>2.8{cut=$0} {outer=$0}'
          
    echo ""
    echo " <I>/sd now reflects the true signal/noise of your data."
    echo ""

else
    echo ""
    echo "FAILED! "
    echo ""
    echo "you should examine $mergescript and the end of ${logfile}merge.log"

    # This should never happen
    
    if(! $?AUTO) then
	set input = ""
	goto Questionaire
    endif
    goto Cleanup
endif









SG_search:
onintr
########################################################################################

  ####    ####            ####   ######    ##    #####    ####   #    #
 #       #    #          #       #        #  #   #    #  #    #  #    #
  ####   #                ####   #####   #    #  #    #  #       ######
      #  #  ###               #  #       ######  #####   #       #    #
 #    #  #    #          #    #  #       #    #  #   #   #    #  #    #
  ####    ####            ####   ######  #    #  #    #   ####   #    #

########################################################################################
#
#	If Space group was choses automatically, we should try other possibilities
#
########################################################################################

set temp = "No"
if("$Rmerge" != 100) then
    # merge.com ran okay
    set temp = "Yes"
    # don't bother if we are in a hurry
    if($?AUTO && $?HURRY) set temp = "No"
    # don't do this twice
    if($?SGsearched) set temp = "No"
    # ALWAYS do this if we are fiddling with the space group
    if("$SG_choice" == "auto") set temp = "Yes"
    # unless, of course, there is only one possibility?
    if("$SG" == "P1" || "$SG" == "C2" || "$SG" == "F23" || "$SG" == "F222") then
    endif
endif
# never scale if we were asked not to
if($?NOSCALE) set temp = "No"
echo "Shall we try mergeing other possible space groups? [$temp]?"
echo -n "$PROMPT"
if($?AUTO) then
    echo "$temp"
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
    set input = "$temp"
    goto Questionaire
endif
if("$temp" =~ [Nn]*) goto Patterson

# break out if we get bored
onintr Skip_SGsearch
./SGsearch.com $mtzout ignore | tee ${logfile}SGsearch.log
#./SGsearch.com $mtzout | tee ${logfile}SGsearch.log
onintr
# reminder that we have finished SG search at least once
set SGsearched

# pick up new space group from SGsearch    
set newSGs = `nawk '/Possible/{for(i=5;i<=NF;++i){print $i}}' ${logfile}SGsearch.log`

# retrieve all mergeing groups (lattice + point group)
cat ${CLIBD}/symop.lib |\
nawk '$5~/^PG/ && $1<500{print "LPG",$4,substr($4,1,1)"_"substr($5,3)}' |\
cat >! ${tempfile}SG_LPG

# get the mergeing groups for the SGs chosen by SGsearch
echo "GOOD $newSGs" |\
cat ${tempfile}SG_LPG - |\
nawk '/^LPG/{lpg[$2]=$3;next}\
   /^GOOD/{for(i=2;i<=NF;++i) print "GOOD",$i,lpg[$i]}' |\
cat >! ${tempfile}goodSGs

# get list of space group that were considered by SGsearch
cat ${logfile}SGsearch.log |\
nawk '/^[PCIFR][1-6]/{SG=$1;print SG; }' |\
sort -u |\
cat ${tempfile}SG_LPG - |\
nawk '/^LPG/{lpg[$2]=$3;next}\
  NF==1{print $1,lpg[$1]}' |\
cat >! ${tempfile}tried

# make list of all LPGs that were tried and did not pass
cat ${tempfile}goodSGs ${tempfile}tried |\
nawk '/^GOOD/{++n;good[n]=$3;next}\
      NF==2{for(i in good) if(good[i]==$2) next; print "BAD",$1,$2}' |\
cat >! ${tempfile}badLPGs

# these badSGs are definitely out.  Add them to the wrongSGs list
echo "BAD $wrongSGs" |\
cat ${tempfile}SG_LPG - |\
nawk '/^LPG/{lpg[$2]=$3;next}\
   /^BAD/{for(i=2;i<=NF;++i) print "BAD",$i,lpg[$i]}' |\
cat >> ${tempfile}badLPGs
set wrongSGs = `sort -u ${tempfile}badLPGs | nawk '{print $2}'`

# clear out any taboo space group choices from the SGsearch list
cat ${tempfile}badLPGs ${tempfile}goodSGs |\
nawk '/BAD/{++bad[$3]} /GOOD/ && ! bad[$3] {print}' |\
cat >! ${tempfile}goodLPGs

# find all SGs that are both chosen by SGsearch and not in the bad list
set newSGs = `nawk '{print $2}' ${tempfile}goodLPGs`

# see if the current space group is on the "good" list
set oldLPG = `nawk -v SG=$SG '$2==SG{print $3}' ${tempfile}SG_LPG`
set oldLPGokay = `nawk -v LPG=$oldLPG '$3==LPG{print 1;exit}' ${tempfile}goodLPGs`

append_file_date.com ${tempfile}goodSGs  >& /dev/null
append_file_date.com ${tempfile}goodLPGs  >& /dev/null
append_file_date.com ${tempfile}badLPGs  >& /dev/null
#rm -f ${tempfile}goodSGs ${tempfile}goodLPGs ${tempfile}badLPGs ${tempfile}tried >& /dev/null

# pick "highest" symmetry SG as a representative
set newSG = "$newSGs[$#newSGs]"

# is this higher symmetry than we started with?
if("$newSG" == "P1" && "$SG" != "P1") then
    # P1 is the only one that merged well, but we didn't ask for it!
    # Make sure P1 only "counts" when it came up in autoindexing
    set newSG = ""
endif

# get the lattice and point group symmetry of the "best" SG choice
set newLPG = `nawk -v SG=$newSG '$2==SG{print $3}' ${tempfile}SG_LPG`
rm -f ${tempfile}SG_LPG >& /dev/null


# check out the space groups that "worked"
if("$newSG" != "") then
        
    # current LPG was bad, or a higher-symmetry option is available
    if(("$oldLPGokay" != "1") || ("$newSG" != "$SG")) then
	# user might want to change SG choice
	set temp = "No"
	if("$newLPG" != "$oldLPG") set temp = "Yes"
#	if((! $?AUTO)&&("$newSG" != "$SG")) set temp = "Yes"
	echo "Do you want to remeasure in ${newSG}? [$temp]"
	echo -n "$PROMPT"
	if($?AUTO) then
	    echo $temp
	else
	    echo -n "$BELL"
	    set in = ( $< )
	    if("$in" != "") set temp = ( $in )
	endif
	if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
	    # unexpected answer
	    set input = "$temp"
	    goto Questionaire
	endif
	if("$temp" =~ [Yy]*) then
	    # user okayed new space group choice
	    
	    # don't consider old space group again (unless it is in the same mergeing group)
	    if ( $newLPG != $oldLPG ) then
	        set wrongSGs = ( $wrongSGs $SG )
	    endif
	    set SG = "$newSG"
	    set strategize = yes
	    unset SMOOTH_RUNS

	    # no longer the last run
	    unset LAST_RUN
	    goto ProcessInput
	endif
	# user said they don't want $newSG as a space group
	set wrongSGs = ( $wrongSGs $newSG )
#	if("$temp" =~ [Nn]*) goto Cleanup
    endif	
else
    # No space groups survived the SGsearch (or they were already bad)
    set sys = `nawk -v SG=$SG '$4==SG{print tolower($6);exit}' $CLIBD/symop.lib`
    if(("$sys" == "trigonal")||("$sys" == "hexagonal")) set sys = "trigonal or hexagonal"
    if(! $?WRONG_SYSTEM) set WRONG_SYSTEM
    set WRONG_SYSTEM = ( $sys $WRONG_SYSTEM )
    
    # all these SGs should have already been added to "wrongSGs" above
    
    echo "No $WRONG_SYSTEM space groups merged acceptably. "
    echo "Chances are, this is not you crystal system. "
    echo ""
    echo "You should autoindex again, but, this time, pick a space group"
    echo "that is not ${WRONG_SYSTEM}."
    
    set temp = "Yes"
    if($?AUTO) set temp = "No"
    if("$SG_choice" == "auto") set temp = "Yes"
    echo "Do you want to autoindex again? [$temp]?"
    echo -n "$PROMPT"
    if($?AUTO) then
	echo "$temp"
    else
	echo -n "$BELL"
	set in = ( $< )
	if("$in" != "") set temp = ( $in )
    endif
    if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
	set input = "$temp"
	goto Questionaire
    endif
    if("$temp" =~ [Yy]*) then
	set CELL = "unknown"
	set SG = "unknown"
	set wrongSGs = ( $wrongSGs $LATT )
	
	goto autoindex
    endif
    
endif

goto Update_merge
Skip_SGsearch:
unset AUTO

Update_merge:
onintr

set temp = "Yes"
if(("$Rmerge" != 100)&&("$SG_choice" == "auto")) set temp = "Yes"
if($?AUTO) set temp = "Yes"
if($?NOSCALE) set temp = "No"
echo "Shall we update $mergefile in $SG? [$temp]?"
echo -n "$PROMPT"
if($?AUTO) then
    echo "$temp"
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
    set input = "$temp"
    goto Questionaire
endif
if("$temp" =~ [Nn]*) goto Patterson

# reaching here means the SG found by SGsearch.com is the same
# as the one we started with, so we are now no longer concerned 
# about our automatically-chosen SG
set SG_choice = search

# jump back to script-runner
goto Run_mergescript


if(! $?SD_CORRECTED) goto AUTOscala



Patterson:
########################################################################################
#
#	make the anomalous Patterson (because we can)
#
########################################################################################
if(! -e "$mergefile") goto Cleanup

# reduce resolution a skosh...
set pattRES = `echo "$hires" |  nawk '$1>0{printf "%.1f", 1/(0.5*((1/$1)^3))^(1/3)}'`
if("$pattRES" == "") set pattRES = 4

# quick script
cat << EOF-script >! Patt.com
#! /bin/csh -f
#
#	basic Patterson script
#
set file1 = "$mergefile"
set file2 = ""
set RESO = $pattRES
set DIFF = ""
set SIG  = 0

if(-e "\$1") set file1 = "\$1"
if(-e "\$2") set file2 = "\$2"

set outfile  = Patt.map
set tempfile = "patt_temp"

if(-e "\$file2") goto iso

# apply an evelope-matching noise supression filter? 
set rolloff = \`echo \$RESO | awk '{print 8.8*\$1*\$1}'\`

######################
if("\$DIFF" == "") then
    # use scalit to get a good maximum-difference cutoff
    scaleit hklin \$file1 << EOF >&! \${tempfile}scale.log
    analyze
    labin FP=DANO SIGFP=SIGDANO FPH1=F SIGFPH1=SIGF
    scale FPH1 0.0000001
    END
EOF
    set DIFF = \`awk '/acceptable differences/{print \$NF}' \${tempfile}scale.log\`
    rm -f \${tempfile}scale.log >& /dev/null
endif

######################
# anomalous Patterson
fft hklin \$file1 mapout \${tempfile}.map << EOF-fft 
PATTERSON
RESOLUTION \$RESO
LABIN F1=DANO SIG1=SIGDANO F2=F SIG2=SIGF
SCALE F1 1 \$rolloff
SCALE F2 0.000001 0
EXCLUDE DIFF \$DIFF
EXCLUDE SIG1 \$SIG
EOF-fft
goto norm

iso:
######################
# isomorphous (dispersive) difference

# put both data sets into same file
cad hklin1 \$file1 hklin2 \$file2 \\
    hklout \${tempfile}.mtz << EOF-cad
LABIN file 1 E1=F  E2=SIGF
LABOU file 1 E1=F1 E2=SIGF1
LABIN file 2 E1=F  E2=SIGF
LABOU file 2 E1=F2 E2=SIGF2
EOF-cad

if(! \$?SCALED) then
    # need to scale input files together
    scaleit HKLIN \${tempfile}.mtz \\
           HKLOUT \${tempfile}scaled.mtz << EOF-scaleit | tee \${tempfile}log
LABIN FP=F1  SIGFP=SIGF1 FPH1=F2 SIGFPH1=SIGF2 
#RESO \$RESO 1000	# exclude lowest resolution data? 
#WEIGHT			# Sigmas should be reliable.
refine anisotropic	# use an anisotropic B-factor
#refine isotropic	# use an isotropic B-factor
#norefine		# don't change relative scale
END
EOF-scaleit
    # now this is the file we want to use for fft
    mv \${tempfile}scaled.mtz \${tempfile}.mtz

    if("\$DIFF" == "") then
	# auto-set DIFF from scaleit output
	set DIFF = \`awk '/acceptable differences/{print \$NF}' \${tempfile}log\`
    endif
    rm -f \${tempfile}log >& /dev/null
endif

######################
# do the Patterson
fft hklin \${tempfile}.mtz mapout \${tempfile}.map << EOF-fft 
PATTERSON
LABIN F1=F1 SIG1=SIGF1 F2=F2 SIG2=SIGF2
RESOLUTION \$RESO
SCALE F1 1 \$rolloff
SCALE F2 1 \$rolloff
EXCLUDE DIFF \$DIFF
EXCLUDE SIG1 \$SIG
EXCLUDE SIG2 \$SIG
EOF-fft
goto norm



norm:
# normalize the output map
echo "SCALE SIGMA" |\\
mapmask mapin \${tempfile}.map mapout \$outfile

# quick peak-pick (for the log)
peakmax mapin \$outfile PEAKS \${tempfile}.xyz TO \${tempfile}.xyz << eof-pick
THRESHOLD RMS 3
OUTPUT PEAKS
END
eof-pick

# clean up
rm -f \${tempfile}.map >& /dev/null
rm -f \${tempfile}.mtz >& /dev/null
rm -f \${tempfile}.xyz >& /dev/null

EOF-script
chmod a+x Patt.com


# now as the user if we should run it
set temp = "No"
if(("$Rmerge" != 100)&&("$SG_choice" == "auto")) set temp = "Yes"
if($?AUTO) set temp = "Yes"
echo "Shall we make an anomalous Patterson map? [$temp]?"
echo -n "$PROMPT"
if($?AUTO) then
    echo "$temp"
else
    echo -n "$BELL"
    set in = ( $< )
    if("$in" != "") set temp = ( $in )
endif
if(($#temp > 1)||("$temp" !~ [NnYy]*)) then
    set input = "$temp"
    goto Questionaire
endif
if("$temp" =~ [Nn]*) goto Cleanup

# run it
rm -f Patt.map >& /dev/null
./Patt.com >! ${logfile}patt.log
if(-e "Patt.map") then
    echo "Patt.map is ready."
endif


# check and see if new frames have appeared? 



goto Cleanup












































exit

Unwrap_Scale_Scripts:
################################################################################

 #    #  #    #  #    #  #####     ##    #####
 #    #  ##   #  #    #  #    #   #  #   #    #
 #    #  # #  #  #    #  #    #  #    #  #    #
 #    #  #  # #  # ## #  #####   ######  #####
 #    #  #   ##  ##  ##  #   #   #    #  #
  ####   #    #  #    #  #    #  #    #  #

################################################################################
#	Unwrap scaling scripts: merge.com, autoscala, and SGsearch
################################################################################

if(-e $mergescript) then
    # retrieve old SDCORR card?
    if($?DEFAULT_SDCORR) then
	set temp = `nawk 'toupper($0) ~ /^SDCORR/ && NF>2 && $2>0.1 {print $2, $3, $4}' ${mergescript} | tail -1`
#	if($#temp > 1) set SDCORR = "$temp"
    endif
endif

set merge_temp = merge_temp
if($?CCP4_SCR) then
    if(-e "$CCP4_SCR") set merge_temp = '${CCP4_SCR}/merge_temp$$'
endif

# defaults
if(! $?merge_tie) set merge_tie = "#"
if(! $?merge_damp) set merge_damp = "#"


cat << EOF-mergescript >! $mergescript
#! /bin/csh -fe
#
#  Automatically generated scaling script for:
set title = "$framedir/${template} frames $first to $last"
#
# make sure netscape reads the graphs properly
echo "<html><pre>"
Help:
if(("\$1" == "")||(\$?HELP)) then
    cat << EOF

usage: \$0 raw.mtz [$SG] [${merge_res}A] [aa]

where: $SG 	- is the space group you want to "reindex" to.
       ${merge_res}A	- is the outer resolution cutoff
       aa	- is the number of amino acids in your asymmetric unit

EOF
    if(\$?HELP) exit
endif


# make sure awk works
alias nawk $nawk
nawk 'BEGIN{exit}' >& /dev/null
if(\$status) alias nawk awk
##############################################################################
set rawfile = $mtzout
set outfile = $mergefile
set tempfile = $merge_temp

##############################################################################
# this value was estimated for a Vm of $Vm in $SG
set ASU  = $ASU
set SG   = ""
set CELL = ""
set RES  = $merge_res

##############################################################################
goto Setup
# interpret command line
Return_From_Setup:
##############################################################################

echo "scaling, mergeing and truncating \$rawfile into \$outfile"
echo "to \${RES}A in \$SG with \${ASU}aa per ASU"



##############################################################################
# make sure the output is sorted
#
##############################################################################
sortmtz hklout \${tempfile}.sorted.mtz  << end_sort
${VRSET}VRSET -9e+38
H K L M/ISYM BATCH I SIGI
\$rawfile
end_sort
#
##############################################################################
# now run SCALA 
#
##############################################################################
scala hklin \${tempfile}.sorted.mtz hklout \${tempfile}.scaled.mtz  \
ROGUES rejected_spots.txt \
ANOMPLOT \${tempfile}.anomplot \
NORMPLOT \${tempfile}.normplot \
SCALES \${tempfile}.scales << EOF-scale
# save disk space?
#NODUMP
#ANALYSE NOPLOT

title "batch scaling of \$title"

resolution \$RES

EOF-mergescript
#if(-e ${tempfile}.runs) then
#    cat ${tempfile}.runs >> $mergescript
#    rm -f ${tempfile}.runs
#else
if($?SMOOTH_RUNS) then
    echo "$SMOOTH_RUNS" |\
	 nawk 'BEGIN{RS="%"} {print}' >> $mergescript
else
    echo "scales batch bfactor on" >> $mergescript
endif
cat << EOF-mergescript >> $mergescript

# straight frame-by-frame scales (for discontinuities in dose per frame)
#scales batch bfactor on
# frame-by-frame scales with smooth B-factor (discontinuous dose, but no xtal decay)
#scales batch bfactor on brotation spacing 5 
# smooth scales with smooth B-factor (if you have no discontinuities in dose per frame)
#scales rotation spacing 5 bfactor on
#
# restrain scales
${merge_tie}tie rotation 0.1
${merge_damp}DAMP 0.1 50
#
# extend nearly-full partials (this is important if you have no fulls)
#intensities scale_partials 0.8
# or use summed partials as fulls:
${scale_partials}intensities partials
$extra_partials
#
#########################################################
#  See SCALA documentation
SDCORR $SDCORR
#########################################################
# 
# converge to within 0.3 sigmas of deviation (maximum of 200 cycles)
cycles 200 converge 0.3

anomalous on

EOF-scale
#
##############################################################################
# run truncate to finish the job
#
##############################################################################
truncate:
truncate hklin \${tempfile}.scaled.mtz hklout \${tempfile}.merged.mtz << EOF-trunc
title "anomalous truncate of \$title"
# resolution used to determine B factor
#rscale 4 2.8
#ranges 0.01

nresidue \$ASU
truncate yes
anomalous yes
LABOUT  F=F  SIGF=SIGF DANO=DANO SIGDANO=SIGDANO ISYM=ISYM
EOF-trunc

##############################################################################
# make sure completeness is correctly reported in mtz
#
##############################################################################
unique hklout \${tempfile}.unique.mtz << EOF-unique
SYMM \$SGnum
CELL \$CELL
RESOLUTION \$RES
LABOUT  F=F  SIGF=SIGF
EOF-unique
mtzutils hklin1 \${tempfile}.merged.mtz \
         hklin2 \${tempfile}.unique.mtz \
         hklout \$outfile << EOF-util
UNIQUE
RUN
EOF-util

# clean up
rm -f \${tempfile}.merged.mtz >& /dev/null
rm -f \${tempfile}.unique.mtz >& /dev/null
rm -f \${tempfile}.scaled.mtz >& /dev/null
rm -f \${tempfile}.sorted.mtz >& /dev/null
rm -f \${tempfile}.anomplot   >& /dev/null
rm -f \${tempfile}.normplot   >& /dev/null
rm -f \${tempfile}.scales     >& /dev/null
rm -f \${tempfile}.\${SG}.mtz  >& /dev/null
exit

##############################################################################
##############################################################################
##############################################################################
##############################################################################
Setup:
# command-line arguments
foreach arg ( \$* )
    if("\$arg" =~ *.mtz) set rawfile = "\$arg"
    if(("\$arg" =~ [0-9]*)&&("\$arg" =~ *A)) then
        # a number ending with "A" must mean resolution
        set RES = \`echo "\$arg" | nawk '{print \$1+0}'\`
	continue
    endif
    if(("\$arg" =~ [0-9]*)&&("\$arg" !~ [a-z,A-Z]*)) then
	# a pure number is on the command line
	if("\$arg" =~ *.*) then
	    # take it as resolution
	    set RES = \`echo "\$arg" | nawk '{print \$1+0}'\`
	else
	    # take it as ASU size
	    set ASU = \`echo "\$arg" | nawk '{print \$1+0}'\`
	endif
    endif
    
    # new space group
    if("\$arg" =~ [PpCcIiFfRrHh][1-6]*) then
	set temp = \`nawk -v SG=\$arg '\$4 == toupper(SG) && \$1<500 {print \$4;exit}' \$CLIBD/symop.lib | head -1\`
	if("\$temp" =~ [PpCcIiFfRrHh][1-6]*) then
	    # known space group
	    set new_SG = "\$temp"
	else
	    # check for "pseudo-spacegroup" language
	    if("\$arg" =~ [Pp]2212) then
		# P2221 with screw along current "b"
		set new_SG = "P2221"
		set REINDEX = "reindex l, h, k"
	    endif
	    if("\$arg" =~ [Pp]2122) then
		# P2221 with screw along current "a"
		set new_SG = "P2221"
		set REINDEX = "reindex k, l, h"
	    endif
	    if("\$arg" =~ [Pp]21221) then
		# P21212 with non-screw along current "b"
		set new_SG = "P21212"
		set REINDEX = "reindex l, h, k"
	    endif
	    if("\$arg" =~ [Pp]22121) then
		# P21212 with non-screw along current "a"
	    	set new_SG = "P21212"
		set REINDEX = "reindex k, l, h"
	    endif
	endif
    endif
end


##############################################################################
# check input MTZ file
if(! -e "\$rawfile") then
    set HELP
    goto Help
endif

##############################################################################
# update cell and SG variables from the raw MTZ header
#
##############################################################################
echo "HEADER" | mtzdump hklin \$rawfile >! \$tempfile
set SG =   \`nawk '/Space group/{gsub("\\047","");print \$5}' \$tempfile\`
set SGnum = \` nawk '/Space group/{print \$NF+0}' \${tempfile} \`
set SG = \` nawk -F "[\\047]" '/Space group/{print \$2}' \${tempfile} \`
set SG = \` nawk -v num=\$SGnum '\$1==num && NF>5{print \$4}' \${CLIBD}/symop.lib \`
set CELL = \`nawk '/Cell Dimensions/{getline;getline;print}' \$tempfile\`
set mtzRES = \`nawk '/Resolution Range/{getline;getline;print \$6}' \$tempfile\`
rm -f \$tempfile

set temp = \`echo "\$RES \$mtzRES" | nawk '\$1>=\$2{print \$1} \$1<\$2{print \$2}'\`
if("\$temp" != "\$RES") then
    echo "\$rawfile resolution is only \${temp}A"
    set RES = "\$temp"
endif


##############################################################################
# change of space group? 
#
##############################################################################
if(("\$?new_SG")||(\$?REINDEX)) then
    # need a new space group
    if(! \$?REINDEX) set REINDEX = ""
    
    # change the space group
    echo "reindexing \$rawfile to \$new_SG \$REINDEX"
    if("\$new_SG" =~ R* || "\$new_SG" =~ H*) then
	set test = \` nawk -v SG=\$new_SG '\$4==SG{print \$1; exit}' \${CLIBD}/symop.lib \`
	if("\$test" != "") set new_SG = \$test
    endif
    reindex HKLIN \$rawfile HKLOUT \${tempfile}.\${new_SG}.mtz << end_reindex
SYMMETRY \$new_SG
\$REINDEX
END
end_reindex
    set SG = \$new_SG
    set rawfile = \${tempfile}.\${SG}.mtz
endif


goto Return_From_Setup

EOF-mergescript
chmod a+x $mergescript



















































cat << EOF-autoscala >! autoscala
#! $nawk -f
BEGIN {
#
#
#	Automatically adjusts SDCORR card in SCALA for "optimum" statistics
#	as given by agrovata.
#
#	The provided script MUST generate mergeing statistics (agrovata or scala).
#	The following scripts must be creatable.
#
#	test_script = "./" FILENAME "_test"
#	best_script = "./" FILENAME "_best"
#
#	The latter will continuously be updated to the best SDCORR line
#	found so far.
#
#
#
#
#
#
#
	# these are convergence criteria
	# specify the number of decimal places you want to refine
	# each variable to.
	sdfac_decimals = 2
	sdprime_decimals = 0
	sdadd_decimals = 2

	# defaults for Golden Section search
	# go ahead and modify these if you're 
	# SURE the best value is bracketed
	maximum_sdprime = 15
	maximum_sdadd   = 0.1

	minimum_sdprime = 0
	minimum_sdadd   = 0
	
	# alternately, you may specify "tune=factor"

	best_so_far = 1000000
	line = 0
	if(!debug) debug = 0
}
# finish up initialization (for linux awk)
NR==1{
    if((!test_script)&&(FILENAME)) test_script = "./" FILENAME "_test"
    if((!best_script)&&(FILENAME)) best_script = "./" FILENAME "_best"
    if((!test_log)&&(FILENAME))    test_log    = "./" FILENAME ".log"

    if(!test_script) test_script = "./scala.com_test"
    if(!best_script) best_script = "./scala.com_best"
    if(!test_log)    test_log    = "./scala.com.log"
}

########################################################################
#       Analyze the supplied script & copy it into memory              #
########################################################################

# copy the script into an array
{
    ++line;
    ++number_of_lines;
    script[line] = \$0;

    # now make everything easier to search
    \$0 = tolower(\$0);
}

# look for the "SDCORR" card in scala
/^sdcorr/ {
    # get the current sd correction parameters
    sdfac = \$2;
    if(NF == 4)
    {
	sdprime = \$3;
	sdadd = \$4;
    }
    else
    {
	# no sdprime specified
	sdprime = 0;
	sdadd = \$3;
    }	

    sdcorr_line = line;
}

END {
########################################################################
#	Now begins the "real" program                                  #
########################################################################


    # user may specify "tuning mode"
    if(tune > 1)
    {
	if(sdprime)
	{
	    maximum_sdprime = sdprime * tune;
	    minimum_sdprime = sdprime / tune;
	}

	if(sdadd)
	{
	    maximum_sdadd = sdadd * tune;
	    minimum_sdadd = sdadd / tune;
	}
    }

    # signal to optimize ...
    max_sdfac = max_sdprime = max_sdadd = "restart"
    done = 0;
    
    while(!done)
    {
	# write the script
	WriteScript(test_script);

	if(value[script[sdcorr_line]] != 0)
	{
	    # we have already caclulated this value
	    
	    RMSD_sigma = value[script[sdcorr_line]]
	    if(debug>1) print  "recall: " script[sdcorr_line] "\\t\\tRMSD(sigma): " RMSD_sigma*100 "\\tbest so far: " best_so_far*100;
	}
	else
	{
	    # we havn't run this pair before
	    
	    # run it, and filter output
	    printf  "trying: %s ", script[sdcorr_line] sdcorr_pad;
	    GetResults(test_script);
	
	    # remember all values obtained (to avoid repeats)
	    value[script[sdcorr_line]] = RMSD_sigma;

	    # print out rating of this run
	    printf "RMS(scatter/sigma -1): %8.5f    ", RMSD_sigma;

	    # update absolute best result
	    if(RMSD_sigma < best_so_far) 
	    {
		best_so_far = RMSD_sigma;
		best_sdcorr = script[sdcorr_line];

		# write out best scripts immediately
		WriteScript(best_script);

		# print out the values used, and their effect
		printf "best so far: %8.5f ", best_so_far;
	    }
	    # finish the line
	    print "";
	}

	# pick next values based on last run...
	if(NextSDadd()) 
	{
	    # ...has converged
	    
	    # "inner" loop done, so pick next sdprime value
	    if(NextSDprime()) 
	    {
		# ...has converged
		
		# both have converged, so we are done
		done = "true";
	    }
	    # reoptimize sdadd with new sdprime
	    max_sdadd = "restart";
	}
    }
    
    # Main loop has exited.
    # parameters have converged, so finish up


    # update scala's output files to best values
    #GetResults(best_script);

    
    # update variables for output
    split(best_sdcorr, best);
#    sdfac   = best[2];
    sdfac   = sprintf("%." sdfac_decimals "f", best_sdfac);
    sdprime = best[3];
    sdadd   = best[4];    
    
    # get rid of "test" script
    system("rm -f " test_script)
    # update the "best" script
    WriteScript(best_script);
    
    if(summary != "no")	    # option for cleaner output
    {
	print  "\\n\\nSUMMARY:\\n"
	printf("%s ==> RMSD = %.4f\\n", best_sdcorr, value[best_sdcorr]);
	print  "\\n"
	print  "****************************************"
	print  "**      BEST CARD FOUND               **"
	printf "**      %21s         **\\n", script[sdcorr_line];
	print  "****************************************"
	print  "\\n"

	# tell user what to do next
	print "***********************"
	print "***   ALL DONE!!!   ***"
	print "***********************"

	print "Your new " FILENAME " can be found at: " best_script

    }

}
########################################################################
#	Functions used in this script                                  #
########################################################################


#########################################################################
#	NextSDprime()							#
#									#
#	Updates optimizing parameters based on observed output from	#
#	the agrovata script.						#
#									#
#	uses:		RMSD_sigma					#
#									#
#	modifies:	sdprime						#
#									#
#	contains:	max_sdprime					#
#			min_sdprime					#
#			best_sdprime					#
#									#
#			value[]						#
#									#
#########################################################################
function NextSDprime()
{
    # offset SDprime to keep from interfering with sdfac in value[]
    sdprime += 100;
    best_sdprime += 100;

    # this should be known first
    value[sdprime] = RMSD_sigma;

    # pick some reasonable limits
    if (max_sdprime == "restart") 
    {
	min_sdprime = minimum_sdprime +100;
	value[max_sdprime] = 100000;

	best_sdprime = min_sdprime;
	value[best_sdprime] = 100000;

	max_sdprime = maximum_sdprime +100;
	value[max_sdprime] = 100000;
    }

    # use the Golden Section method to find minimum
    sdprime = GoldStep(min_sdprime, sdprime, best_sdprime, max_sdprime);
    min_sdprime = Gold_min;
    max_sdprime = Gold_max;
    best_sdprime = Gold_best;

        
    # just for monitoring...
    sdprime_step = sdprime - best_sdprime;
	
    # update move counter
    ++move;

    # now move sdprime back to true value
    sdprime -= 100;
    best_sdprime -= 100;

    # check for convergence
    if(max_sdprime - min_sdprime < 0.1^sdprime_decimals)
    {
	#convergence reached
	doneness = "true";
    }
    else
    {
	doneness = "";
    }
    
    # in case you're intetested...
    return doneness;
}

#########################################################################
#	NextSDadd()							#
#									#
#	Updates optimizing parameters based on observed output from	#
#	the agrovata script.						#
#									#
#	uses:		RMSD_sigma					#
#									#
#	modifies:	sdadd						#
#									#
#	contains:	max_sdadd					#
#			min_sdadd					#
#			best_sdadd					#
#									#
#			value[]						#
#									#
#########################################################################
function NextSDadd()
{
    # this should be known first
    value[sdadd] = RMSD_sigma;

    # pick some reasonable limits
    if (max_sdadd == "restart") 
    {
	min_sdadd = minimum_sdadd;
	value[max_sdadd] = 100000;

	best_sdadd = min_sdadd - min_sdadd_step/10;
	value[best_sdadd] = 100000;

	max_sdadd = maximum_sdadd;
	value[max_sdadd] = 100000;
    }

    # use the Golden Section method to find minimum
    sdadd = GoldStep(min_sdadd, sdadd, best_sdadd, max_sdadd);
    min_sdadd = Gold_min;
    max_sdadd = Gold_max;
    best_sdadd = Gold_best;

                
    # just for monitoring...
    sdadd_step = sdadd - best_sdadd;
	
    # update move counter
    ++move;

    # check for convergence
    if(max_sdadd - min_sdadd < 0.1^sdadd_decimals)
    {
	#convergence reached
	doneness = "true";
    }
    else
    {
	doneness = "";
    }

    # in case you're intetested...
    return doneness;
}





#########################################################################
#	WriteScript(filename)						#
#									#
#	Writes the script contained in the script[] array to the	#
#	file given in "filename."					#
#		The following cards, however, are rewriten with		#
#	the existing trial values:	WIDTH				#
#									#
#	uses:		script[]					#
#			bin_scale					#
#			width						#
#									#
#########################################################################
function WriteScript( filename )
{	
    for(line = 1; line <= number_of_lines; ++line)
    {
	if(line == sdcorr_line)
	{
	    script[line] = "SDCORR " sdfac \\
				 " " round(sdprime, sdprime_decimals) \\
				 " " round(sdadd, sdadd_decimals);
	    sdcorr_pad = "";
    	    for(i=0;i < 25 - length(script[line]); ++i) {sdcorr_pad = sdcorr_pad " "}
	}

	print script[line] > filename;
    }
    # close the file
    close(filename);

    #change it to an executable;
    system("chmod u+x " filename);
}


#########################################################################
#       GetResults(filename)                                            #
#                                                                       #
#       Runs the script given as "filename" and analyzes the output     #
#       for the agrovata Sigma(scatter/SD) graph.                       #
#               The RMS deviation from an even distribution of          #
#       observations per intensity bin is computed as RMSD_width.       #
#               The RMS deviation from 1.0 of the scatter/SD is         #
#       also computed and placed in RMSD_sigma.                         #
#                                                                       #
#       modifies:       RMSD_width                                      #
#                       RMSD_width_p                                    #
#                       RMSD_sigma                                      #
#                       RMSD_sigma_p                                    #
#                       RMSD_sigma_w                                    #
#                       best_sdfac                                      #
#                                                                       #
#########################################################################
function GetResults ( filename )
{
    # report what we're doing
#    print "running " filename "..."

    # analyze stdout from "agrovata" script
    command = filename
#    if(test_log) command = filename " | tee " test_log
    while(command | getline > 0)
    {
        # look for the graph entry
        if (\$0 ~ /^ \\\$GRAPHS: Sigma\\(scatter\\/SD\\)/)
	{
	    graph = 1
	    
	    # initialize cumulative variables
	    count_full["sum"]=count_part["sum"]=count["sum"]=0
	    bins = 0  
	}
	if (\$1 == "TOTALS:") graph = 0

        if (graph && (\$0 !~ /[a-z]/) && NF>3)
        {
            # we are reading a line of graph data
	    ++bins
	    
	    # gather stats	    
#	    count_full[bins]  = \$5
#	    count_part[bins]  = \$9
	    count_full[bins]  = substr(\$0, 38, 9)+0
	    count_part[bins]  = substr(\$0, 77, 9)+0
	    count[bins]       = count_full[bins]+count_part[bins]

	    # sums
	    count_full["sum"] += count_full[bins]
	    count_part["sum"] += count_part[bins]
	         count["sum"] += count[bins]

#	    scatt_full[bins]  = \$7-1
#	    scatt_part[bins]  = \$NF-1
	    scatt_full[bins]  = substr(\$0, 55, 8)-1
	    scatt_part[bins]  = \$NF-1
	    scatt[bins]       = (scatt_full[bins]+scatt_part[bins])/2
	}

        # look for refined SDfac
	if(\$0 ~ /Final assessment of SDcorrection multipliers/) { sdfac_list = 1 }
	if(\$0 ~ /Summary/) { sdfac_list = 0 }

	if(sdfac_list)
	{
	    if((\$0 ~ /[0-9]/)&&(\$0 !~ /[a-z]/))
	    {
		if(NF>2)
		{
		    ++sdfacs
		    sdfac_sum+=(count_full["sum"]*\$2+count_part["sum"]*\$5)/(count["sum"])
		}
		else
		{
		    sdfac_list = 0
		}
	    }
	}
    }
    
    # close the pipe!
    close(filename);

    # calculate mean SDFAC
    if(sdfacs) best_sdfac = sdfac_sum/sdfacs
#    printf best_sdfac

    # the scatt and count arrays should now contain the LAST graph in the log
    if(bins)
    {
	# calculate average values
	count_full["avg"] = count_full["sum"]/bins
	count_part["avg"] = count_part["sum"]/bins
	count["avg"]      = count["sum"]     /bins

	# and now rmsds
	count_full["rms"]=count_part["rms"]=count["rms"]=0
	scatt_full["rms"]=scatt_part["rms"]=scatt["rms"]=scatt["wrms"]=0
	for(i=1; i<=bins; ++i)
	{
	    count_full["rms"] += (count_full[i]-count_full["avg"])*(count_full[i]-count_full["avg"])
	    count_part["rms"] += (count_part[i]-count_part["avg"])*(count_part[i]-count_part["avg"])
	    count["rms"]      += (count[i]     -count["avg"]     )*(count[i]     -count["avg"]     )

	    scatt_full["rms"] += scatt_full[i]*scatt_full[i]
	    scatt_part["rms"] += scatt_part[i]*scatt_part[i]
	    scatt["rms"]      += scatt[i]*scatt[i]
	    scatt["wrms"]     += count_full[i]*scatt_full[i]*scatt_full[i]
	    scatt["wrms"]     += count_part[i]*scatt_part[i]*scatt_part[i]
	}
	
	count_full["rms"] = sqrt(count_full["rms"]/bins)
	count_part["rms"] = sqrt(count_part["rms"]/bins)
	count["rms"]      = sqrt(count["rms"]/bins)
	
	scatt_full["rms"] = sqrt(scatt_full["rms"]/bins)
	scatt_part["rms"] = sqrt(scatt_part["rms"]/bins)
	scatt["rms"]      = sqrt(scatt["rms"]/bins)
	scatt["wrms"]     = sqrt(scatt["wrms"]/count["sum"])
    }
    else
    {
	print "ERROR: no stats generated by " filename
	print "please edit " FILENAME " and make sure it runs by itself."
	exit
    }

    # update global variables
    RMSD_width   = count_full["rms"]
    RMSD_width_p = count_part["rms"]
    RMSD_sigma   = scatt_full["rms"]
    RMSD_sigma_p = scatt_part["rms"]
    RMSD_sigma_w = scatt["wrms"]

    RMSD_sigma = RMSD_sigma_w

}

#########################################################################
#	GoldStep(min, last, best, max)					#
#									#
# Computes the Golden (next) step to minimize a variable		#
#									#
#	modifies:							#
#									#
#########################################################################

function GoldStep(min, last, best, max)
{
    # debugging...
    if(debug) printf "\\n" min " " best " " max " ==GoldStep==> "
    
    # eliminate sections that cannot contain the minimum
    if(last >= best)
    {
	# we tried a larger value last time
	if(value[last] <= value[best])
	{
	    # minimum must be somewhere between "best" and "max"
	    min = best;
	    best = last;
	}
	else
	{
	    # minimum must be somewhere between "min" and "last"
	    max = last;
	}
    }
    else
    {
	# we tried a smaller value last time
	if(value[last] <= value[best])
	{
	    # minimum must be somewhere between "min" and "best"
	    max = best;
	    best = last;
	}
	else
	{
	    # minimum must be somewhere between "last" and "max"
	    min = last;	    
	}
    }

    # now decide what width to try next
    if((max - best) > (best - min))
    {
	# next value should be larger
	Gold_next = best + 0.38*(max - best)
    }
    else
    {
	# next value should be smaller
	Gold_next = best - 0.38*(best - min)
    }
    
    # save the parameters as Globals ( this is awful!)
    Gold_min = min;
    Gold_max = max;
    Gold_next = Gold_next;
    Gold_best = best;
    
    # debugging...
    if (debug) printf min " " best " " max "\\t"
    
    return Gold_next;
}


function abs(number)
{
	return sqrt(number^2);
}

function round(number, sigdigs)
{
	return int(number*10^sigdigs)/10^sigdigs;
}

EOF-autoscala
chmod a+x autoscala



















































cat << EOF-search >! SGsearch.com
#! /bin/csh -f
#
#	SGsearch.com	4.1			-James Holton   6-30-04
#
#  Space group search script for scala scripts
#
set rawfile  = raw.mtz
set script   = merge.com
set logfile  = logs/merge
set tempfile = \${CCP4_SCR}/SGsearch_temp\$\$

set SG   = P1		# read from \$rawfile
set CELL		
set RES  = ""		# default to resolution in \$script or \$rawfile
set P1_scales_SG = ""

alias nawk $nawk
nawk 'BEGIN{exit}' >& /dev/null
if(\$status) alias nawk awk

# command-line arguments (1 of 2)
foreach arg ( \$* )
    if(-e "\$arg") then
	if("\$arg" =~ *.mtz) set rawfile = "\$arg"
	if("\$arg" =~ *.com) set script  = "\$arg"
    endif
    if("\$arg" == ignore) set IGNORE
end

if((! -e "\$rawfile")||(! -e "\$script")) then
cat << EOF
usage: \$0 [\$script] [\$rawfile] \$SG 2.2A
where:
 \$script will scale and merge
 scaling, mergeing and truncating \$rawfile

 \$rawfile is the unmerged mtz file

 \$SG is the "root" space group i.e.
    P222 for P222, P2221, P21212, and P212121

 2.2A is the resolution for scaling and mergeing


EOF
    exit 1
endif

ls -1 \${logfile}.*.log >& /dev/null
if((! \$status)&&(! \$?IGNORE)) then
    echo ""
    echo "NOTICE: using stats from \${logfile}.*.log"
    echo ""
endif
if(! -e logs) mkdir logs

echo -n "evaluating alternative space groups for \$rawfile with \$script"

##############################################################################
# update cell and SG variables from the raw MTZ header
#
##############################################################################
echo "HEADER" | mtzdump hklin \$rawfile >! \$tempfile
set SG = \`nawk '/Space group/{print \$5}' \$tempfile\`
set SG = \`nawk '/Space group/{gsub("\\047","");print \$5}' \$tempfile\`
set SGnum = \` nawk '/Space group/{print \$NF+0}' \${tempfile} \`
set SG = \` nawk -F "[\\047]" '/Space group/{print \$2}' \${tempfile} \`
set SG = \` nawk -v num=\$SGnum '\$1==num && NF>5{print \$4}' \${CLIBD}/symop.lib \`
set CELL = \`nawk '/Cell Dimensions/{getline;getline;print}' \$tempfile\`
set mtzRES = \`nawk '/Resolution Range/{getline;getline;print \$6}' \$tempfile\`

# calculate unit cell volume
echo \$CELL |\\
nawk 'NF==6{s=atan2(1,0)/90; A=cos(s*\$4); B=cos(s*\$5); G=cos(s*\$6); \\
 skew = 1 + 2*A*B*G - A*A - B*B - G*G ; if(skew < 0) skew = -skew;\\
 printf "%.3f\\n", \$1*\$2*\$3*sqrt(skew)}' |\\
cat >! \${tempfile}volume
set CELLvolume = \`cat \${tempfile}volume\`
rm -f \${tempfile}volume >> /dev/null

# command-line arguments (2 of 2)
foreach arg ( \$* )
    if("\$arg" =~ [PpCcIiFfRrHh][1-6]*) set SG = \`echo \$arg | nawk '{print toupper(\$0)}'\`
    if(("\$arg" =~ [0-9]*)&&("\$arg" !~ [a-z,A-Z]*)) then
	# a pure number is on the command line
	if("\$arg" =~ *.*) then
	    # take it as resolution
	    set RES = \`echo \$arg | nawk '\$1+0>0.5 && \$1+0<10{print \$1+0}'\`
	else
	    # take it as ASU size
	    set ASU = \`echo \$arg | nawk '{printf "%d", \$1+0}'\`
	endif
    endif
    if("\$arg" =~ [0-9]*A) then
	# looks like a resolution
	set temp = \`echo \$arg | nawk '\$1+0>0.5 && \$1+0<10{print \$1+0}'\`
	if(\$#temp) set RES = "\$temp"
    endif
end


if("\$RES" != "") then
    echo " to \${RES}A"
else
    echo ""
    set RES = "\$mtzRES"
endif

# extract protein-compatible space groups from CCP4 in order of increasing symmetry
#nawk '\$5 ~ /^PG/ && ! /m/ && ! /bar/ && \$1 < 500' \$CLIBD/symop.lib >! \$tempfile
cat \${CLIBD}/symop.lib |\\
nawk '\$5 ~ /^PG/ && ! /m/ && ! /bar/ && \$1 < 500{\\
	printf "%s ", \$0; for(op=\$2;op>0;--op){getline;printf \$1 \$2};print ""}' |\\
nawk '{print length(\$NF), \$0}' |\\
sort -n |\\
nawk '{print \$2,\$3,\$4,\$5,\$6,\$7}' >! \$tempfile


# get crystal system of \$SG
set sys = \`nawk -v SG=\$SG '\$4==SG{print \$6}' \$tempfile\`
set latt = \`echo \$SG | nawk '{print substr(\$1,1,1)}'\`

# extract point group representatives
nawk 'substr(\$4,2)==substr(\$5,3)' \$tempfile >! \${tempfile}PGs
# extract point group representatives of the same lattice type
#nawk -v latt=\$latt 'substr(\$4,1,1)==latt && substr(\$4,2)==substr(\$5,3)' \$tempfile >! \${tempfile}PGs
nawk -v latt=\$latt 'substr(\$4,1,1)==latt && ! seen[substr(\$5,3)]{print;++seen[substr(\$5,3)]}' \$tempfile >! \${tempfile}PGs


# now get all point groups that co-index with \$SG
if(("\$sys" == "TRIGONAL") || ("\$sys" == "HEXAGONAL")) then
    set SGs =  \`nawk '\$6 ~ /TRIG/{print \$4} \$6 ~ /HEXA/{print \$4}' \${tempfile}PGs\`
else
    set SGs =  \`nawk -v S=\$sys '\$6==S{print \$4}' \${tempfile}PGs\`
endif
rm -f \$tempfile \${tempfile}PGs

echo "SG      ASU(A^3)  ASU(~kD) Rmerge(%)   Brightest systematic absence"

SGcheck:

# add any extra considerations
set SGs = ( \$SGs )
if("\$SGs " !~ "P1 "*) set SGs = "P1 \$SGs"

foreach SG ( \$SGs )

    # get size of ASU (in A^3)
    set temp = \`nawk -v SG=\$SG '\$4==SG && \$1 < 500{print \$2}' \$CLIBD/symop.lib\`
    set temp = \`echo "\$CELLvolume \$temp" | nawk '\$2+0!=0{print \$1/\$2}'\`
    if("\$temp" != "") set volume = "\$temp"

    # indicate P1 merge after P1_scales_SG scaling
    set printSG = "\$SG"
    if("\$P1_scales_SG" != "" && "\$SG" == "P1" && "\$P1_scales_SG" != "P1") then
	set SG = \$P1_scales_SG
	set printSG = "\${SG}-P1"
    endif
    
    # print it out in A^3 and kD at Vm=2.5
    echo "\$printSG" | nawk '{printf "%-7s", \$0}'
    echo "\$volume" | nawk '{printf "%9d  %3d      ", \$0, \$0/2500}'   
    
    # remove bum log files
    if(-e \${logfile}.\${printSG}.log) then
	grep Overall: \${logfile}.\${printSG}.log >& /dev/null
	if((\$status)||(\$?IGNORE)) rm -f \${logfile}.\${printSG}.log
    endif
    
    # set up reindexing procedure
    set REINDEX = ""
    set new_SG  = "\$SG"
    # check for "pseudo-spacegroups"
    set temp = \`echo \$SG | nawk '{print toupper(\$1)}'\`
    if("\$temp" =~ [PC]2[12][12]*) then
	set axes = ""
	if("\$temp" == P2221) then
	    # P2221 with screw along longest axis
	    set axes  = "a b c"
	    set new_SG = "P2221"
	endif
	if("\$temp" == P2212) then
	    # P2221 with screw along mid-length axis
	    set axes  = "b c a"
	    set new_SG = "P2221"
	endif
	if("\$temp" == P2122) then
	    # P2221 with screw along shortest axis
	    set axes  = "c a b"
	    set new_SG = "P2221"
	endif
	
	if("\$temp" == P21212) then
	    # P21212 with non-screw along longest axis
	    set axes  = "a b c"
	    set new_SG = "P21212"
	endif
	if("\$temp" == P21221) then
	    # P21212 with non-screw along mid-length axis
	    set axes  = "b c a"
	    set new_SG = "P21212"
	endif
	if("\$temp" == P22121) then
	    # P21212 with non-screw along shotest axis
	    set axes  = "c a b"
	    set new_SG = "P21212"
	endif
	    
	# cannonize these
	if("\$new_SG" == "P222")    set axes = "a b c"
	if("\$new_SG" == "P212121") set axes = "a b c"
	
	# decide on new axis ordering (for asymmetric orthorhombics)
	if("\$axes" != "") then
	    # get current axis ordering
	    # find out what the cannonical one would be
	    # then decide how to go from current ordering to the desired one
	    echo "\$CELL" | nawk '{\\
		# print out current axis order \\
		print \$1, "h"; print \$2, "k"; print \$3, "l"}' |\\
	    sort -n |\\
	    nawk '\\
		# add cannonical axis names\\
		NR==1{print \$0, "a"} NR==2{print \$0, "b"} NR==3{print \$0, "c"}' |\\
	    nawk -v axes="\$axes" 'BEGIN{split(axes, abc)} {\\
		# write desired axis ordering in front of cannonical one \\
		print abc[NR], \$0}' |\\
	    sort |\\
	    cat >! \${tempfile}order    
	    set REINDEX = "reindex "\`nawk '{printf "%s", \$3} NR~/[12]/{print ","}'  \${tempfile}order\`
	
	    # this should give us a mapping between any two orthorhombics
	endif
    endif
    if("\$new_SG" =~ R*) set new_SG = \$SGnum
    if("\$new_SG" =~ H*) set new_SG = \$SGnum


    # only run mergeing step if we havn't already done so
    if((! -e \${logfile}.\${printSG}.log)||(\$?IGNORE)) then
	echo -n "" >! \${logfile}.\${printSG}.log

	# apply the resolution cutoff
	echo "RESOLUTION \$RES" |\\
	mtzutils hklin1 \$rawfile hklout \${tempfile}.cut.mtz >>& \${logfile}.\${printSG}.log
	
	# now re-index the input, raw mtz file
	reindex HKLIN \${tempfile}.cut.mtz \\
		HKLOUT \${tempfile}.reindexed.mtz << end_reindex >>& \${logfile}.\${printSG}.log
SYMMETRY \$new_SG
\$REINDEX
END
end_reindex
	rm -f \${tempfile}.cut.mtz >& /dev/null
	
	# make sure it's sorted
	sortmtz hklout \${tempfile}.\${SG}.mtz  << end_sort >>& \${logfile}.\${printSG}.log
	${VRSET}VRSET -9e+38
	H K L M/ISYM BATCH I SIGI
	\${tempfile}.reindexed.mtz
end_sort
	rm -f \${tempfile}.reindexed.mtz >& /dev/null
 	
	# run the merge script
	if("\$printSG" !~ *-P1) then
	    ./\$script \${tempfile}.\${SG}.mtz >>& \${logfile}.\${printSG}.log
	else
	    # rewrite the script to scale with one SG and merge in P1
	    cat \$script |\\
	    nawk '{print} tolower(\$1)~/^cycle/{print "DUMP '\${tempfile}'_scales.txt"}' |\\
	    cat >! \${tempfile}_scale.com
            cat \$script |\\
            nawk '{print} tolower(\$1)~/^cycle/{print "RESTORE '\${tempfile}'_scales.txt";print "ONLYMERGE"}' |\\
            cat >! \${tempfile}_merge.com
	    chmod a+x \${tempfile}_scale.com \${tempfile}_merge.com
 	    \${tempfile}_scale.com \${tempfile}.\${SG}.mtz >>& \${logfile}.\${printSG}.log
	    # now merge in P1
	    echo "SYMM P1" |\\
	    reindex hklin \${tempfile}.\${SG}.mtz \\
		 hklout \${tempfile}.\${printSG}.mtz >>& \${logfile}.\${printSG}.log
	    \${tempfile}_merge.com \${tempfile}.\${printSG}.mtz >>& \${logfile}.\${printSG}.log

#	    rm -f \${tempfile}_scale.com \${tempfile}_merge.com >& /dev/null
#	    rm -f \${tempfile}.scales.txt >& /dev/null
#	    rm -f \${tempfile}.\${printSG}.mtz >& /dev/null
	endif
	
	# see if truncate was run
	grep "SUITE: TRUNCATE" \${logfile}.\${printSG}.log >& /dev/null
	if(\$status) then
	    # truncate was not run, so lets try to run it
	    set mergedmtz = \`nawk '/Filename:/{mtz=\$NF} /Scala/&&/termination/{print mtz}' \${logfile}.\${printSG}.log\`
	    set ASU = \`echo "\$volume" | nawk '{print \$0/2500}'\`
	    if((-e "\$mergedmtz")&&("\$ASU" != "")) then
		echo "nresidue \$ASU" |\\
		truncate hklin \$mergedmtz hklout \${tempfile}.mtz >>& \${logfile}.\${printSG}.log
	    	if(\$status) then
		    # truncate failed, try it again? 
		endif
	    endif
	endif
	
	# clean up
	rm -f \${tempfile}.\${SG}.mtz >& /dev/null
    endif
    
    # print out Rmerge
    set Rmerge = \`nawk '/ Overall: /{print \$2}' logs/merge.\${printSG}.log | tail -1\`
    if("\$Rmerge" == "0.000") then
	# use "Ranom" instead?
	set Rmerge = \`nawk '/ Overall: /{print \$5}' logs/merge.\${printSG}.log | tail -1\`
    endif
    if("\$Rmerge" == "") then
	echo "-"
    else
	# print out Rmerge
	echo \$Rmerge | nawk '{printf "%5.1f        ", \$1*100}'
    
	# Look for Systematic absence intensities
	cat  logs/merge.\${printSG}.log |\\
	nawk '/Systematic absences are OMITTED/,/Distributions/' |\\
	nawk 'NF==5 && ! /[a-z]/ && \$5 != 0{printf "%-4d%-4d%-4d I/sig = %8.3f\\n", \$1, \$2, \$3, \$4/\$5}' |\\
	sort +5n >! \$tempfile
	set Absence = \`tail -1 \$tempfile\`
	if("\$Absence" != "") then
	    # print out the worst one
	    tail -1 \$tempfile | nawk '{printf "%s", \$0}'
	endif
	rm -f \$tempfile
    
	echo ""
    endif
end

# now, pick the best point/space group

# gather stats from last round of runs

if(\$?saved_SGs) then
    set SGs = ( \$saved_SGs )
    unset saved_SGs
endif
echo "" >! \$tempfile
foreach SG ( \$SGs )
    # indicates P1 merge after P1_scales_SG scaling
    set printSG = "\$SG"
    if("\$P1_scales_SG" != "" && "\$SG" == "P1" && "\$P1_scales_SG" != "P1") then
	set printSG = "\${P1_scales_SG}-P1"
    endif
    
    set Rmerge = \`nawk '/ Overall: /{print \$2}' logs/merge.\${printSG}.log | tail -1\`
    if("\$Rmerge" == "0.000") then
	# use "Ranom" instead?
	set Rmerge = \`nawk '/ Overall: /{print \$5}' logs/merge.\${printSG}.log | tail -1\`
    endif
    if("\$Rmerge" != "") then
	echo -n "\$SG " >> \$tempfile
	echo -n "\$Rmerge " >> \$tempfile
	cat  logs/merge.\${printSG}.log |\\
	nawk '/Systematic absences are OMITTED/,/Distributions/' |\\
	nawk 'NF==5 && ! /[a-z]/ && \$5 != 0{print \$4/\$5}' |\\
	sort -n | tail -1 >! \$tempfile.absent
	set Absence = \`tail -1 \$tempfile.absent\`
	echo "\$Absence" >> \$tempfile
    endif
end
rm -f \$tempfile.absent >& /dev/null

# do some statistics
set best_SG     = \`sort -n +1 \$tempfile | nawk 'NF==2' | head -1 | nawk '\$2+0>0.0{print \$1}'\`
set P1_Rmerge   = \`nawk '\$1=="P1"{print \$2}' \$tempfile\`
set min_Rmerge  = \`sort -n +1 \$tempfile | nawk 'NF==2' | head -1 | nawk '\$2+0>0.0{print \$2}'\`
set max_Rmerge  = \`sort -nr +1 \$tempfile | nawk 'NF==2' | head -1 | nawk '\$2+0>0.0{print \$2}'\`
set mean_Rmerge = \`nawk '\$2+0>0{sum += \$2;++count} END{if(count) print sum/count}' \$tempfile\`
set rmsd_Rmerge = \`nawk -v avg=\$mean_Rmerge '\$2+0>0{sum+=(\$2-avg)^2;++count} END{if(count) print sqrt(sum/count)}' \$tempfile\`

# do we already have a "best" SG for obtaining the P1 baseline?
if("\$P1_scales_SG" == "" && "\$best_SG" != "P1" && "\$best_SG" != "") then
    # probably always a good idea to try and use P1_scales_SGs scales, but merge with P1
    set P1_scales_SG = "\$best_SG"
    set saved_SGs = ( \$SGs )
    set SGs = P1
    echo "scaling with \$P1_scales_SG to merge in P1"
    goto SGcheck
endif

set Rmerge_cutoff = ""

# see if P1 run worked
if("\$P1_Rmerge" != "") then
    # P1 run succeeded, so "no symmetry" hypothesis has been considered
    if("\$best_SG" == "P1") then
	# P1 had a lower Rmerge than anything else
	set Rmerge_cutoff = \`echo \$min_Rmerge 0.1 | nawk '{print \$1+1.0*\$2}'\`
    else
	# P1 worked, but it was not the best score
	set Rmerge_cutoff = \`echo \$min_Rmerge 0.1 | nawk '{print \$1+1.0*\$2}'\`
    endif
else
    # P1 run failed, but we gotta have it
    # what do we do?
    set Rmerge_cutoff = 0.2
endif

set test = \`echo \$Rmerge_cutoff 0.5 | nawk 'NF==2{print (\$1 > \$2)}'\`
if("\$test" == "1") set Rmerge_cutoff = 0.5

# filter for SGs below the mergeing criteria
set SGs = \`nawk -v max=\$Rmerge_cutoff '\$2+0 < max && \$3+0 < 4 {print \$1}' \$tempfile\`


if("\$SGs" == "") then
    echo "WARNING: none of these space groups merged well."
    if("\$P1_Rmerge" == "") echo "not even P1"
    echo "         try to tune up \$script next time."
    exit 9
endif

# if \$?PG, we have been here before
if(\$?PG) then
    if(\$#SGs == 1) then
	echo "Possible space group is: \$SGs"
    else
	echo "Possible space groups are: \$SGs"
    endif
#    echo "\$SGs" >! SGs.txt
    rm -f \$tempfile
    exit
endif
    
# extract protein-compatible space groups from CCP4 in order of increasing symmetry
#nawk '\$5 ~ /^PG/ && ! /m/ && ! /bar/ && \$1 < 500' \$CLIBD/symop.lib >! \$tempfile
cat \${CLIBD}/symop.lib |\\
nawk '\$5 ~ /^PG/ && ! /m/ && ! /bar/ && \$1 < 500{\\
        printf "%s ", \$0; for(op=\$2;op>0;--op){getline;printf \$1 \$2};print ""}' |\\
nawk '{print length(\$NF), \$0}' |\\
sort -n |\\
nawk '{print \$2,\$3,\$4,\$5,\$6,\$7}' >! \$tempfile


# pursue all potential possibilites (but there should really only be one)
set temp = ""
echo "checking for screw axes in \$SGs"
foreach SG ( \$SGs )

    # get point group of \$SG
    set PG = \`nawk -v SG=\$SG '\$4==SG{print \$5}' \$tempfile\`
    set latt = \`echo \$SG | nawk '{print substr(\$1,1,1)}'\`
    
    # now get all space groups in \$PG on \$latt
    set temp =  "\$temp "\`nawk -v PG=\$PG -v latt=\$latt '\$5==PG && substr(\$4,1,1)==latt{print \$4}' \$tempfile\`

    # add pseudo-SGs for asymmetric orthorhombics
    if("\$PG" == "PG222") then
	set pseudoSGs = ""
	foreach sg ( \$temp )
	    set pseudoSGs = "\$pseudoSGs \$sg"
	    if("\$sg" == "P2221") set  set pseudoSGs = "\$pseudoSGs P2212 P2122"
	    if("\$sg" == "P21212") set  set pseudoSGs = "\$pseudoSGs P21221 P22121"
	end
	set temp = "\$pseudoSGs"
    endif
end
rm -f \$tempfile

set SGs = \`echo \$temp\`

# check each of these

goto SGcheck


exit

EOF-search
chmod a+x SGsearch.com 









# write out a convenient mtz2various script
cat << EOF-mtz2various >! mtz2various.com
#! /bin/csh -f
#
#	general script for converting mtz to another format
#
##############################################################################
# set up awk
alias nawk $nawk
nawk 'BEGIN{print 1; exit}' >& /dev/null
if(\$status) alias nawk awk

# defaults
set mtzfile  = $mergefile
set tempfile = mtz2various_temp

# output F, phase, etc. (automatic by default)
set hiRES    = ""
set F        = Fin
set SIGF     = SIGFin
set DANO     = ""
set SIGD     = ""
set PHI      = PHIDM
set FOM      = FOMDM
set FREE     = FreeR_flag

# output files
set outfile   = outfile.cif
# supported: xplor cns tnt cif shelx fin phs
set format    = "CIF"

if("\$1" == "") goto Help
goto Setup
#  Procedure (at bottom) to read command-line args
#  mtz, Fs, or resolution
Help:
cat << EOF

usage: \$0 mtzfile.mtz [F] [PHI] outfile.fmt

where:
mtzfile.mtz  - an mtz file you want to convert
[F] [PHI]    - are the dataset names in mtzfile.mtz you want to extract
outfile.fmt  - is the output file name
fmt          - implies format:
		cif -> CIF
		hkl -> shelx
		tnt -> TNT
		fin -> XtalView
		phs -> XtalView
		fobs-> XPLOR
		cv  -> XPLOR
		cns -> CNS

EOF
exit 9
ReturnFromSetup:

# construct a LABIN card for the dump
set label = ""
if("\$F" != "")    set label = "\$label FP=\$F"
if("\$SIGF" != "") set label = "\$label SIGFP=\$SIGF"
if("\$DANO" != "") set label = "\$label DP=\$DANO"
if("\$SIGD" != "") set label = "\$label SIGDP=\$SIGD"
if("\$PHI" != "")  set label = "\$label PHIB=\$PHI"
if("\$FOM" != "")  set label = "\$label FOM=\$FOM"
if("\$FREE" != "") set label = "\$label FREE=\$FREE"

################################################################################
# extract columns of interest
mtz2various HKLIN \$mtzfile HKLOUT \${tempfile}.hkl << EOF-dump 
#>> /dev/null
RESOLUTION 1000 \$hiRES
OUTPUT \$format
LABIN \$label
END
EOF-dump
if(\$status) exit

if("\$format" == "TNT") then
    if("\$FREE" != "") then
	# extract FREE-R set
	cat \${tempfile}.hkl |\\
	nawk '\$NF=="FREE"{print substr(\$0,1,index(\$0,"FREE")-1)}' |\\
	sort +1n -2 +2n -3 +3n -4 |\\
	cat >! \${outfile}.free
    endif
    # make sure the output is properly sorted
    cat \${tempfile}.hkl |\\
    nawk '\$NF!="FREE"{print}' |\\
    sort +1n -2 +2n -3 +3n -4 |\\
    cat >! \${outfile}

    echo "TNT version of \$F \$SIGF \$PHI \$FOM in \$mtzfile is now in:"
    echo "\$outfile"
    echo "\${outfile}.free contains the Free-R flagged HKLs"
    rm -f \${tempfile}.hkl >& /dev/null
    exit
endif

# check for supported/unsupported output
if("\$format" != 'USER *') then
    # use whatever mtz2various did
    mv \${tempfile}.hkl \$outfile

    echo "\$format version of \$F \$SIGF \$DANO \$SIGD \$PHI \$FOM from \$mtzfile is at:"
    echo "\$outfile"
    exit
endif

# must have been an unsupported format (fin, phs)
if(("\$ext" == "fin")||("\$ext" == "phs")) then
    echo "name" >! \${outfile}.CRYSTAL
    echo "cell \$CELL" >> \${outfile}.CRYSTAL
    cat \${CLIBD}/symop.lib |\\
    nawk -v SG=\$SG '\$4==SG{print "spgr", tolower(\$4), \$1, \$2, \$3, tolower(\$6);\\
	getline; getline; printf "symm x,y,z"; \\
	while(NF==1){printf "; %s", tolower(\$1); getline};\\
	print "."; exit}' |\\
    cat >> \${outfile}.CRYSTAL
endif

if("\$ext" == "phs") then
    # XtalView phs file
    # should have been output as H K L F PHI FOM
    cat \${tempfile}.hkl |\\
    nawk '{printf "%4d %4d %4d %12.4f %7.4f %7.2f\\n", \$1, \$2, \$3, \$4, \$6, \$5}' |\\
    cat >! \$outfile

    echo "XtalView version of \$F \$PHI \$FOM from \$mtzfile is at:"
    echo "\$outfile"
    echo "\${outfile}.CRYSTAL"
    rm -f \${tempfile}.hkl >& /dev/null
    exit
endif


if("\$ext" == "fin") then
    # XtalView fin file
    # should have been output as H K L F SIGF D SIGD
    cat \${tempfile}.hkl |\\
    nawk 'NF>=7{F1=\$4+(\$6/2); F2=\$4-(\$6/2); SIG1=SIG2=\$5*1.4142;}\\
	  NF<7 || \$NF+0==0{F1=\$4; SIG1=\$5; F2=0; SIG2=9999}\\
	  NF>3{printf "%4d %4d %4d %12.4f %12.4f %12.4f %12.4f\\n", \$1, \$2, \$3, F1, SIG1, F2, SIG2}' |\\
    cat >! \$outfile

    echo "XtalView version of \$F \$SIGF \$DANO \$SIGD from \$mtzfile is at:"
    echo "\$outfile"
    echo "\${outfile}.CRYSTAL"
    rm -f \${tempfile}.hkl >& /dev/null
    exit
endif


####################################################################
exit
####################################################################



Setup:
# scan the command line for files
foreach arg ( \$* )
    if( "\$arg" =~ *.mtz ) then
	if(! -e "\$arg") then
	    echo "WARNING: \$arg does not exist! "
	    continue
	endif
	set mtzfile  = "\$arg"
	continue
    endif
    if("\$arg" =~ *.cif) then
        set outfile  = "\$arg"
        set format   = "CIF data_\$arg"
        continue
    endif
    if("\$arg" =~ *.hkl) then
	set outfile  = "\$arg"
	set format   = "SHELX"
	continue
    endif
    if("\$arg" =~ *.tnt) then
        set outfile  = "\$arg"
        set format   = "TNT"
        continue
    endif
    if("\$arg" =~ *.cns) then
        set outfile  = "\$arg"
        set format   = "CNS"
        continue
    endif
    if(("\$arg" =~ *.fobs)||("\$arg" =~ *.cv)) then
	set outfile  = "\$arg"
	set format   = "XPLOR"
	continue
    endif
    if("\$arg" =~ *.fin) then
        set outfile  = "\$arg"
        set format   = 'FIN'
        continue
    endif
    if("\$arg" =~ *.phs) then
        set outfile  = "\$arg"
        set format   = 'PHS'
        continue
    endif
    if( "\$arg" =~ [0-9]* ) then
	set temp = \`echo "\$arg" | nawk '\$1+0>0.1{print \$1+0}'\`
	if("\$temp" != "") set hiRES = "\$temp"
    endif
end

#get variables from mtz file
echo "go" | mtzdump hklin \$mtzfile | tee \${tempfile}mtzhead |\\
nawk '/OVERALL FILE STATISTICS/,/No. of reflections used/' |\\
nawk 'NF>10 && \$(NF-1) ~ /[FQPWADI]/' |\\
cat >! \${tempfile}mtzdmp

# set misc header values
set CELL = \`nawk '/Cell Dimensions/{getline; getline; print}' \${tempfile}mtzhead\`
set SG   = \`nawk '/Space group/{gsub("\\047","");print \$5}' \${tempfile}mtzhead\`
set SGnum = \` nawk '/Space group/{print \$NF+0}' \${tempfile}mtzhead \`
set SG = \` nawk -F "[\\047]" '/Space group/{print \$2}' \${tempfile}mtzhead \`
set SG = \` nawk -v num=\$SGnum '\$1==num && NF>5{print \$4}' \${CLIBD}/symop.lib \`
set mtzRES = \`nawk '/Resolution Range/{getline;getline;print \$6}' \${tempfile}mtzhead\`
rm -f \${tempfile}mtzhead >& /dev/null

# use completeness, or F/sigF to pick default F
cat \${tempfile}mtzdmp |\\
nawk '\$(NF-1) == "F"{F=\$NF; meanF=\$8; reso=\$(NF-2); comp=substr(\$0,32)+0; \\
      getline; S=\$NF; if(\$8) meanF /= \$8; print F, S, reso, comp, meanF;}' |\\
sort +2n -3 +3nr -4 +4nr >! \${tempfile}F

# same for D/sigD for anomalous diffs
cat \${tempfile}mtzdmp |\\
nawk '\$(NF-1) == "D"{D=\$NF; meanD=\$8; reso=\$(NF-2); comp=substr(\$0,32)+0; \\
      getline; S=\$NF; if(\$8) meanD /= \$8; print D, S, reso, comp, meanD;}' |\\
sort +2n -3 +3nr -4 +4nr >! \${tempfile}D


# and extract all dataset types/labels
cat \${tempfile}mtzdmp |\\
nawk 'NF>2{print \$(NF-1), \$NF, " "}' |\\
cat >! \${tempfile}cards

#clean up
rm -f \${tempfile}mtzdmp

# pick F with best resolution, or <F>/<sigma(F)>
set F    = \`head -1 \${tempfile}F\`
if(\$#F > 2) then
    set SIGF = \$F[2]
    set F    = \$F[1]
endif

# see if default phase is available in this file
grep "P \$PHI" \${tempfile}cards >& /dev/null
if(\$status) then
    # pick most recently-added phase
    set temp = \`nawk '/^P/{print \$2}' \${tempfile}cards  | tail -1\`
    if("\$temp" != "") set PHI = "\$temp"
endif
# see if default FOM is available in this file
grep "W \$FOM" \${tempfile}cards >& /dev/null
if(\$status) then
    # pick most recently-added FOM
    set temp = \`nawk '/^W/{print \$2}' \${tempfile}cards | tail -1\`
    if("\$temp" != "") then
	set FOM = "\$temp"
    else
	# there are no FOMs in this mtz file
	set FOM = ""
    endif
endif

# see if user specified an F, Phase, or FOM
set last = "F"
foreach arg ( \$* )
    set temp = \`grep " \$arg " \${tempfile}cards\`
    if("\$temp" =~ F*) then
	set F = "\${arg}"
	set last = "F"
	# assign most likely sigma too
	set temp = \`nawk -v arg="\$arg" '\$1==arg{print \$2}' \${tempfile}F\`
	if(\$#temp == 1) set SIGF = "\$temp"
	continue
    endif
    if("\$temp" =~ D*) then
        set DANO = "\${arg}"
	set last = "D"
        # assign most likely sigma too
        set temp = \`nawk -v arg="\$arg" '\$1==arg{print \$2}' \${tempfile}D\`
        if(\$#temp == 1) set SIGD = "\$temp"
        continue
    endif
    if("\$temp" =~ Q*) then
	if("\$last" == "F") set SIGF = "\${arg}"
	if("\$last" == "D") set SIGD = "\${arg}"
    endif
    if("\$temp" =~ P*) set PHI  = "\${arg}"
    if("\$temp" =~ W*) set FOM  = "\${arg}"


    # detect particular out-of-context format specifiers
    set arg = \`echo "\$arg" | nawk '{print tolower(\$1)}'\`
    if("\$arg" == "shelx") set format = SHELX
    if("\$arg" == "tnt")   set format = TNT
    if("\$arg" == "cif")   set format = CIF
    if("\$arg" == "xplor") set format = XPLOR
    if("\$arg" == "cns")   set format = CNS
    if("\$arg" == "xtalview") then
        if("\$PHI" == "") then
            set format = "FIN"
        else
            set format = "PHS"
        endif
    endif
end

# check for DANO, if we might need one
if(("\$format" == "FIN")&&("\$DANO" == "")) then
    # grab pattern from name
    set temp = \`echo \$F | nawk '{print substr(\$1,2)}'\`
    set DANO = \`nawk -v patt=\$temp '\$1~ patt"\$" {print \$1; exit}' \${tempfile}D\`
    # get likely sigma too
    set SIGD = \`nawk -v arg="\$DANO" '\$1==arg{print \$2}' \${tempfile}D\`
endif

# now check and see if the sigma is really there
grep "Q \$SIGF" \${tempfile}cards >& /dev/null
if(\$status) then
    # no sigma availale
    set SIGF = ""
endif
grep "Q \$SIGD" \${tempfile}cards >& /dev/null
if(\$status) then
    # no sigma availale 
    set SIGD = ""
endif
grep "P \$PHI" \${tempfile}cards >& /dev/null
if(\$status) then
    # no phase availale
    set PHI = ""
endif
grep "W \$FOM" \${tempfile}cards >& /dev/null
if(\$status) then
    # no weight availale
    set FOM = ""
endif
grep " \$FREE" \${tempfile}cards >& /dev/null
if(\$status) then
    # no weight availale
    set FREE = ""
endif


rm -f \${tempfile}cards \${tempfile}F \${tempfile}D >& /dev/null

# set resolution (if none previously given)
if("\$hiRES" == "") set hiRES = "\$mtzRES"

# store filename extension/format
set ext = \`echo \$outfile | nawk 'BEGIN{FS="."} {print \$NF}'\`
if("\$format" == "CIF") then
    # needs an extra word
    set format = "CIF data_dump"
endif
if("\$format" == "FIN") then
    # not supported by mtz2various
    set format = 'USER *'
    set ext = fin
    set PHI = ""
    set FOM = ""
    set FREE = ""
endif
if("\$format" == "PHS") then
    # not supported by mtz2various
    set format = 'USER *'
    set ext = phs
    set SIGF = ""
    set DANO = ""
    set SIGD = ""
    set FREE = ""
endif

goto ReturnFromSetup

####################
# future:
better handling of shelx
multiple datasets/mtzs?

EOF-mtz2various
chmod a+x mtz2various.com










goto Return_Unwrap_Scale_Scripts





DumpSymopLib:
###########################################################################

  ####    #   #  #    #   ####   #####           #          #    #####
 #         # #   ##  ##  #    #  #    #          #          #    #    #
  ####      #    # ## #  #    #  #    #          #          #    #####
      #     #    #    #  #    #  #####    ###    #          #    #    #
 #    #     #    #    #  #    #  #        ###    #          #    #    #
  ####      #    #    #   ####   #        ###    ######     #    #####

###########################################################################
#
#   a copy of the CCP4 symop library (so mosflm can barely function)
#
###########################################################################
cat << EOF-symoplib >! ${CLIBD}/symop.lib
1 1 1 P1 PG1 TRICLINIC
 X,Y,Z
2 2 2 P-1 PG1bar TRICLINIC
 X,Y,Z
 -X,-Y,-Z
3 2 2 P2 PG2 MONOCLINIC
 X,Y,Z
 -X,Y,-Z
1003 2 2 P2 PG2 MONOCLINIC (dyad along z)
 X,Y,Z
 -X,-Y,Z
4 2 2 P21 PG2 MONOCLINIC
 X,Y,Z
 -X,Y+1/2,-Z
3004 2 1 I21 PG2
 X,Y,Z * -X,1/2+Y,-Z
 X+1/2,Y+1/2,Z+1/2 * -X+1/2,Y,1/2-Z
1004 1 1 P1121 PG2
 X,Y,Z * -X,-Y,1/2+Z
2005 2 1 A2 PG2 ! (Origin on screw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+Z,3/4-Y
 3/4-Z,1/4-Y,1/4+X
 1/4-Z,1/4+Y,3/4-X
 1/4+Z,3/4-Y,1/4-X
 3/4+Z,3/4+Y,3/4+X
EOF-symoplib


cat << EOF-environ >! ${CINCL}/environ.def
# minimized environ.def
#
ABCOEFFS=inout.coeff            # Optional Fourier terms (fft)
ABSIN=in.dat                    # absorption data (absurd)
BADSPOT=inout.spt               # mosflm
CROSSECDATA=in.lib              # crossec
GENFILE=inout.gen               # abscale, oscgen (mosflm distrib)
HKLIN=in.mtz                    # general reflexion i/p file
HKLOUT=out.mtz                  # general reflexion o/p file
PMOSFLMDAT=in.dat               # mosflm
PROFILE=inout.prf               # mosflm
SYMOP=in.lib                    # symlib
SPOTOD=inout.od                 # mosflm
SUMMARY=out.sum                 # mosflm

EOF-environ


cat << EOF-default >! ${CINCL}/default.def
# minimized default.def

ABCOEFFS=fftkw.abcoeffs         # fft
ATS=ATS.scr
BADSPOT=badspot.scr             # mosflm
CROSSECDATA=crossec.lib         # crossec
DISKIO1=IO1.scr
DISKIO2=IO2.scr
HISTLIB=hist.lib                # dm
FFTHKLSCR=IO4.scr               # fft, sfall
SD1=SD1.scr                     # ?
SD2=SD2.scr                     # ?
SYMOP=symop.lib                 # symlib
TEMP=temp.scr

EOF-default

goto ReturnFrom_DumpSymopLib


#########################################################################################
The Future:

TODO:
"alternative" beam center list?
de-novo beam centering
support external spot list
update merge.com reindexing
install ginger
don't "refine" two_theta angle from TILT?

MAYBE:
separate refine.com and integ.com scripts?
preemtive spot pick for autoindexing?
do "next wedge" question at end.
true postrefinement (after scaling)


