#! /bin/csh -f

#
# getrunlist - can be run in two ways:
#
# (1) without runlistfile - finds all the subdirectories 
#     of dir with name of the form %03d and echos them 
#     to stdout. If dir does not exist or there are no
#     runs, exits with status 1. 
#
# (2) with runlistfile - opens the run list file, reads
#     the runs, and checks that all runs exist in dir.
#     If dir does not exist or all the runs do not exist,
#     exits with status 1.
# 
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2010/04/06 18:33:23 $
#    $Revision: 1.6 $
#
# 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
#


if($#argv != 1 && $#argv != 2) then
  echo "USAGE: getrunlist dir <runlistfile>"
  exit 1;
endif

set dir = $argv[1];
if(! -d $dir) then
  echo "ERROR: $dir does not exist"
  exit 1;
endif


if($#argv != 2) then
  # This is the new, fast way to do it
  pushd $dir > /dev/null
  set RunList = (`find -maxdepth 1 -name "[0-9][0-9][0-9]"`);
  if($#RunList == 0) then
    echo "ERROR: no run directories found"
    exit 1;
  endif
  set RunList = (`ls -d $RunList`); # sort by run number
  echo $RunList | sed 's/.\///g'
  exit 0;
endif

if(0 && $#argv != 2) then
  # This is the old, slow way to do it
  set RunList = ();
  set run = 1;
  @ nohit = 0;
  while($nohit < 300)
    set runid = `printf %03d $run`;
    if( -d $dir/$runid ) then
      set RunList = ($RunList $runid);
      @ nohit = 0;
    else
      @ nohit = $nohit + 1;
    endif
    @ run = $run + 1;
  end

  if($#RunList == 0) then
    echo "ERROR: no run directories found"
    exit 1;
  endif

  echo $RunList;
  exit 0
endif

# Only gets here if a runlistfile was specified

set rlf = $dir/$argv[2];
if(! -e $rlf) then
  echo "ERROR: $rlf does not exist"
  exit 1;
endif

set RunList = `cat $rlf`;
foreach run ($RunList)
  if(! -e $dir/$run) then
    echo "ERROR: run $run from $rlf does not exist"
    exit 1;
  endif
end
echo $RunList;

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