#!/bin/tcsh -f
# tkmeditfv

set VERSION = 'tkmeditfv dev';

setenv FS_COPY_HEADER_CTAB 1 # make sure that anything saved in FV has its colortable

set subject = ();
set overlay = ();
set mainvol = ();
set auxvol = ();
set auxvol0 = ();
set segvol = ();
set segvol0 = ();
set segctab = ();
set auxsegvol = ();
set auxsegvol0 = ();
set auxsegctab = ();
set segvollist = ();
set segcolorlist = ();
set surflist = ();
set surflist0 = ();
set surfcolor = ();
set mainsurf = ();
set auxsurf = ();
set DoSurfs = 0;
set surfext = ()
set overlay = ();
set overlayreg = ();
set twfvol = ();
set twfreg = ();
set segcolor = $FREESURFER_HOME/FreeSurferColorLUT.txt
set auxsegcolor = $FREESURFER_HOME/FreeSurferColorLUT.txt
set ctabset = 0
set segopacity = 1;
set fthresh = 2;
set fmax    = 5;
set labellist = ();
set UseTkMedit = 0;
set vollist0 = ();
set CursorCRS = ();
set CenterCursor = 0;
set Zoom = ();
set altargs = ()
set DoDefects = 0;
set SegOutline = 0;
set mainmin = ()
set mainmax = ()
set annot = ()

set tmpdir = ();
set cleanup = 1;
set LF = ();

set inputargs = ($argv);
set PrintHelp = 0;

if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
endif
set n = `echo $argv | grep -e -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:
goto check_params;
check_params_return:

set StartTime = `date`;
set tSecStart = `date '+%s'`;

#========================================================

if(! $UseTkMedit) then
  ### FreeView ####----------------------------------------------
  if($#mainmin == 0) then
    set cmd = (freeview  -v $mainvol)
  else
    set cmd = (freeview  -v $mainvol":"grayscale=$mainmin,$mainmax)
  endif
  if($#auxvol) set cmd = ($cmd -v $auxvol)
  if($#segvol) then
    set cmd = ($cmd -v "$segvol":"opacity=$segopacity":"colormap=lut":"outline=$SegOutline")
    set hasctab = `mri_info --ctab $segvol | wc -l`
 echo main hasctab $hasctab
    if($ctabset || ! $hasctab) then
      if($#segcolor) set cmd = ($cmd":lut=$segcolor")
    endif
  endif
  if($#auxsegvol) then
    set cmd = ($cmd -v "$auxsegvol":"opacity=$segopacity":"colormap=lut":"outline=$SegOutline")
    set hasctab = `mri_info --ctab $auxsegvol | wc -l`
    if($ctabset || ! $hasctab) then
      if($#segcolor) set cmd = ($cmd":lut=$segcolor")
    endif
  endif
  @ nth = 0;
  foreach v ($segvollist) 
    @ nth = $nth + 1;
    set cmd = ($cmd -v "$v":"opacity=$segopacity":"colormap=lut")
    set hasctab = `mri_info --ctab $v | wc -l`
    if($ctabset || ! $hasctab) then
      if($#segcolor) set cmd = ($cmd":lut=$segcolorlist[$nth]")
    endif
  end
  if($#labellist) then
    foreach label ($labellist)
      set cmd = ($cmd -l $label)
    end
  endif
  foreach ov ($overlay)
    #set fmid = `echo "($fthresh+$fmax)/2"|bc -l`
    set fmid = $fthresh;
    set fvopt = ($ov":"colormap=heat":"heatscale=$fthresh,$fmid,$fmax)
    if($#overlayreg) set fvopt = ($fvopt":"reg=$overlayreg)
    set cmd = ($cmd -v $fvopt)
  end
  if($#twfvol) then
    set fvopt = ($twfvol)
    if($#twfreg) set fvopt = ($fvopt":"reg=$twfreg)
    set cmd = ($cmd -v $fvopt)
  endif
  foreach vol ($vollist)
    set cmd = ($cmd -v $vol)
  end
  if($DoDefects) then
    set cmd = ($cmd -c $SUBJECTS_DIR/$subject/surf/?h.defects.pointset)
  endif
  @ nth = 0;
  foreach surf ($surflist)
    @ nth = $nth + 1;
    set ov = ()
    if($DoDefects) then
      set sdir = $SUBJECTS_DIR/$subject/surf
      if($surflist0[$nth] == lh.orig.nofix) set ov = ":overlay=$sdir/lh.defect_labels:edgecolor=overlay"
      if($surflist0[$nth] == rh.orig.nofix) set ov = ":overlay=$sdir/rh.defect_labels:edgecolor=overlay"
    endif
    set annotarg = ()
    if($#annot) then
      set surfname = `basename $surf`
      set hemi = `echo $surfname | cut -c1-2`
      if($hemi == lh || $hemi == rh) then
        set annotfile = $SUBJECTS_DIR/$subject/label/$hemi.$annot
        set annotarg = ":annot=$annotfile":"annot_outline=0"
      endif   
    endif
    set cmd = ($cmd --surface $surf":"edgecolor=$surfcolor[$nth]$ov$annotarg)
  end
  if($#CursorCRS) set cmd = ($cmd -slice $CursorCRS)
  if($CenterCursor) set cmd = ($cmd -cc)
  if($#Zoom) set cmd = ($cmd -zoom $Zoom)
  set cmd = ($cmd $altargs --hide-3d-slices)
else
  ### tkmedit ####----------------------------------------------
  set cmd = tkmedit
  if($#subject) then 
    set cmd = ($cmd $subject)
  else
    set cmd = ($cmd -f)
  endif
  set cmd = ($cmd $mainvol)
  if($#mainsurf) set cmd = ($cmd $mainsurf)
  if($#auxvol) set cmd = ($cmd -aux $auxvol)
  if($#segvol) set cmd = ($cmd -seg $segvol $segcolor -opacity $segopacity)
  if($#auxsegvol) set cmd = ($cmd -seg $auxsegvol $auxsegcolor -opacity $segopacity)
  if($#overlay) then
    set cmd = ($cmd -overlay $overlay)
    if($#overlayreg) set cmd = ($cmd -overlay-reg $overlayreg)
  endif
  if($#twfvol) then
    set cmd = ($cmd -t $twfvol)
    if($#twfreg) set cmd = ($cmd -timecourse-reg $twfreg)
  endif
  if($#labellist) then
    foreach label ($labellist)
      set cmd = ($cmd -label $label)
    end
  endif
  if($#auxsurf) set cmd = ($cmd -aux-surface $auxsurf)
  if($DoSurfs) set cmd = ($cmd -surfs)
endif
echo $cmd
fsvglrun $cmd
#setenv VGL_DISPLAY :0
#  exec /usr/pubsw/bin/vglrun $cmd


#========================================================

exit 0

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

############--------------##################
parse_args:
set cmdline = ($argv);

if("$argv[1]" == "-f") then
  set flag = $argv[1]; shift;
  set mainvol0 = $argv[1]; shift;
else
  set subject = $argv[1]; shift;
  set mainvol0 = $argv[1]; shift;
  if(! `isargflag $argv`) then
    set mainsurf = $argv[1]
    set surflist0 = ($surflist0 $mainsurf); shift;
  endif
endif

while( $#argv != 0 )

  set flag = $argv[1]; shift;
  
  switch($flag)

    case "-aux":
      if($#argv < 1) goto arg1err;
      set auxvol0 = $argv[1]; shift;
      breaksw

    case "-seg":
      if($#argv < 1) goto arg1err;
      set segvol0 = $argv[1]; shift;
      if(! `isargflag $argv`) then
        set segcolor = $argv[1]; shift;
      endif
      breaksw

    case "-seg2":
      # This is a slightly embarassing hack to have more than two
      # seg volumes in freeview. I should reprogram it so that 
      # the main and aux seg are just part of the segvollist
      if($#argv < 1) goto arg1err;
      set segvol2 = $argv[1]; shift;
      if(! `isargflag $argv`) then
        set segcolor2 = $argv[1]; shift;
      else
        set segcolor2 = $FREESURFER_HOME/FreeSurferColorLUT.txt
      endif
      set segvollist = ($segvollist $segvol2)
      set segcolorlist = ($segcolorlist $segcolor2)
      breaksw

    case "-aux-seg":
      if($#argv < 1) goto arg1err;
      set auxsegvol0 = $argv[1]; shift;
      if(! `isargflag $argv`) then
        set auxsegcolor = $argv[1]; shift;
      endif
      breaksw

    case "-ctab":
      if($#argv < 1) goto arg1err;
      set segcolor = $argv[1]; shift
      set segcolor2 = $segcolor
      set auxsegcolor = $segcolor
      set ctabset = 1
      breaksw

    case "-no-ctab":
      set segcolor = ()
      set segcolor2 = ()
      set auxsegcolor = ()
      breaksw

    case "-aseg":
      set segvol0 = aseg.mgz
      breaksw

    case "-aparc+aseg":
      set segvol0 = aparc+aseg.mgz
      breaksw

    case "-defect":
    case "-defects":
      set DoDefects = 1;
      set segvol0 = surface.defects.mgz
      set segcolor = (); # color table imbedded
      set surflist0 = ($surflist0 lh.orig.nofix)
      set surflist0 = ($surflist0 rh.orig.nofix)
      set surflist0 = ($surflist0 lh.orig)
      set surflist0 = ($surflist0 rh.orig)
      set surfcolor = ($surfcolor green green yellow yellow)
      breaksw

    case "-vol":
      if($#argv < 1) goto arg1err;
      set vol = $argv[1];
      set vollist0 = ($vollist0 $vol); shift;
      breaksw

    case "-annot":
      if($#argv < 1) goto arg1err;
      set annot = $argv[1]; shift;
      breaksw

    case "-aparc":
      set annot = aparc.annot
      breaksw

    case "-op":
    case "-opacity":
      if($#argv < 1) goto arg1err;
      set segopacity = $argv[1]; shift;
      breaksw

    case "-label":
    case "-l":
      if($#argv < 1) goto arg1err;
      set labellist = ($labellist $argv[1]); shift;
      breaksw

    case "-reg":
      if($#argv < 1) goto arg1err;
      set overlayreg = $argv[1]; shift;
      set twfreg = $overlayreg;
      breaksw

    case "-overlay-reg":
      if($#argv < 1) goto arg1err;
      set overlayreg = $argv[1]; shift;
      breaksw

    case "-timecourse-reg":
      if($#argv < 1) goto arg1err;
      set twfreg = $argv[1]; shift;
      breaksw

    case "-overlay":
    case "-ov":
      if($#argv < 1) goto arg1err;
      set ov = $argv[1]; shift;
      if(! -e $ov) then
        echo "ERROR: cannot find $ov"
        exit 1;
      endif
      set overlay = ($overlay $ov)
      breaksw

    case "-timecourse":
    case "-t":
      if($#argv < 1) goto arg1err;
      set twfvol = $argv[1]; shift;
      if(! -e $twfvol) then
        echo "ERROR: cannot find $twfvol"
        exit 1;
      endif
      breaksw

    case "-main-minmax":
      if($#argv < 2) goto arg2err;
      set mainmin = $argv[1]; shift;
      set mainmax = $argv[1]; shift;
      breaksw

    case "-fminmax":
      if($#argv < 2) goto arg2err;
      set fthresh = $argv[1]; shift;
      set fmax = $argv[1]; shift;
      breaksw

    case "-fmin":
    case "-fthresh":
      if($#argv < 1) goto arg1err;
      set fthresh = $argv[1]; shift;
      breaksw

    case "-fmax":
      if($#argv < 1) goto arg1err;
      set fmax = $argv[1]; shift;
      breaksw

    case "-surface":
    case "-surf":
      if($#argv < 1) goto arg1err;
      set mainsurf = $argv[1]; shift;
      set surflist0 = ($surflist0 $mainsurf); 
      set sc = "yellow";
      if($#argv > 0) then
         if(! `isargflag $argv[1]`) set sc = $argv[1]; shift;
      endif
      set surfcolor = ($surfcolor $sc)
      breaksw

    case "-aux-surface":
    case "-aux-surf":
      if($#argv < 1) goto arg1err;
      set auxsurf = $argv[1]
      set surflist0 = ($surflist0 $auxsurf); shift;
      set sc = "yellow";
      if($#argv > 0) then
        if(! `isargflag $argv[1]`) then
          set sc = $argv[1]; shift;
        else
          set auxsegcolor = "red";
        endif
      endif
      set surfcolor = ($surfcolor $sc)
      breaksw

    case "-surfs":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.white rh.white lh.pial rh.pial)
      set surfcolor = ($surfcolor yellow yellow red red);
      breaksw

    case "-lh-surfs":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.white lh.pial)
      set surfcolor = ($surfcolor yellow red);
      breaksw

    case "-rh-surfs":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 rh.white rh.pial)
      set surfcolor = ($surfcolor yellow red);
      breaksw

    case "-pial":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.pial rh.pial)
      set surfcolor = ($surfcolor red red);
      breaksw

    case "-woT2":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.woT2.pial rh.woT2.pial)
      set surfcolor = ($surfcolor red red);
      breaksw

    case "-white":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.white rh.white)
      set surfcolor = ($surfcolor yellow yellow)
      breaksw

    case "-orig":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.orig rh.orig)
      set surfcolor = ($surfcolor green green)
      breaksw

    case "-orig.nofix":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.orig.nofix rh.orig.nofix)
      set surfcolor = ($surfcolor cyan cyan)
      breaksw

    case "-inflated":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.inflated rh.inflated)
      set surfcolor = ($surfcolor cyan cyan)
      breaksw

    case "-lh-inflated":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 lh.inflated)
      set surfcolor = ($surfcolor cyan)
      breaksw

    case "-rh-inflated":
      set DoSurfs = 1;
      set surflist0 = ($surflist0 rh.inflated)
      set surfcolor = ($surfcolor cyan)
      breaksw

    case "-surfext":  
      if($#argv < 1) goto arg1err;
      set surfext = $argv[1]; shift
      breaksw

    case "-crs":
      if($#argv < 3) goto arg3err;
      set CursorCRS = ($argv[1-3]);
      shift;shift;shift;
      set CenterCursor = 1;
      breaksw

    case "-zoom":
      if($#argv < 1) goto arg1err;
      set Zoom = $argv[1]; shift;
      breaksw

    case "-seg-outline":
      set SegOutline = 1;
      breaksw

    case "-tkmedit":
    case "-tkm":
      set UseTkMedit = 1;
      breaksw

    case "-vgl":
      setenv FS_ALLOW_VGLRUN 1
      breaksw
    case "-novgl":
    case "-no-vgl":
      unsetenv FS_ALLOW_VGLRUN 
      breaksw

    case "--nolog":
    case "--no-log":
      set LF = /dev/null
      breaksw

    case "--tmp":
    case "--tmpdir":
      if($#argv < 1) goto arg1err;
      set tmpdir = $argv[1]; shift;
      set cleanup = 0;
      breaksw

    case "--nocleanup":
      set cleanup = 0;
      breaksw

    case "--cleanup":
      set cleanup = 1;
      breaksw

    case "-debug":
    case "--debug":
      set verbose = 1;
      set echo = 1;
      breaksw

    default:
      set altargs = ($altargs $flag)
      #echo ERROR: Flag $flag unrecognized. 
      #echo $cmdline
      #exit 1
      breaksw

  endsw

end

goto parse_args_return;
############--------------##################

############--------------##################
check_params:

if($#subject) then
  if("$subject" == getreg) then
    if($#overlayreg == 0) then
      echo "ERROR: must supply regfile with getreg"
      exit 1;
    endif
    if(! -e $overlayreg ) then
      echo "ERROR: cannot find $overlayreg"
      exit 1;
    endif
    #set subject = `head -n 1 $overlayreg`
    set subject = `reg2subject --r $overlayreg`;
  endif
  if(! -e $SUBJECTS_DIR/$subject) then
    echo "ERROR: cannot find $subject"
    exit 1;
  endif
  if(-e $mainvol0) then
    set mainvol = $mainvol0
  else
    set mainvol = $SUBJECTS_DIR/$subject/mri/$mainvol0
  endif
  if($#auxvol0) then
    if(-e $auxvol0) then
      set auxvol = $auxvol0
    else
      set auxvol = $SUBJECTS_DIR/$subject/mri/$auxvol0
    endif
  endif
  if($#segvol0) then
    if(-e $segvol0) then
      set segvol = $segvol0
    else
      set segvol = $SUBJECTS_DIR/$subject/mri/$segvol0
    endif
    if($#segcolor) then
      if(! -e $segcolor) then
        set segcolor0 = $segcolor;
        set segcolor = $SUBJECTS_DIR/$subject/mri/$segcolor0
        if(! -e $segcolor) then
          set segcolor = $FREESURFER_HOME/$segcolor0
          if(! -e $segcolor) then
            echo "ERROR: cannot find $segcolor0"
            exit 1; 
          endif
        endif
      endif
    endif
  endif
  if($#auxsegvol0) then
    if(-e $auxsegvol0) then
      set auxsegvol = $auxsegvol0
    else
      set auxsegvol = $SUBJECTS_DIR/$subject/mri/$auxsegvol0
    endif
    if($#auxsegcolor) then
      if(! -e $auxsegcolor) then
        set auxsegcolor0 = $auxsegcolor;
        set auxsegcolor = $SUBJECTS_DIR/$subject/mri/$auxsegcolor0
        if(! -e $auxsegcolor) then
          set auxsegcolor = $FREESURFER_HOME/$auxsegcolor0
          if(! -e $auxsegcolor) then
            echo "ERROR: cannot find $auxsegcolor0"
            exit 1; 
          endif
        endif
      endif
    endif
  endif
  foreach surf ($surflist0)
    if(-e $surf$surfext) then
      set surflist = ($surflist $surf$surfext)
    else
      set surfpath = $SUBJECTS_DIR/$subject/surf/$surf$surfext
      set surflist = ($surflist $surfpath)
    endif
  end
  set labellist2 = ()
  foreach label ($labellist)
    if(! -e $label) then
      set l0 = $SUBJECTS_DIR/$subject/label/$label
      if(! -e $l0 && ! -e $label) then 
        echo "ERROR: cannot find $label or $l0"
        exit 1;
      endif
      set label = $l0
      set labellist2 = ($labellist2 $label)
    endif
  end
  set labellist = ($labellist2)
else
  set mainvol = $mainvol0
  if($#auxvol0) set auxvol = $auxvol0
  if($#segvol0) set segvol = $segvol0
  if($#auxsegvol0) set auxsegvol = $auxsegvol0
  set surflist = ($surflist0)
endif

foreach label ($labellist)
  if(! -e $label) then
    echo "ERROR: cannot find $label"
    exit 1;
  endif
end

set vollist = ()
foreach vol0 ($vollist0)
  set vol = ();
  if(-e $vol0) set vol = $vol0;
  else 
    set voltry = $SUBJECTS_DIR/$subject/mri/$vol0
    if(-e $vol0) then
      set vol = $voltry
    else 
      echo "ERROR: cannot find $vol0"
      exit 1;
    endif
  endif
  set vollist = ($vollist $vol) 
end

goto check_params_return;
############--------------##################

############--------------##################
arg1err:
  echo "ERROR: flag $flag requires one argument"
  exit 1
############--------------##################
arg2err:
  echo "ERROR: flag $flag requires two arguments"
  exit 1
############--------------##################
arg3err:
  echo "ERROR: flag $flag requires three arguments"
  exit 1
############--------------##################

############--------------##################
usage_exit:
  echo ""
  echo "This is a script that runs freeview with arguments like tkmedit."
  echo "Not all tkmedit functionality is replicated and it can do some things that"
  echo "that tkmedit cannot do."
  echo ""
  echo "tkmeditfv subject mainvol -aux auxvol -seg segvol -ov overlay  -t timecourse -reg overlaytimereg"
  echo "tkmeditfv -f mainvol -aux auxvol -seg segvol -ov overlay -reg overlayreg "
  echo ""
  echo "-tkmedit : use tkmedit instead of freeview"
  echo "-aparc+aseg"
  echo "-surfs  : load lh and rh white and pial (-lh-surfs, -rh-surfs)"
  echo "-surf /path/to/surface <color> : load surface with optional color (eg, blue)"
  echo "-vol volume1 <-vol volume2> : load extra volumes "
  echo "-crs col row slice : place cursor at given location and center FoV"
  echo "-zoom Zoom : set zoom level"
  echo "-seg2 seg3 <-seg2 seg4> : add segs beyond -seg and -aux-seg"
  echo "-white : load {l,r}h.white"
  echo "-pial : load {l,r}h.pial"
  echo "-orig : load {l,r}h.orig"
  echo "-orig.nofix : load {l,r}h.orig.nofix"
  echo "-inflated : load {l,r}h.inflated (-lh-inflated, -rh-inflated)"
  echo "-annot annotname : load subject/label/hemi.annotname"
  echo "-aparc : load subject/label/hemi.aparc.annot"
  echo "-surfext ext : add ext to the name of the surface"
  echo "-seg-outline : bring up segmentation in outline mode"
  echo "-main-minmax min max : set intensity min max on fist volume"
  echo "-vgl :   setenv VGL_DISPLAY :0 and runs freeview with /usr/pubsw/bin/vglrun"
  echo ""
  if(! $PrintHelp) exit 1;
  echo $VERSION
  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'
exit 1;

#---- Everything below here is printed out as part of help -----#
BEGINHELP

