#! /bin/csh -f

#
# functcvm-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:17 $
#    $Revision: 1.2 $
#
# 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 inputargs = ($argv);
set VERSION = '$Id: functcvm-sess,v 1.2 2007/01/09 22:41:17 nicks Exp $';

set SessList = ();
set fsd = "bold";
set funcstem = "f"; # stem of functional volume
set rlf = ();
set bmask = ();
set bmaskmatch = 1;
set outsuffix = ();
set outdir = ();
set collapse = 0;
set monly = 0;

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

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

set PWDCMD = `getpwdcmd`;

set SessList = `getsesspath $argv`;
if($status || $#SessList == 0) then
  echo $SessList
  exit 1;
endif

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

set StartTime = `date`;

# Create a log file #
if(-w .) then
  mkdir -p log
  set LF = `$PWDCMD`/log/functcvm-sess-$fsd.log
  rm -f $LF
else
  set LF = /dev/null
endif

echo "functcvm-sess" >> $LF
echo $VERSION     >> $LF
uname -a          >> $LF
date              >> $LF
$PWDCMD           >> $LF
echo $inputargs   >> $LF

if($monly) then
  set QuitOnError = 0;
else
  set QuitOnError = 1;
  set MLF = functcvm_sess_$$.m
endif
rm -f $MLF
echo "Matlab file is $MLF"

if($#outdir != 0) then
  mkdir -p $outdir
  pushd $outdir > /dev/null
  set outdir = `$PWDCMD`;
  popd > /dev/null
endif

#----------------------------------------------------------------#
tee $MLF <<EOF

  global QuitOnError;
  QuitOnError = $QuitOnError;
  SessList = splitstring('$SessList');
  funcstem = '$funcstem';
  fsd = '$fsd';
  rlf = '$rlf';
  bmasksessstem = '$bmask';
  bmaskmatch = $bmaskmatch;
  outsuffix = '$outsuffix';
  outdir    = '$outdir';
  collapse  = $collapse;

  tic;
  nsessions = size(SessList,1);
  %---------------------- Session Loop ----------------------------%
  for nthsess = 1:nsessions
    sesspath = deblank(SessList(nthsess,:));
    sessid = basename(sesspath);
    fprintf('%3d/%d %s %g\n',nthsess,nsessions,sessid,toc);

    if(~isempty(bmasksessstem))
      bmaskstem = sprintf('%s/%s/mask/%s',sesspath,fsd,bmasksessstem);
      bmask = fmri_ldbvolume(bmaskstem);
      if(isempty(bmask)) 
        qoe(bmaskfullstem); 
        error(bmaskfullstem); 
      end
      nbmasktot = length(find(bmask == bmaskmatch));
      if(nbmasktot == 0) 
        msg = sprintf('No active voxels found in bmask');
        qoe(msg); error(msg);
      end
      fprintf('nbmask = %d\n',nbmasktot);
    else
      bmask = [];
      bmaskstem = [];
    end

    if(~isempty(outdir))
      outfile = sprintf('%s/%s-%s-%s-%s',outdir,sessid,funcstem,outsuffix);
    else
      outfile = sprintf('%s/%s/%s-%s',sesspath,fsd,funcstem,outsuffix);
    end
    fprintf('outfile = %s\n',outfile);

    if(isempty(rlf))
      fsdpath = sprintf('%s/%s',sesspath,fsd);
      runlist = fast_runlist(fsdpath);
    else
      rlfpath = sprintf('%s/%s/%s',sesspath,fsd,rlf);
      runlist = fast_runlistfile(rlfpath);      
    end
    nruns = size(runlist,1);

    %----------------------- Row Run Loop -------------------------%
    instem_perrun = [];
    ntrs_perrun = [];
    globalmean_perrun = [];
    for ithrun = 1:nruns

      runid1 = deblank(runlist(ithrun,:));
      instem1 = sprintf('%s/%s/%s/%s',sesspath,fsd,runid1,funcstem);
      [nslices nrows ncols ntrs endian bext] = fmri_bvoldim(instem1);
      nvslice = nrows*ncols;

      fprintf('Loading Run %s (%d/%d)  %g\n',runid1,ithrun,nruns,toc);
      f1vol = fmri_ldbvolume(instem1);
      if(isempty(f1vol))
        msg = sprintf('ERROR: reading %s\n',instem1);
        qoe(msg); error(msg);
      end

      if(ithrun == 1) tcvm = zeros(ntrs*nruns); end
      instem_perrun = strvcat(instem_perrun,instem1);
      ntrs_perrun = [ntrs_perrun ntrs];
      globalmean = mean(reshape1d(f1vol));
      globalmean_perrun = [globalmean_perrun globalmean];

      %--------------- Column Run Loop -------------------------%
      for jthrun = ithrun:nruns
        runid2 = deblank(runlist(jthrun,:));
        fprintf('XRUN: %s ',runid2);
        instem2 = sprintf('%s/%s/%s/%s',sesspath,fsd,runid2,funcstem);

          %---------------- Slice Loop -------------------------------%
          tcvmtmp = 0;
          for nthslice = 0:nslices-1
            fprintf('%2d ',nthslice);

            % fname1 = sprintf('%s_%03d.%s',instem1,nthslice,bext);
            % f1 = fmri_ldbfile(fname1);
            % if(isempty(f1))
            %   msg = sprintf('ERROR: reading %s\n',fname1);
            %   qoe(msg); error(msg);
            % end
            f1 = squeeze(f1vol(nthslice+1,:,:));
            f1 = reshape(f1,[nvslice ntrs])'; %'

            if(ithrun ~= jthrun)
              fname2 = sprintf('%s_%03d.%s',instem2,nthslice,bext);
              f2 = fmri_ldbfile(fname2);
              if(isempty(f2))
                msg = sprintf('ERROR: reading %s\n',fname2);
                qoe(msg); error(msg);
              end
              f2 = reshape(f2,[nvslice ntrs])'; %'
            else
              f2 = f1;
            end

            if(~isempty(bmask))
              ibmask = find(squeeze(bmask(nthslice+1,:,:)==bmaskmatch));
              nbmask = length(ibmask);
              f1 = f1(:,ibmask);
              f2 = f2(:,ibmask);
            else
              nbmask = nvslice;
            end

            if(nbmask > 0)
              tcvm_slice = f1 * f2'; %'
              tcvmtmp = tcvmtmp + tcvm_slice;
            end

          end %---------- Slice Loop ---------------------%
          fprintf('\n');

          % Makes it easier to fill in the other side %
          if(ithrun ~= jthrun) tcvmtmp = 2*tcvmtmp;  end

          r0 = ntrs * (ithrun-1) + 1;
          r1 = r0 + ntrs - 1;
          c0 = ntrs * (jthrun-1) + 1;
          c1 = c0 + ntrs - 1;
          tcvm(r0:r1,c0:c1) = tcvmtmp;

      end %---------- Run Loop 1 ---------------------%
      fprintf('\n');

    end %---------- Run Loop 2---------------------%

    % Fill in the other values so that tcvm is symmetical %
    % This step requires tcvmtmp = 2*tcvmtmp for i ~= j
    tcvm = (tcvm + tcvm')/2; %'

    save(outfile,'tcvm','nruns','instem_perrun',...
         'ntrs_perrun','globalmean_perrun',...
         'sesspath','fsd','runlist','funcstem','bmasksessstem',...
         'bmaskstem','bmask','bmaskmatch');

  end %----------- Session Loop ------------------%

  fprintf('matlab done (run time = %g min)\n',toc/60);
EOF
#----------------------------------------------------------------#

if(! $monly ) then
  cat $MLF | matlab -display iconic | tee -a $LF
  rm -f $MLF
endif

echo " "
echo "StartTime: $StartTime"
echo "EndTime:   `date`"
echo " "


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


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

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

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

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

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

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

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

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

    case "-nocollapse":
      set collapse = 0;
      breaksw

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

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

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

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

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

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

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

    case "-g":
    case "-s":
    case "-sf":
    case "-d":
    case "-df":
      shift;
      # ignore getsesspath arguments 
      breaksw

    case "-cwd":
      # ignore getsesspath arguments 
      breaksw

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

end

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

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

  if($#outsuffix == 0) then
    echo "ERROR: must spec output suffix (-os)"
    exit 1;
  endif

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: functcvm-sess"
  echo "   -os outputsuffix   : output suffix"
  echo ""
  echo " Options"
  echo "   -funcstem stem     : <f>   "
  echo "   -fsd      dir      : <bold>"
  echo "   -rlf runlistfile   : default is to use all runs  "
  echo "   -bmask     stem    : binary mask stem found in fsd/mask"
  echo "   -bmaskmatch val    : use voxels where bmask=val (def: val=1)"
  echo ""
  echo "   -od outputdir      : save as outdir/sessid-fstem-fsd-outsuf"
  echo ""
  echo "   -umask umask       : set unix file permission mask"
  echo "   -version           : print version and exit"
  echo ""
  echo "Session Arguments (Required)"
  echo "   -sf sessidfile  "
  echo "   -df srchdirfile "
  echo "   -s  sessid      "
  echo "   -d  srchdir     "
  echo ""
exit 1;

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

