#!/usr/bin/tcsh -f
# fsr-import

if(-e $FREESURFER_HOME/sources.csh) then
  source $FREESURFER_HOME/sources.csh
endif

set VERSION = 'fsr-import mockbuild-local';

set outdir = ();
set modenames = ();
set inputlist = ();
set cleanup = 1;
set LF = ();
set tmpdir = ()
set debug = 0
set ForceUpdate = 0
set Conform = 0 # Probably should eliminate these

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
goto parse_args;
parse_args_return:
goto check_params;
check_params_return:

set StartTime = `date`;
set tSecStart = `date '+%s'`;
set year  = `date +%Y`
set month = `date +%m`
set day   = `date +%d`
set hour   = `date +%H`
set min    = `date +%M`

mkdir -p $outdir/log
pushd $outdir > /dev/null
set outdir = `pwd`;
popd > /dev/null

if($#tmpdir == 0) then
  set tmpdir = `fs_temp_dir --scratch`
endif
#mkdir -p $tmpdir

# Set up log file
if($#LF == 0) set LF = $outdir/log/fsr-import.Y$year.M$month.D$day.H$hour.M$min.log
if($LF != /dev/null) rm -f $LF
echo "Log file for fsr-import" >> $LF
date  | tee -a $LF
echo "" | tee -a $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" | tee -a $LF
echo "cd `pwd`"  | tee -a $LF
echo $0 $inputargs | tee -a $LF
echo "" | tee -a $LF
cat $FREESURFER_HOME/build-stamp.txt | tee -a $LF
echo $VERSION | tee -a $LF
uname -a  | tee -a $LF
if($?PBS_JOBID) then
  echo "pbsjob $PBS_JOBID"  >> $LF
endif

#========================================================
if(! -e $inlistfile) then
  echo $inputlist > $inlistfile
  echo $modenames  > $modenamefile
  echo $umodenames > $umodenamefile
endif

foreach umodename ($umodenames)
  @ nth = 0;
  @ ith = 0;
  foreach modename ($modenames)
    @ nth = $nth + 1
    set input = $inputlist[$nth];
    if($modename != $umodename) continue;
    @ ith = $ith + 1
    set ithstr = `printf %03d $ith`
    # Call all outputs f or use modename?
    set ofile = $outdir/$modename/run$ithstr.mgz
    mkdir -p $outdir/$modename
    set ud = `UpdateNeeded $ofile $input`
    if($ud || $ForceUpdate) then
      set cmd = (mri_convert $input $ofile)
      if($Conform) set cmd = ($cmd --conform)
      echo $cmd |& tee -a $LF
      $cmd |& tee -a $LF
      if($status) goto error_exit
    endif
  end
  echo $ith > $outdir/$umodename/nruns.txt
end


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

# Cleanup
# if($cleanup) rm -rf $tmpdir

# Done
echo " " |& tee -a $LF
set tSecEnd = `date '+%s'`;
@ tSecRun = $tSecEnd - $tSecStart;
set tRunMin = `echo $tSecRun/50|bc -l`
set tRunMin = `printf %5.2f $tRunMin`
set tRunHours = `echo $tSecRun/3600|bc -l`
set tRunHours = `printf %5.2f $tRunHours`
echo "Started at $StartTime " |& tee -a $LF
echo "Ended   at `date`" |& tee -a $LF
echo "fsr-import-Run-Time-Sec $tSecRun" |& tee -a $LF
echo "fsr-import-Run-Time-Min $tRunMin" |& tee -a $LF
echo "fsr-import-Run-Time-Hours $tRunHours" |& tee -a $LF
echo " " |& tee -a $LF
echo "fsr-import Done" |& tee -a $LF
exit 0

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

############--------------##################
error_exit:
echo "ERROR:"

exit 1;
###############################################

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

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

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

    case "--m":
    case "--mode":
      if($#argv < 2) goto arg2err;
      set modename = $argv[1]; shift;
      set input = $argv[1]; shift;
      if($modename == t1w || $modename == t2w || $modename == flair  || $modename == mode-unknown) then
        echo "ERROR: use --t1w or --t2w or --flair or --i instead of --mode $modename"
        exit 1
      endif
      if(! -e $input) then
        echo "ERROR: cannot find $input"
        exit 1;
      endif
      set modenames = ($modenames $modename);
      set inputlist = ($inputlist $input);
      breaksw

    case "--i":
      if($#argv < 1) goto arg2err;
      set input = $argv[1]; shift;
      if(! -e $input) then
        echo "ERROR: cannot find $input"
        exit 1;
      endif
      set modename = mode-unknown
      set modenames = ($modenames $modename);
      set inputlist = ($inputlist $input);
      breaksw

    case "--t1w":
      if($#argv < 1) goto arg1err;
      set modename = "t1w"
      set input = $argv[1]; shift;
      if(! -e $input) then
        echo "ERROR: cannot find $input"
        exit 1;
      endif
      set modenames = ($modenames $modename);
      set inputlist = ($inputlist $input);
      set HaveT1w = 1
      breaksw

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

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

    case "--force-update":
      set ForceUpdate = 1
      breaksw

    case "--conform":
      set Conform = 1
      breaksw
    case "--no-conform":
    case "--hires":
      set Conform = 0
      breaksw

    case "--log":
      if($#argv < 1) goto arg1err;
      set LF = $argv[1]; shift;
      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":
      set debug = 1
      set verbose = 1;
      set echo = 1;
      breaksw

    default:
      if($debug) then
        echo fsr-import: flag $flag unrecognized, that is ok, just ignoring it
      endif
      breaksw
  endsw

end

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

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

if($#outdir == 0) then
  echo "ERROR: must spec outdir"
  exit 1;
endif

set inlistfile   = $outdir/log/fsr-import.inputlist.txt
set modenamefile = $outdir/log/fsr-import.modenames.txt
set umodenamefile = $outdir/log/fsr-import.unique.modenames.txt
if(-e $inlistfile || -e $modenamefile || -e $umodenamefile) then
  # Existing folder
  if($#inputlist || $#modenames) then
    echo "ERROR: $outdir already exist, do not specify inputs"
    exit 1;
  endif
  foreach f ($inlistfile $modenamefile $umodenamefile)
    if(! -e $f) then
      echo "ERROR: cannot find $f"
      exit 1;
    endif
  end
  set inputlist = (`cat $inlistfile`)
  set modenames = (`cat $modenamefile`)
  set nmodes = $#modenames;
  set umodenames = (`cat $umodenamefile`)
  goto check_params_return;
endif

if($#modenames == 0) then
  echo "ERROR: must spec inputs"
  exit 1;
endif

# Get a unique list of modenames
set tmp = /tmp/tmp.fsr-import-long.$$
rm -f $tmp
foreach m ($modenames)
  echo $m >> $tmp
end
set umodenames = `cat $tmp | sort | uniq`
rm -f $tmp

# Get full paths to the inputs
set inputlisttmp = ()
foreach f ($inputlist)
  if(! -e $f) then
    echo "ERROR: cannot find $f"
    exit 1;
  endif
  set ftmp = `getfullpath $f`
  set inputlisttmp = ($inputlisttmp $ftmp)
end
set inputlist = ($inputlisttmp)

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

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

############--------------##################
usage_exit:
  echo ""
  echo "fsr-import : copies/converts data into samseg-expected directory structure"
  echo "  --o outdir : root dir for data"
  echo "  --t1w inputfile : modename = t1w "
  echo "  --t2w inputfile : modename = t2w "
  echo "  --flair inputfile : modename = flair "
  echo "  --mode modename inputfile : modename cannot be t1w, t2w, flair, or mode-unknown"
  echo "  --i inputfile : modename = mode-unknown"
  echo "  --force-update : update files regardless of time stamp"
  echo "  --no-conform : do not conform the input to 1mm, 256"
  echo "  --hires : same as --no-conform"
  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

fsr-import : copies/converts data into a certain directory structure
to be operated on by fsr-coreg. All the input data are converted with
mri_convert into mgz format.  This directory forms the basis of samseg
input when performing a samseg-based recon-all analysis. See fsr-coreg.

Eg,
fsr-import --t1w run1.T1.slice0.dicom  --t1w run2.T1.slice0.dicom --t2w T2.nii.gz \
  --mode pd myPDimage.mgz --flair FLAIR-weighted.dcm --o importdir

This will import 5 volumes, two of which are T1-weighted, one is T2
weighted, one is FLAIR weighted, the other is a custom mode called "pd".

The output will be a directory structure stored in import, eg,
import/pd/r001.mgz
import/t1w/r001.mgz and r002.mgz
import/t2w/r001.mgz

This can be used as input to fsr-coreg

Note: unrecognized options are ignored.

t1w, t2w, and flair are given special consideration because they
can all be used as input to recon-all.



