#! /bin/csh -f

#
# compress-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:16 $
#    $Revision: 1.3 $
#
# Copyright (C) 2002-2007,
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-bugs@nmr.mgh.harvard.edu
#


set VERSION = '$Id: compress-sess,v 1.3 2007/01/09 22:41:16 nicks Exp $';

set inputargs = ($argv);

set motioncor = 0;
set raw = 1;
set fsd = bold;
set fstem = f;
set compress = 1;
set decompress = 0;
set nolog = 0;
set delete = 1;
set overwrite = 1;

set n = `echo $argv | grep version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

goto parse_args;
parse_args_return:

set SessList = `getsesspath $inputargs`;
if($status) then
  echo "$SessList"
  exit 1;
endif

goto check_params;
check_params_return:

## Look for nolog option ##
set n = `echo $inputargs | grep nolog | wc -l` 
if($n != 0) set nolog = 1;

##### Create a log file ######
if(! $nolog) then
  set logdir = `pwd`/log;
  mkdir -p $logdir
  if(! -e $logdir) then
    echo "ERROR: could not create $logdir"
    exit 1;
  endif
  set LF = $logdir/compress-sess.log
  if(-e $LF) mv $LF $LF.old
else
  echo "No log file"
  set LF = /dev/null
endif

echo "compress-sess Logfile is $LF"

echo "compress-sess log file" >> $LF
echo $VERSION >> $LF
id            >> $LF
pwd           >> $LF
echo "$0"     >> $LF
echo $inputargs  >> $LF
uname -a      >> $LF
date          >> $LF

if($motioncor) set fstem = fmc;

set err  = 0;
set warn = 0;

foreach sess ($SessList)
  set sessid = `basename $sess`;
  echo $sess |& tee -a $LF

  set runlist = `getrunlist $sess/$fsd`;
  if($#runlist == 0) then
    echo "INFO: $sess has no runs ... continuing" |& tee -a $LF
    set err = 1;
    continue;
  endif

  foreach run ($runlist)
    echo "$sessid $run ---------------------------" |& tee -a $LF
    date |& tee -a $LF
    pwd |& tee -a $LF
    df . |& tee -a $LF

    set rundir = $sess/$fsd/$run
    pushd $rundir > /dev/null
    set tarfile  = $fstem.tar
    set tarzfile = $tarfile.gz

    #-------------------------------------------------------------------#
    if($compress) then

      # make sure that the input volume is ok #
      bfvcheck $fstem;
      if($status) then
        echo "ERROR: $sessid $run : there's something wrong with volume $fstem"\
             |& tee -a $LF
        set err = 1;
        continue;
      endif

      # check whether the tarfile exists or not #
      if(-e $tarzfile) then
        echo -n "WARNING: $sessid $run $tarzfile already exists ..." |& tee -a $LF
        if(! $overwrite) then
          echo "skipping" 
          set warn = 1;
          continue;
        else
          echo "overwriting" 
        endif
      endif

      # tar data #
      tar Wcvf $tarfile $fstem\_???.* |& tee -a $LF
      if($status) then
        echo "ERROR: $sessid $run : problem tarring" |& tee -a $LF
        set err = 1;
        continue;
      endif

      # compress data #
      echo "Compressing ..."
      gzip $tarfile
      if($status) then
        echo "ERROR: $sessid $run : problem compressing" |& tee -a $LF
        set err = 1;
        continue;
      endif

      # delete the old volume #
      if($delete) rm $fstem\_???.* |& tee -a $LF

    endif #-------- end compress --------#

    #-------------------------------------------------------------------#
    if($decompress) then

      # check that the tarred/zipped file is there #
      if(! -e $tarzfile) then
        echo "ERROR: $sessid $run $tarzfile does not exist" |& tee -a $LF
        set err = 1;
        continue;
      endif

      # make sure the target volume is NOT there #
      bfvcheck $fstem;
      if(! $status) then
        echo -n "WARNING: $sessid $run : $fstem volume already exists..."|& tee -a $LF
        if(! $overwrite) then
          echo "skipping"
          set warn = 1;
          continue;
        else
          echo "overwriting"
        endif
      endif

      # detar the unzipped tar file #
      tar zxvf $tarzfile |& tee -a $LF
      if($status) then
        echo "ERROR: $sessid $run : problem decompressing/untarring" |& tee -a $LF
        set err = 1;
        continue;
      endif

      # verify that the output volume is ok #
      bfvcheck $fstem;
      if($status) then
        echo "ERROR: $sessid $run : stem $fstem failed check" |& tee -a $LF
        set err = 1;
        continue;
      endif

      if($delete) rm $tarzfile

    endif #-------- end decompress --------#

    popd > /dev/null;
  end # Loop over runs 

end # Loop over sessions

date | tee -a $LF
echo " "
if($err)  echo "compress-sess completed with errors" | tee -a $LF
if($warn) echo "compress-sess completed with warnings" | tee -a $LF
if($err == 0 && $warn == 0) then
  echo "compress-sess completed SUCCESSFULLY" | tee -a $LF
endif
echo " "

exit 0;
###############################################

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

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

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

    case "-umask":
      if ( $#argv == 0) goto arg1err;
      umask $argv[1]; shift;
      breaksw

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

    case "-compress":
      set compress = 1;
      set decompress = 0;
      breaksw

    case "-decompress":
    case "-uncompress":
      set compress = 0;
      set decompress = 1;
      breaksw

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

    case "-nodelete":
      set delete = 0;
      breaksw

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

    case "-nooverwrite":
      set overwrite = 0;
      breaksw

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

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

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

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


    case "-nolog"
      breaksw

    case "-cwd"
      set IsSess = 1;  # otherwise, ignore getsesspath arguments 
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      set IsSess = 1;  # otherwise, ignore getsesspath arguments 
      shift;
      breaksw

    default:
      echo ERROR: Flag $flag unrecognized. 
      echo $cmdline
      exit 1
      breaksw
  endsw

end

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

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

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

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

############--------------##################
usage_exit:
  echo "USAGE: compress-sess"
  echo "Options:";
  echo "   -compress    : compress data"
  echo "   -decompress  : decompress data"
  echo "   -raw : compress raw data"
  echo "   -motioncor : compress motion corrected raw data"
  echo "   -nodelete    : do not delete data after compressing "
  echo "   -nooverwrite : do not force overwrite"
  echo "   -fsd fsd : functional subdirectory"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo "   -version       : print version and exit"
  echo "   -umask umask   : set unix file permission mask"
exit 1;
