#!/bin/csh

# Run treedist as a command
# Version  2/27/2007
# Synopsis: treedist.csh intree disttype outgroup rooted whichdist outstyle outfile


#Convert arguments to variables
set INFILE      = $1
set DISTTYPE    = $2
set OUTGROUP    = $3
set ROOTED      = $4
set WHICHDIST   = $5
set OUTSTYLE    = $6
set OUTFILE     = $7


# RM_CMD - command to be used for removing files and directories
if (-e /usr/bin/rm) then
   set RM_CMD = /usr/bin/rm
else
   if (-e /bin/rm) then
      set RM_CMD = /bin/rm
   else
      set RM_CMD = rm
   endif
endif

# Make a temporary directory to run the program in 
set TEMPDIR = TREEDIST.$$
mkdir $TEMPDIR
cp $INFILE $TEMPDIR/intree
cd $TEMPDIR

# Remember where we started
set STARTDIR = $PWD


#----------------- Generate a header to append to the beginning of the output file -----
echo '                   TREEDIST' > MSGFILE
echo '' >> MSGFILE 

#----------------- generate keyboard input to send to program -----

# Check for branch lengths in first few lines of input file.
# If no branch lengths exist, we must use Symmetric 
@ BRLEN  = `head intree | egrep -c -e ".*\:[0-9]*\.[0-9]*"` 
if ( ("$DISTTYPE" == "b") && ( "$BRLEN" == "0" ) ) then
   set DISTTYPE = "s"
    echo '>>>>> Warning: No branch lengths.' >> MSGFILE
    echo '>>>>> Using Symmetric Difference.' >> MSGFILE
    echo '' >> MSGFILE
endif

# Choose distance measure
switch ($DISTTYPE)
  case "b":                # Branch Score Distance (default)
    breaksw
  case "s":                # Symmetric
     echo d >> PARAMFILE
    breaksw
  default :              
    breaksw    
endsw

# Outgroup
if ($OUTGROUP > 1) then
   echo o >> PARAMFILE
   echo $OUTGROUP >> PARAMFILE
endif

# Should tree be rooted?
if ($ROOTED ==  y) echo r >> PARAMFILE

# Set the style for the report written to outfile
# C and L not currently implemented.
switch ($WHICHDIST)
  case "a":                # Dist. between adjacent pairs in one tree file (default)
    echo 2 >> PARAMFILE
    echo a >> PARAMFILE
    if ( ($OUTSTYLE == v) | ($OUTSTYLE == s) ) then
       echo $OUTSTYLE >> PARAMFILE 
    else
       echo v >> PARAMFILE
    endif    
    breaksw
  case "p":                # Dist. between all possible pairs in one tree file
    echo 2 >> PARAMFILE
    echo p >> PARAMFILE
    if ( ($OUTSTYLE == f ) | ($OUTSTYLE == v) | ($OUTSTYLE == s) ) then
       echo $OUTSTYLE >> PARAMFILE 
    else
       echo v >> PARAMFILE
    endif   
    breaksw
  default :                
    breaksw    
endsw

#accept current settings and do the analysis
echo y  >> PARAMFILE


#-------- Run treedist, sending terminal output to /dev/null -----------
# high nice level is set just in case we do get an infinite loop
# Remember, treedist reads a file called intree, and writes to outfile
nice +10 treedist < PARAMFILE > /dev/null 
cat MSGFILE outfile > ../$OUTFILE
cd ..
$RM_CMD -r $TEMPDIR






