#! /bin/csh -f
set pn = "recombine"

set tempdir = ""
set cleanlist = ""
set newstcom = "recombine.$$"
if ($?IMOD_DIR) then
    setenv PATH "$IMOD_DIR/bin:$PATH"
endif

if ($#argv == 0)then
    echo "This program recombines files split apart with Splitmrc"
    echo "Usage: $pn [-d directory_for_temporary_files]  split_list_file"
    exit 0
endif

while ($#argv > 1)
  switch ($argv[1])
    case -d:
      set tempdir = $argv[2]"/"
      if (! (-d $tempdir))then
	echo "${pn}: Directory $tempdir does not exist"
	exit 1
      endif
      shift; shift
      breaksw
    default:
      echo "${pn}: bad argument $argv[1]"
      exit 1
  endsw
end
if ($#argv == 0) then
    echo "${pn}: need to enter a split list file"
    exit 1
endif
if (! -e $argv[1])then
  echo "${pn}: input split list file $argv[1] does not exist"
  exit 1
endif

echo "This program will recombine files split apart by Splitmrc"
echo "Type Ctrl-C and Return to interrupt when it is waiting for input."
echo " "
echo  "Enter your command for ejecting the CD, or Return if you are not"
echo -n " taking files from CDs: "

set ejectcom = $<

set splitlist = `cat $argv[1]`
@ nfiles = $splitlist[1]
shift splitlist

# set up default source directory as directory where list file is
set srcdir = $argv[1]:h
if ($srcdir == $argv[1]) then
    set srcdir = '.'
endif

onintr clean

echo $nfiles >! $newstcom
while ($nfiles > 0)

    set fileok = 0
    echo "Insert new CD if necessary before answering the next question"
    while ($fileok == 0)
	echo -n "Source directory for file $splitlist[1] (Return for $srcdir): "
	set srcin = $<
	if ($srcin != "") then
	    set srcdir = $srcin
	endif

	set srcfile = $srcdir/$splitlist[1]
	@ ncheck = 0
	while ($fileok == 0 & $ncheck < 16)
	    if (-e $srcfile) then
		set fileok = 1
	    else
		@ ncheck++
		sleep 1
	    endif
	end
	if ($fileok == 0) then
	    echo "$srcfile not found; check CD or directory name and try again"
	endif
    end

    if ($nfiles > 1) then
	# If it's not last file, copy it to temporary location and eject CD
	set tmpfile = $tempdir$splitlist[1].$$
	set cleanlist = ($cleanlist $tmpfile)
	echo "Copying to temporary file..."
	\cp $srcfile $tmpfile

	# eject the disk
	if ("$ejectcom" != "") then
	    echo "Ejecting disk..."
	    $ejectcom
	endif
    else
	# otherwise, for last file, set name to read it directly
	set tmpfile = $srcfile
    endif

    # add file to newstack command, maintain end of loop
    echo $tmpfile >> $newstcom
    echo $splitlist[2] >> $newstcom
    shift splitlist ; shift splitlist
    @ nfiles--
end

# Finish the newstack input file and run it

set tailname = $argv[1]:t
set outname = $tailname:r
cat >> $newstcom <<EOF
1
$outname
/
/
0
0
0
EOF
echo "Recombining..."
newstack < $newstcom > /dev/null

clean:
\rm -f $newstcom $cleanlist
