#!/bin/csh

#Version  7/ 7/2006
#Synopsis: consense.csh intree method fraction outgroup rooted outfile outtree

# Run consense as a command
# At present, this script has no way to check the number of 
# "species" in the trees in intree. If OUTGROUP is greater
# than the number of sequences, consense will go into an 
# infinite loop prompting for OUTGROUP. dnapars.csh does
# check the number of "species". Similar checks should exist
# in any procedure that calls this script.

#Convert arguments to variables
set INFILE      = $1
set METHOD      = $2
set FRACTION    = $3
set OUTGROUP    = $4
set ROOTED      = $5
set OUTFILE     = $6
set TREEFILE    = $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 = CONSENSE.$$
mkdir $TEMPDIR
cp $INFILE $TEMPDIR/intree
cd $TEMPDIR

# Remember where we started
set STARTDIR = $PWD

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

# Choose resampling method
switch ($METHOD)
  case "e":                # Majority rule (extended)
    breaksw
  case "s":                # strict majority rule
     echo c >> PARAMFILE
    breaksw
  case "m":                # Majority rule
     echo c >> PARAMFILE
     echo c >> PARAMFILE
    breaksw
  case "l":                # Ml
     echo c >> PARAMFILE
     echo c >> PARAMFILE
     echo c >> 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

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

# Enter fraction for M1 method. This can either
# be a real number, in which case it is directly
# used, or an integer between 50 and 100, which
# is converted to a real number.
if ($METHOD == "l") then
   # consense.item generates an integer between 50 and 100,
   # which we can convert into a fraction
   if ($FRACTION > 1) then
      if ($FRACTION == "100") then
         set FRACTION = 1
      else
         set FRACTION = 0.$FRACTION
      endif
   endif
   echo $FRACTION >> PARAMFILE
   echo 'FRACTION set to '$FRACTION
endif

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






