#!/bin/csh
#      maketree.csh <blocks> <type>  Make a tree from a set of blocks
#	<type> = dat (data), xbm (xbitmap), ps (postscript),
#		 pdf (pdf), new (newick), gif
#	<type> is optional, calls drawgram.csh if provided
#	creates <blocks>:r.treefile & displays it in <type> format
#   where <blocks> is a file containing the blocks to be processed
#   Attempts to find nseq from <blocks>:r.seqs
#	Used by process_blocks.pl
#--------------------------------------------------------------------------
#  7/19/02 Check for and save $r.treefile
#  1/ 3/03 Replace clustalw with quicktree
#
unalias rm
unalias mv
limit cputime 5m

#
#  If $1 = /howard/btest/tmp/AA.blks, then $r = /howard/btest/tmp/AA
#
if ( -e $1 ) then
   set r = $1:r

   #  Try to find out how big the tree is
   if ( -e $r.seqs ) then
       @ nseq = (`grep -c ">" $r.seqs`)
   else
       @ nseq = 0
   endif

   #   See if the tree is already made
   if ( !(-e $r.treefile) ) then
      #		Make tree file using quicktree
      ./blimps-bin/blalign $1 -h > $r.hblks
      if ( -e $r.hblks ) then
         @ nchar = (`wc -m $r.hblks | awk '{print $1}'`)
         @ nerr = (`grep -c "ERROR in block" $r.hblks`)
#echo "nseq=$nseq nchar=$nchar nerr=$nerr"
         if ($nerr == 0) then
            # 	Bootstrap if not too many seqs (same limit as protomat.csh)
            if (($nseq > 0 && $nseq <= 100) || ($nseq == 0 && $nchar <= 25000)) then
               @ nboot = 100
               (./quicktree -in a -out t -kimura -boot $nboot $r.hblks > $r.treefile) >& $r.err
            else
               (./quicktree -in a -out t -kimura $r.hblks > $r.treefile) >& $r.err
            endif
            if ( !(-e $r.treefile) || (-z $r.treefile)) then
               echo "quicktree failed to make a tree" >> $r.treefile
               cat $r.err >> $r.treefile
            endif
         else
            echo "Failed to make a tree due to block errors" >> $r.treefile
            grep "ERROR in block" $r.hblks >> $r.treefile
         endif  # end of nerr
      endif  # end of if hblks
#     rm $r.hblks $r.err >& /dev/null
   endif      # end of if no treefile
#  
else
   echo "Cannot open blocks file $1 to make a tree." >> $r.treefile
   exit
endif
#
#------------------Make plotfile & display the tree -------------------

if ($#argv < 2) then 
   exit(0)
else
   set type = $2
endif
if ( -e $r.treefile ) then
	./drawgram.csh $r.treefile $type
endif

exit(0)
