#! /bin/csh -f
#
#  $Author: mast $
#
#  $Date: 2006/06/08 19:03:59 $
#
#  $Revision: 3eec683f6046 $
#
#  $Log$
#  Revision 3.3  2005/11/19 04:31:26  mast
#  Quote path setting to preserve spaces
#
#  Revision 3.2  2004/06/29 03:54:37  mast
#  Fixed path-setting
#
#  Revision 3.1  2003/11/13 19:49:32  mast
#  Inserted -f flags on csh invocations
#
#
set FILTERPARAMS=".01,.05,0,.1"
#
# If no argument, print usage
#
if ($#argv < 1) then 
  echo "Usage: setuplong image_name.ext [X and Y size of average (default 168 by 168)]"
  exit 0
endif
if ($?IMOD_DIR) then
    setenv PATH "$IMOD_DIR/bin:$PATH"
endif
#
# GET BASE NAME = BN
#
set BN = $argv[1]:r
#
# count lines in point file to get numsec
#
set wcout = `wc -l $BN.pt`
@ NUMSEC = $wcout[1]
set IXAVG = "168"
set IYAVG = "168"
if ($#argv > 1) then
  set IXAVG = $argv[2]
endif
if ($#argv > 2) then
  set IYAVG = $argv[3]
endif
#
# create _1.com file
#
set com1 = ${BN}_1.com
set comm = ${BN}_m.com
#
#
cat >! $com1 <<EOCAT
#! /bin/csh -f
set IFBILINEAR = \$argv[1]
cat >! filesectlist <<ENDOFDATA
$BN.avge
0
$BN.exce
EOCAT
#
@ NUM = 0
while ($NUM < $NUMSEC)
  echo $NUM >> $com1
  @ NUM++
end
#
# append master xfalign file
#
cat  >> $com1 << EOTEMPLATE
ENDOFDATA
#
# THIS IS A SPECIAL VERSION OF xfalign TO ALIGN ALL SECTIONS IN A
# STACK TO A SINGLE SECTION IN ANOTHER STACK
# Above HERE, the first line should have the name of the reference image
# file containing the section to which all others will be aligned
# The second line should have the section number in that image file
# On the 3rd and following lines, put either the stack name then the
# successive section numbers (one per line), or a zero (0) on the first
# line and the successive file names, one per line.
# DO NOT CHANGE THE "ENDOFDATA" LINE! ! !
#
# Sections will be extracted one by one from the input stack using NEWSTACK
# NEWSIZE, NEWMODE, and NEWCEN control image extraction as follows:
#
# set NEWSIZE to a new x and y image size (e.g. "x,y") or leave as "/" for
# same size as input
set NEWSIZE = "/"
#
# set NEWMODE to a new data mode, or leave as "/" for same mode as input
set NEWMODE = "/"
#
# set NEWCEN to a relative center offset if using a new image size
set NEWCEN = "0,0"
#
# Sections can then be prepared for alignment using the program ENHANCE
# Set FILTERPARAM to the "sigma1, sigma2, radius1, radius2" values required
# by ENHANCE (the same parameters used in VIEWFILT) or leave as "NONE" to
# omit filtering.  
set FILTERPARAM = "NONE"
#
# Set XFLISTFILE to the name of the file to receive the list of F transforms
set XFLISTFILE = "xflist.tmp"
#
# Now specify the parameters to XFSIMPLEX.  Default values are in []
# Set tolerances in difference/distance measure and in transformation
# parameters for terminating final minimization [.0005 and .02, or .001 and
# .04 for images no larger than 128 by 128], tolerances for terminating
# initial search, or 0,0 to have only the final search [.005 and .2],
# factor to apply to basic step sizes to get initial step size [2], and
# 1 or 2 for trace, or 0 for no trace [0]
set TOLERANCES = ",,,,,,"
#
# Set NPARAM to 0 search for the six formal transformation parameters, or set
# it to the number of semi-natural parameters to vary [0]
set NPARAM = "3"
#
# Set FRACMATT to the fraction of the image to ignore at each edge [0.05]
set FRACMATT = ","
#
# Set RANGEMEAN to 0 or 1 to float images to have same range or same mean,
# respectively [1]
set RANGEMEAN = ","
#
# Set NREDUCE to binning factor to reduce images by in x and y [1]
set NREDUCE = "1"
#
# set DIFFDIST to 0 to use the difference between images as a measure of the
# match between images, or 1 to use the sum of distances between points in the
# images with corresponding intensities. [0]
set DIFFDIST = "0"
#
# If you select the difference measure, you just need to set IFBILINEAR to 1
# to use bilinear interpolation to assess image fit, or 0 not to [0]
# set IFBILINEAR = "0"
#
# If instead you use the distance measure, there is no bilinear option, but
# you have 5 more parameters to select.
# Set NREDUNDANT to the distance in pixels to search from a "comparison point"
# to eliminate redundant points with similar densities.  [Default is 0 for
# images less than 240*180pixels after reduction by 2 (if any), 1 for images
# between 240*180 and 480*360, and, 2 for larger images]
set NREDUNDANT = ","
#
# Set RADIUS to the maximum distance in pixels to search from a comparison
# point for points in the other image with matching densities.  [Default is 4
# if images are reduced by 2, or 5 if they are not]
set RADIUS = ","
#
# Set MATCHDIFF to the maximum density difference constituting a match [0.05]
set MATCHDIFF = ","
#
# Set NPCRANGES to the # of ranges of densities to make comparisons with [2]
set NPCRANGES = ","
#
# Set PCRANGES to the lower and upper percentiles for those ranges.  [Default
# is 0,8,92,100 for images of 320*240 pixels or smaller (after reductions
# by 2, if any), and the ranges scale linearly down to 0,5,95,100 for images
# of 640*480 pixels or larger].
set PCRANGES = ",,,,"
#
#
# Here is the subroutine to prep a file.  You can add any desired functions
# here.  The image is in TMP.PIC upon entering the subroutine, and must be in
# TMP.PRP upon exiting from it.  You can put operations before and/or after
# the runenhance or replace the runenhance entirely.  To run a program that
# needs input other than from the command line, imitate the <<EOF style used
# below.
#
cat >! prepfile <<EOCAT
runenhance
EOCAT
# ----------------------------------------------------------------------
#                      YOU ARE DONE SETTING PARAMETERS
# ----------------------------------------------------------------------
set noglob
onintr clean
#
# set up the file to enhance or just rename tmp.pic
# 
if ( (\$FILTERPARAM  == "0.,0.,0.,0.")  ||  (\$FILTERPARAM == "NONE") ) then
   echo '\mv -f tmp.pic tmp.prp' >! runenhance
else
   cat >! runenhance <<EOCAT
enhance tmp.pic tmp.prp <<EOF
\$FILTERPARAM
1
EOF
EOCAT
endif
chmod +x runenhance prepfile
#
#     Initialize xflist file
#
echo -n >! \$XFLISTFILE
#
#      Set up file to run xfsimplex with the given parameters
#
cat >! runsearch <<EOCAT
xfsimplex <<EOF
tmpl.prp
tmp.prp
tmp.xf

\$TOLERANCES
\$NPARAM
\$FRACMATT
\$RANGEMEAN
\$NREDUCE
\$DIFFDIST
EOCAT
if (\$DIFFDIST == "0") then
cat >> runsearch <<EOCAT
\$IFBILINEAR
EOF
EOCAT
else
cat >> runsearch <<EOCAT
\$NREDUNDANT
\$RADIUS
\$MATCHDIFF
\$NPCRANGES
\$PCRANGES
EOF
EOCAT
endif
chmod +x runsearch
#
# 	Get the file and section list as a wordlist
#
set filesect = \`cat filesectlist\`
#
#	 SPECIAL: first line is stack name of reference
#
set nameorzero = \$filesect[1]
shift filesect
#
# 	next is section number
set fileorsect = \$filesect[1]
shift filesect
#
#	now get the section and prep it
#
#
newstack << EOF
1
\$nameorzero
\$fileorsect
1
tmp.pic
\$NEWSIZE
\$NEWMODE
1
\$NEWCEN
0
0
EOF
#
prepfile
#
#	 rename this prep'd file to "previous" prep file
\\mv -f tmp.prp tmpl.prp
#
#	 next line is either a stack name or 0 for separate files
#
set nameorzero = \$filesect[1]
shift filesect
#
while (\$#filesect != 0 )
#
set fileorsect = \$filesect[1]
shift filesect
#
set docopy = "0"
if (\$nameorzero != "0") then
set infile = \$nameorzero
set insect = \$fileorsect
else
set infile = \$fileorsect
set insect = "0"
if (\$NEWSIZE == "/" && \$NEWMODE == "/" && \$NEWCEN == "0,0") set docopy = "1"
endif
if (\$docopy == "1") then
cp \$infile tmp.pic
else
#
newstack << EOF
1
\$infile
\$insect
1
tmp.pic
\$NEWSIZE
\$NEWMODE
1
\$NEWCEN
0
0
EOF
#
# 	prep the file next with enhance or whatever
#
prepfile
#
#      Now do search for transform
#
runsearch
#
#      Add transform to file
#
cat tmp.xf >> \$XFLISTFILE
#
end
#
clean:
unset noglob
\\rm -f filesectlist prepfile runenhance runsearch
\\rm -f tmp.xf* tmp.pic* tmp.prp* tmpl.prp*
EOTEMPLATE
@ NUMMI1 = $NUMSEC - 1
#
# create _m.com file
#
cat >! $comm <<EOCAT
#
excise <<EOF
$argv[1]

$BN.pt
$BN.exc
$IXAVG
$IYAVG
0,0
EOF
#
# Average them
#
avgstack <<EOF
$BN.exc
$BN.avg
/
EOF
#
# Filter excised pieces and their average
#
enhance $BN.avg $BN.avge <<EOF
$FILTERPARAMS
1
EOF
enhance $BN.exc $BN.exce <<EOF
$FILTERPARAMS
1
EOF
#
# Run first alignment to initial average, without interpolation in search
#
csh -f $com1 0
#
# Transform pieces, average them, and filter average
#
newstack <<EOF
1
$BN.exc
0-$NUMMI1
1
$BN.ali
/
/
0
1
xflist.tmp
0-$NUMMI1
0
EOF
avgstack <<EOF
$BN.ali
$BN.avg
/
EOF
#
enhance $BN.avg $BN.avge <<EOF
$FILTERPARAMS
1
EOF
#
# Run second alignment, to improved average, with interpolation in search
#
csh -f $com1 1
#
# Transform again with new alignment, get final average
#
newstack <<EOF
1
$BN.exc
0-$NUMMI1
1
$BN.ali
/
/
0
1
xflist.tmp
0-$NUMMI1
0
EOF
avgstack <<EOF
$BN.ali
$BN.avg
/
EOF
#
# Save transform file, clean up files; leave excised pieces and all averages
#
if (-e xf$BN.dat) \mv -f xf$BN.dat xf$BN.dat~
\mv xflist.tmp xf$BN.dat
\rm -f $BN.ali* $BN.avge* $BN.exce*
echo2 Longitudinal average $BN finished
EOCAT
#
chmod +x $com1 $comm
csh -f $comm >/dev/null &
echo "Master command file being executed in background, output to /dev/null"
