#!/bin/ksh
. ./settings.ksh
#-------------------------------------------------------------------
# Function: extract11
#
# Purpose:  Called when user clicks Start button during MoJoe extract process.
#
#-------------------------------------------------------------------
#===================================================================
# C H A N G E   L O G
#
# BAS   03/30/04   Changed to call lx_ximg.
# BAS   04/16/04   Changed to remotely run autoimgsort_lx instead of autolocsort_x.
# BAS   04/23/04   Added "rm -f $locdir" at end so don't fill up scanner with junk
# BAS   05/20/04   Changed call from autoimagesort_lx to autolocsort_lx for consistency.
# BAS   06/07/04   Changed to call wfu_cmd_ge_to_analyze.
# BAS   06/18/04   Changed so will accept a series even if gen_timestamp = 0.
# KLP   10/04/04   Changed to call Perl "lookup11" function to get patient and series lists
#
# KLP   11/05/04   Added routines for IDE CD-RW controller;
#	           inserted burnproof test where cdrecord is first defined;
#                  redirected all cdrecord STDERR messages not previously
#		   saved to /dev/null to prevent feedback in start-up window
#       
# KLP   06/06/06   send through kip instead of relito;
#                  reference /ansir2/fmri instead of /fmri2/fmri
#                  reference dicom scripts in dicom subdirectory
#                  reference monkey program in Monkey subdirectory
#
# KLP   07/18/06   changed /ansir2/fmri references back to /fmri2/fmri
# KLP   08/29/06   added note about exiting on ftp check error
# KLP   10/31/06   save infofile for monitor
# KLP   12/28/06   cut patient list in a different location to allow for dates
# KLP   01/12/07   ssh/scp
# KLP   01/18/07   look for CD-R, not CD-RW, in cdrecord -checkdrive response
# KLP   01/31/07   add numerous checkdrive tries before giving warning
# KLP   02/02/07   add check for zipping extract tar file
# KLP   02/05/07   write zipped tar file to CD
# KLP   02/06/07   add billing info from DICOM headers in tabular format
# KLP   05/08/07   send lines from psd_syserr.log plus all config logs
# KLP   05/21/07   send serieslist log
# KLP   06/15/07   increase from 500 to 1000 lines sent from psd_syserr.log
# KLP   07/11/07   allow patient label date not TODAY if MOJOE_DATE set
# BCW   10/15/07   send 1000 lines from gesys_*.log to config dir
# BCW	  10/06/08   copy /usr/g/service/gating to patientDiir/gating
# BCW		12/17/08	 Added settings.ksh and abstracted embeded setttings
#===================================================================
#
#===================================================================
# IDE CD-RW controller routines KLP 11/05/04
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# when CD is blank, cdrecord command with IDE controller reports 
#    "Cannot read TOC header"
#
function ide_cd_blank {
cd_blank=0
blank=`$cdrecord dev=$cdr -toc 2>&1 | grep 'Cannot read TOC header' `
if (test ${#blank} -gt 0) then
        cd_blank=1
fi
}
#-------------------------------------------------------------------
# if and only if CD is not blank and CD is not locked,
# cdrecord command with IDE controller reports
# "first,last" track msinfo
#
function ide_cd_appendable {
track1=0
track2=0
ide_cd_blank
if (test $cd_blank -ne 1) then
	tracks=`$cdrecord dev=$cdr -msinfo 2>/dev/null`
	lines=`echo $tracks | wc -l`
	if (test $lines -eq 1) then
		comma=`echo $tracks | grep ','`;
		if (test ${#comma} -gt 0) then
			track1=`echo $tracks | tr ',' ' ' | awk '{print $1}'`
			track2=`echo $tracks | tr ',' ' ' | awk '{print $2}'`
			if (test $track2 -lt $track1) then
				track1=0
				track2=0
			fi
		fi
	fi
fi

cd_first_sector=$track1
cd_last_sector=$track2
cd_appendable=0
if (test $track1 -ge 0) then
    if (test $track2 -gt $track1) then
	cd_appendable=1
    fi
fi
}
#-------------------------------------------------------------------
#-------------------------------------------------------------------

#-------------------------------------------------------------------
#command arguments retrievment
#felix added for retrieve command line arguments
#usage: extract1 -R[remotedir] -D[path] -L[label] exam# ser#1 ser#2 nocd noftp lessjoe
#       path store in destpath
#       label store in destlabel
#       lessjoe use lessjoe working directory and filenames
#example: extract1 -Dbschiffm -C "1,6,0" -L272af 838 1 2 nocd
#-------------------------------------------------------------------
Rflag=
Dflag=
Lflag=
Mflag=

#------------------------
#cdr_controller=1
#cdr_scsi_id=6
#cdr_target=0
#------------------------
Cval=1
Ival=6
Tval=0


   while getopts R:D:L:M:C:I:T name
   do
     case $name in
       R) Rflag=1
       	  Rval="$OPTARG";;
       D) Dflag=1
       	  Dval="$OPTARG";;
       L) Lflag=1
          Lval="$OPTARG";;
       M) Mflag=1
	  Mval="$OPTARG";;
       C) Cflag=1
       	  cdline="$OPTARG"
 	  cdline=`echo $cdline | 	tr ',' ' '`
	  Cval=`echo $cdline | awk '{print $1}' `
          Ival=`echo $cdline | awk '{print $2}' `	
          Tval=`echo $cdline | awk '{print $3}' `;;    
       ?) printf "Usage: %s: [-D path] [-L label] args\n" $0
          exit 2;;
     esac
   done

    destpath=$Dval
    destlabel=$Lval    
    destemail=$Mval
    cdr_controller=$Cval
    cdr_scsi_id=$Ival
    cdr_target=$Tval
    

    if (test ${#destpath} -eq 0) then gui=0; else gui=1; fi
    shift `expr $OPTIND - 1`

#end of felix add---------------------------------------------------

flagextracting=`ps -e |grep fmriarch1 | wc -l`

#echo flag:$flagarchiving

if (test $flagextracting -gt 1) then
    echo "extract script is already running..."
    exit 1
fi

#echo
#echo
#echo "  EXTRACT:  A Utility to Extract a Whole Exam or Selected Series to DAT or CDR"
#echo "                         DICOM version                          "
#echo "             Courtesy of Joe Maldjian and John Listerud         "
#echo "             syntax:  extract examnumber [series list] [-nq]  "
#echo  "  To extract an entire exam:	extract exam#         "
#echo  "  To extract a series:		extract exam# series# "
#echo  "  To extract multiple series:	extract exam# series1 series2 series3 ... " 
#echo  "  Options:                        notape    do not write to tape  "
#echo  "                                  q    quiet (fewer messages)  "
#echo  "Autoftp and autolocsort implemented"
#echo  "Autohardware detection of tape device and CDR implemented" 
#echo "***********************************************************************"
#NOTE: if debugging on SunOs use /usr/xpg4/bin/sh or /bin/ksh

#-------------------------------------------
#Begin User edit Section
#-------------------------------------------
#--------------------------------------------------
#autoftp and autorecon settings
#Edit the ftp_check file for site specific settings
#regarding remote host and ftp directories
#--------------------------------------------------
ftpflag=1
reconflag=1

#--------------------------------------------------
#Configuration Settings and Checkking
#--------------------------------------------------
mojoe_dir=$MOJOE_DIR
if (test ${#mojoe_dir} -lt 1)
    then
    mojoe_dir=$HOME/mojoe
fi

if [[ ${#fmri_dir} -eq 0 ]]; then
	fmri_dir=/fmri2/fmri
fi

if [[ ${#bin_dir} -eq 0 ]]; then
	bin_dir=/raid/neuro/bin
fi

if [[ ${#sshserver} -eq 0 ]]; then
	sshserver=152.11.158.50
fi

if [[ ${#sshuser} -eq 0 ]]; then
	sshuser=fmri
fi

    
#--------------------------------------------------
#CD-R settings
#--------------------------------------------------
cdrflag=1
cdr_speed=16
lookup=$mojoe_dir/lookup11
cdr_dir=$mojoe_dir/CDRECORD
burnproof=1
hinvdetect=0

#-------------------------------------------
#Setup the lessjoe directory
#-------------------------------------------
lessjoe=`echo $@ | awk '/lessjoe/{print}' `
if (test ${#lessjoe} -ne 0) 
  then 
    echo 'lessjoe';
    mojoe_dir=$mojoe_dir/lessjoe_working
    MOJOE_DIR=$mojoe_dir/lessjoe_working
    export MOJOE_DIR
fi
#-------------------------------------------
#End setup of lessjoe directory
#-------------------------------------------



#-------------------------------------------
#END User edit Section
#DO NOT EDIT BELOW THIS LINE
#-------------------------------------------

#-------------------------------------------------------------
#tapearchive flag
#No need to edit this line since we are now
#using hardware autodetection to test if there is a tape device
#--------------------------------------------------------------
tapearchive=0
multi=`echo -multi`

#-------------------------------------------------------------
#executable definitions
#--------------------------------------------------------------
autoftp=$mojoe_dir/autoftp
imenu=$mojoe_dir/imenu
remote_launch=$mojoe_dir/remote_launch
ftp_check=$mojoe_dir/ftp_check1
read_ximg_header=$mojoe_dir/read_ximg_header
read_ge_ls_header=$mojoe_dir/read_ge_ls_header
read_dcm_header=$mojoe_dir/dicom/read_dcm_header
read_dcm_biller=$mojoe_dir/dicom/read_dcm_biller
###read_dcm_header=$mojoe_dir/infodcm

#-------------------------------------
#monkey
#-------------------------------------
monkey=$mojoe_dir/Monkey/monkey


#--------------------------------------------------
#CD-R settings
#Hardware autodetect in effect for CDR
#--------------------------------------------------
cdr=`echo $cdr_controller,$cdr_scsi_id,$cdr_target`
#isoflags=`echo -pad -R -l -L -allow-multidot -allow-lowercase `
isoflags=`echo -R -l -L -allow-multidot -allow-lowercase `
###if (test $burnproof = 1) then driveropts=`echo driveropts=burnproof` ; else driveropts=''; fi # KLP 11-05-04

cdrarchive=1
cdrecord=$cdr_dir/cdrecord
mkisofs=$cdr_dir/mkisofs

### KLP 11-05-04 burnproof test must be inserted here after cdrecord path is set
if (test $burnproof = 1) then
    burntest=`$cdrecord dev=$cdr -prcap 2>/dev/null | grep "Does support BURN-Proof"`
    if (test ${#burntest} -eq 0) then burnproof=0; fi
    fi
if (test $burnproof = 1) then driveropts=`echo driveropts=burnproof` ; else driveropts=''; fi
###

#--------------------------------------------------
#If this is a remote login, disable tape and CD writing
#-------------------------------------------------
if (test $gui = 0) then
    if (test $REMOTEHOST) then 
	tapearchive=0 
	cdrflag=0
    fi

else

    gui=1
    echo $destpath
    echo $destlabel
    awk=`echo awk`
    #------------------------------------------
    #Check the ftp option
    #------------------------------------------
    noftp=`echo $@ | $awk '/noftp/{print}' `
    if (test ${#noftp} -eq 0) then echo 'ftp'; else echo 'noftp'; fi

    #------------------------------------------
    #Check the CD option
    #------------------------------------------
    nocdwrite=`echo $@ | $awk '/nocd/{print}' `
    if (test ${#nocdwrite} -eq 0) then echo 'cd ('$cdr_controller','$cdr_scsi_id','$cdr_target')'; else echo 'nocd ('$cdr_controller','$cdr_scsi_id','$cdr_target')' ; fi
    echo $destemail
fi

#-------------------------------------------
#LX tape and blocking factor definitions
#-------------------------------------------
tapedev=/dev/nrtape
bf=512
lxflag=1
#for 5.x use /dev/nrst8 and a blocking factor of 96

helpflag=0
if (test $# -eq 0) then helpflag=1; fi
if (test $# -gt 0) then
    if (test $1 = ?) then helpflag=1; fi
fi

ftp_failed=0

mkisofs_loop  ()  {
	successful_mkisofs=0
	mkisofs_counter=0	
	while (test $successful_mkisofs -eq 0) 
	do
		let mkisofs_counter=mkisofs_counter+1
		here=`pwd`
		cd $outputdir
#		if (test $multiflag = 0) then
#			$mkisofs -o $cdimage  $isoflags $allpfiles >> $quiet 2>>$quiet
#			else
#			$mkisofs -o $cdimage $isoflags -C $startsector,$endsector -M $cdr $allpfiles >>$quiet 2>>$quiet
#		fi
# must use a 31-char max CD file name
#
                #cp -p $tarfile $cdtarfile
                ln $tarfile $cdtarfile
		if (test $multiflag = 0) then
			$mkisofs -o $cdimage  $isoflags $cdtarfile >> $quiet 2>>$quiet
			else
			$mkisofs -o $cdimage $isoflags -C $startsector,$endsector -M $cdr $cdtarfile >>$quiet 2>>$quiet
		fi
                rm -rf $cdtarfile
#
                cd $here
		if (test -a $cdimage) then 
			successful_mkisofs=1
			break
		fi
		echo MKISOFS PROBLEM....TRYING TO RECOVER >> $quiet
		reply=`$cdrecord dev=$cdr -reset 2>/dev/null`
		echo $reply >> $quiet

		reply=`$cdrecord dev=$cdr -eject 2>/dev/null`
		echo $reply >> $quiet

		reply=`$cdrecord dev=$cdr -load 2>/dev/null`
		echo $reply >> $quiet

		if (test $mkisofs_counter -gt 2)  then 
			echo 'Unable to recover from mkisofs error'
			echo "CDR write error, data not saved to CD!!!!! "
			echo "raw file "$pfile" renamed to "$pfilen" may be corrupted on CD"
			echo "FTP will continue"
			echo 'Unable to recover from CD error' >> $quiet
			echo "raw file "$pfile" renamed to "$pfilen" may be corrupted on CD" >> $quiet
			echo "FTP will continue"  >> $quiet
			if (test $ftpflag = 1)  then 
				$autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $log_filename >/dev/null 2>/dev/null
				$autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $log_mojoe >/dev/null 2>/dev/null
			fi
		break
		fi

 	done	
}









#dbaccess - << EOF > tmpfile$$ 2>&1
#database ctmr_sdc_db;
#select F.d_study_id, P.PATIENT_NAME 
#FROM PATIENT_FOLDER P, EXAMINATION_FOLDER F
#where  P.patient_id = F.patient_id
#Group by f.d_study_id, P.Patient_name
#EOF
#--$lookup -P
###cat patients.txt >tmpfile$$
#--sort -nro tmpfile$$ $mojoe_dir/patients.txt
#patient_list=`cat tmpfile$$ | awk '/patient_name/{$1="";print}'  | tr ' ' '_' `
#exam_list=`cat tmpfile$$ | awk '/d_study_id/{$1="";print}' `
#--patient_list=`cat tmpfile$$ | cut -c7-37`
#--exam_list=`cat tmpfile$$ | cut -c1-5`
#--rm tmpfile$$
$mojoe_dir/dicom/gen1
# KLP 12-28-06 patient_list=`cut -c7- < $mojoe_dir/patientlist`
patient_list=`cut -c26- < $mojoe_dir/patientlist`
exam_list=`cut -c1-5 < $mojoe_dir/patientlist`
if (test $helpflag -eq 1) then
    echo
    echo
    echo "***********************************************************************"
    cnt=1
    echo  "exam patient" | awk '{printf("%5s %30s \n", $1, $2)}'
    echo  "------   -------------" | awk '{printf("%5s %30s \n", $1, $2)}'
    for i in $exam_list
    do
#      	patient_name=`echo $patient_list | awk -v index=$cnt '{print $index }'  `	
       	patient_name=`echo $patient_list | cut -d' ' -f$cnt`	
       	echo $i	$patient_name | awk '{printf("%5s %30s \n", $1, $2 )}'
       	cnt=`expr $cnt + 1`
    done
    echo "***********************************************************************"
    echo
    echo
fi

echo "***********************************************************************"
echo "  EXTRACT:  A Utility to Extract a Whole Exam or Selected Series to DAT"
echo "                         DICOM version                          "
echo "             Courtesy of Joe Maldjian and John Listerud         "
if (test $gui = 0) then
echo "             syntax:  extract examnumber [series list] [-nq]  "
echo "  To extract an entire exam:	extract exam#         "
echo "  To extract a series:		extract exam# series# "
echo "  To extract multiple series:	extract exam# series1 series2 series3 ... " 
echo "  Options:                       [notape nocd noftp norecon]   "
fi
echo "***********************************************************************"

if (test $helpflag -eq 1) then exit; fi

startdir=`pwd`

#------------------------------------------
#Check the autoftp connection
#------------------------------------------
noftp=`echo $@ | awk '/noftp/{print}' `
if (test ${#noftp} -eq 0) then noftp=0; else ftpflag=0; fi

#------------------------------------------
#Check the close cd option
#------------------------------------------
closecd=`echo $@ | awk '/closecd/{print}' `
if (test ${#closecd} -eq 0) then closecd=0; else closecd=1; fi

#------------------------------------------
#Check the norecon flag
#------------------------------------------
norecon=`echo $@ | awk '/norecon/{print}' `
if (test ${#norecon} -eq 0) then norecon=0; else reconflag=0; fi

#-------------------------
#Initialize logfile
#-------------------------
logdir=$mojoe_dir
echo $mojoe_dir
lessjoe=`echo $@ | awk '/lessjoe/{print}' `
if (test ${#lessjoe} -eq 0) 
  then 
    log_filename=extract.log
    log_mojoe=mojoe_extract.log
    info_mojoe=mojoe_extract.sinfo
  else
    log_filename=extract.log
    log_mojoe=lessjoe_extract.log
    info_mojoe=lessjoe_extract.sinfo
fi

logfile=$logdir/$log_filename
infofile=$logdir/$info_mojoe

#logfilemojoe=$logdir/$log_mojoe

echo 'logfile for extract' > $logfile
echo `date` >> $logfile
echo `echo called as:  extract $@` >> $logfile
echo '' >> $logfile

#-------------------------
#sequence service log
#-------------------------

#servicedir=/usr/g/service/log
servicedir=$MOJOE_SERVICE
if (test ${#servicedir} -lt 1)
    then
    servicedir=/usr/g/service/log
fi
servicelog=review.out
newservicelog=review.out_extract

debugflag=`echo $@ | awk '/debug/{print}' `
if (test ${#debugflag} -eq 0) then debugflag=0; else debugflag=1; fi
if (test $debugflag = 1) then quiet=''; else quiet=$logfile; fi

if (test $ftpflag = 1) then
   # if (test ${#destpath} -eq 0) then
    if (test $gui -eq 0) then
	$ftp_check w
        #interactive
    else
        $ftp_check -R$Rval -D$destpath -L$destlabel -m w
        #script called from gui
    fi
    reply=`cat $mojoe_dir/secretpassword`
    rm $mojoe_dir/secretpassword
    ftpflag=`echo $reply | awk '{print $2}' `
    error_code=`echo $reply | awk '{print $3}'`
    remotehost=`echo $reply | awk '{print $4}'`
    remotehostname=`echo $reply | awk '{print $5}'`
    user=`echo $reply | awk '{print $6}'`
    pass=`echo $reply | awk '{print $7}'`
    remotedir=`echo $reply | awk '{print $8}'`
    avail=`echo $reply | awk '{print $9}'`
    idlhostname=`echo $reply | awk '{print $10}'`
    idlhost=`echo $reply | awk '{print $11}'`
    idluser=`echo $reply | awk '{print $12}'`

    if (test $ftpflag = 0) then
	if (test $gui -eq 0) then
	    echo
	    echo
	    echo "#######################################################################"
	    echo "ERROR ERROR ERROR !!!!!!!!!!!!!!!!"
	    echo "ftp_check failed  !!!!!!!!!!!!!!!!"
	    echo 
	    echo "Check if directory $remotedir exists on $remotehostname ($remotehost)"	
	    echo "If network is down, you can disable autoftp feature using:"
	    echo "extract -noftp"
	    echo 
	    echo "Exiting extract"
	    echo "#######################################################################"
	    echo
	    echo
	else
	    echo
	    echo
	    echo "#######################################################################"
	    echo "ERROR ERROR ERROR !!!!!!!!!!!!!!!!"
	    echo "ftp_check failed  !!!!!!!!!!!!!!!!"
	    echo 
	    echo "Check if directory $remotedir exists on $remotehostname ($remotehost)"    
	    echo "If network is down, you can disable ftp feature by unchecking the"
	    echo "FTP checkbox in MoJoe's main window."
	    echo 
       	    echo "Exiting Extract"
	    echo "#######################################################################"
	    echo
	    echo "Click Kill/Yes to return to MoJoe menu"
	    echo
	fi
        exit
    fi
fi


#label=`date '+%m_%d_%y'`
label=$MOJOE_DATE
if (test ${#label} -lt 1)
    then
    label=`date '+%m_%d_%y'`
fi
patient_label=`echo $destlabel"_"$label`

echo "***********************************************************************" > $infofile
echo "  EXTRACT:  A Utility to Extract a Whole Exam or Selected Series to DAT" >> $infofile
echo "                         DICOM version                          " >> $infofile
echo "             Courtesy of Joe Maldjian and John Listerud         " >> $infofile
echo "***********************************************************************" >> $infofile
echo "******************************" >> $infofile
echo "General Info " >> $infofile
echo "******************************" >> $infofile
echo "DATE:" `date '+%m_%d_%y'` >> $infofile
echo "TIME:" `date '+%H_%M_%S'` >> $infofile
echo "DEST: $remotedir/$patient_label" >> $infofile
echo "email: $destemail" >> $infofile
echo "\n\n" >> $infofile
echo "******************************" >> $infofile
echo "Details " >> $infofile
echo "******************************" >> $infofile 


### 01-31-07 KLP must create patient directory since it may not yet exist with correct permissions
ssh $remotehost -l $user "mkdir -p $remotedir/$patient_label" >/dev/null 2>/dev/null
### 10-31-08 BCW REPORT if the directory is not created
if [[ $? -gt 0 ]]; then
	errorLine="!!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
	echo $errorLine
	echo $errorLine
	echo
	echo "UNABLE TO CREATE REMOTE DIRECTORY AT $remotedir/$patient_label"
	echo
	echo $errorLine
	echo $errorLine
	echo 
	echo "Please kill this window and select an accesable location."
	exit 1
fi
###


#--------------------------------------------
#Set some OS and debugging specific commands
#--------------------------------------------
tr=`echo tr`
OS=`uname`
if (test $OS == SunOS) then tr=/usr/xpg4/bin/tr; fi

#----------------------------------------------
#Check if a valid argument list was provided
#----------------------------------------------
argument_list=$@
argument_list=`echo $argument_list | $tr -cd '0-9 ' `
nospaces=`echo $argument_list | $tr -d ' ' `
if (test ${#nospaces} -eq 0) then
    echo no valid arguments provided: $@ 
    exit
fi
examnum=`echo $argument_list | awk '{print $1}' `
#nowrite=`echo $@ | awk '/n/{print}' ` 

nowrite=`echo $@ | awk '/nowrite/{print}' `

if (test ${#nowrite} -eq 0) then nowrite=0; else nowrite=1; fi

#noprompt=`echo $@ | awk '/q/{print}' `
verbose=1
quietflag=`echo $@ | awk '/q/{print}' `
if (test ${#quietflag} -gt 0) then verbose=0; fi

#-------------------------------------------------------------------
#TAPE HARDWARE AUTODETECTION
#-------------------------------------------------------------------
if (mt -f $tapedev status >/dev/null 2>/dev/null) then 
    echo DAT Tape device detected
else 
#    echo No DAT Tape device detected
    tapearchive=0
    echo
fi

#-------------------------------------------------------------------
#CDR HARDWARE AUTODETECTION
#-------------------------------------------------------------------
nocdwrite=`echo $@ | awk '/nocd/{print}' `
#if ((test ${#nocdwrite} -eq 0)|(test $cdrflag -eq 1)) then 
#    nocdwrite=0
#    cdrarchive=1
#else 
    if (test ${#nocdwrite} -eq 0) then nocdwrite=0; else cdrflag=0;fi
#    cdrflag=0
if (test $gui = 0) then
    if (test $hinvdetect = 0) then
	ncd=`$cdrecord -scanbus 2>>$quiet | grep -c CD-ROM`
	if (test $ncd -gt 0) then 
	    echo CDR device detected
	    cdloop=0
	    while true
	    do
		let cdloop=cdloop+1
		if (test $cdloop -gt $ncd) then
		    echo "No valid CDR device detected"
		    cdrarchive=0 
		    break
		fi
		cdrarchive=1
		cdline=`$cdrecord -scanbus 2>>$quiet | grep CD-ROM | awk '{print $1}' | head -n $cdloop | tail -1`
		#valid_cdr=`$cdrecord dev=$cdline -checkdrive 2>/dev/null | grep "mmc CD-RW"`
		valid_cdr=`$cdrecord dev=$cdline -checkdrive 2>/dev/null | grep "mmc CD-R"`
		if (test ${#valid_cdr} -gt 0) then
		    cdline1=$cdline
		    cdline=`echo $cdline | 	tr ',' ' '`
		    s_controller=`echo $cdline | awk '{print $1}' `
		    s_id=`echo $cdline | awk '{print $2}' `	
		    s_target=`echo $cdline | awk '{print $3}' `
		    cdrarchive=1
		    if (test $burnproof = 1) then
			burntest=`$cdrecord dev=$cdline1 -prcap  2>/dev/null | grep "Does support BURN-Proof"`
			#burntest=`$cdrecord dev=$cdline driveropts=help -checkdrive 2>$HOME/crap2;_
			#cat $HOME/crap2; unalias rm; rm $HOME/crap2`
			#burntest=`echo $burntest| grep burnproof`
			if (test ${#burntest} -eq 0) then burnproof=0; fi
		    fi
		    break
		fi
	    done

	    if (test $cdrarchive = 1) then			
		scsi_string=`echo $cdr_controller,$cdr_scsi_id,$cdr_target`
		test_cdr=`echo $cdline1 | grep "$scsi_string" `
		if (test ${#test_cdr} -eq 0) then 
		    echo
		    echo "------------------------------------------------------------"
		    echo "Your supplied CDR controller:$cdr_controller scsi_id:$cdr_scsi_id and target:$cdr_target do not exist!"
		    echo "Should I use the detected values of controller:$s_controller scsi_id:$s_id target:$s_target? (y/n)"
		    read fix_cdr
		    echo "------------------------------------------------------------"
		    case "$fix_cdr" in
		    [yY*])
			cdr_controller=$s_controller
			cdr_scsi_id=$s_id
			cdr_target=$s_target
			cdr=`echo $cdr_controller,$cdr_scsi_id,$cdr_target`	
			break;;
		    *)
			echo cd archiving off
			cdrarchive=0;;
		    esac
		fi
	    fi
	else 
	    echo No CDR device detected
	    cdrarchive=0
	fi
    fi

    if (test $hinvdetect = 1) then
	ncd=`hinv | grep -c CDROM`
	if (test $ncd -gt 1) then 
	    echo CDR device detected
	    cdrarchive=1
	    cdline=`hinv | grep CDROM | tail -1`
	    s_controller=`echo $cdline | awk '{print $7}' `
	    s_id=`echo $cdline | awk '{print $3}' `	
	    controller_string=`echo controller $cdr_controller`
	    scsi_id_string=`echo unit $cdr_scsi_id`
	    test_cdr=`hinv | grep CDROM | grep "$scsi_id_string" | grep "$controller_string" `
	    if (test $cdrflag = 1) then
		if (test ${#test_cdr} -eq 0) then 
		    echo
		    echo "------------------------------------------------------------"
		    echo "Your supplied CDR controller:$cdr_controller and scsi_id:$cdr_scsi_id do not exist!"
		    #echo $cdline
		    echo "Should I use the detected values of controller:$s_controller and scsi_id:$s_id ? (y/n)"
		    read fix_cdr
		    echo "------------------------------------------------------------"
		    case "$fix_cdr" in
		    [yY*])
			cdr_controller=$s_controller
			cdr_scsi_id=$s_id
			cdr=`echo $cdr_controller,$cdr_scsi_id,$cdr_target`    
			break;;
		    *)
			echo cd archiving off
			cdrarchive=0;;
		    esac
		fi
	    fi
	else 
	    echo No CDR device detected
	    cdrarchive=0
	fi
    fi
fi
    echo
#fi

if (test $gui -eq 0) then
    if (test $cdrflag = 0) then cdrarchive=0; fi
fi
#-------------------------------------------------------------------
#CDR LOOP
#-------------------------------------------------------------------
nocdwrite=`echo $@ | awk '/nocd/{print}' `
if (test ${#nocdwrite} -eq 0) then nocdwrite=0; else cdrarchive=0; fi

alldevices=`echo $@ | awk '/all/{print}' `
if (test ${#alldevices} -eq 0) then alldevices=0; else alldevices=1; fi

#------------------------------------------
#Check for dummy CD write
#------------------------------------------
dummyflag=`echo $@ | awk '/dummy/{print}' `
if (test ${#dummyflag} -eq 0) then dummyflag=0; else dummyflag=1; fi
newcdr=1
if (test $cdrarchive = 1) then
    reply=`$cdrecord dev=$cdr -reset 2>/dev/null`
    reply=`$cdrecord dev=$cdr -eject 2>/dev/null`
    while true
    do
       	#echo CDR LOOP
       	if (test $alldevices = 0) then tapearchive=0; fi;
       	echo
	if (test $gui = 0) then
	    echo "Please make sure a CD is in the drive"
	    echo -n "Hit Return when ready or control C to abort  "
	    read dummy
	    echo
	fi
       	#echo "cdrecord command is $cdrecord dev=$cdr -msinfo>/dev/null 2>&1"
       	#if ($cdrecord dev=$cdr -msinfo> /dev/null 2>&1)
       	echo "Checking for CD..."
###
# KLP 11-05-04 IDE toc always returns text response
#              IDE returns unhelpful track response
###     
    	###if ($cdrecord dev=$cdr -toc> /dev/null 2>&1) then 
	#valid_cdr=`$cdrecord dev=$cdr -checkdrive 2>/dev/null | grep "mmc CD-RW"`
###
	###valid_cdr=`$cdrecord dev=$cdr -checkdrive 2>/dev/null | grep "mmc CD-R"`
	let max_valid_cdr=25
	let n_valid_cdr=0
	while (test $n_valid_cdr -lt $max_valid_cdr) do
	    valid_cdr=`$cdrecord dev=$cdr -checkdrive 2>/dev/null | grep "mmc CD-R"`
	    if (test ${#valid_cdr} -gt 0) then
		break;
	    fi
	let n_valid_cdr=n_valid_cdr+1
	done
###
	if (test ${#valid_cdr} -gt 0) then
	    #reply=`$cdrecord dev=$cdr -msinfo 2>&1 | grep 'Sense Key' `
	    ###reply=`$cdrecord dev=$cdr -toc 2>&1 | grep 'track' `
	    ###if (test ${#reply} -eq 0) then
	    ide_cd_blank
	    if (test $cd_blank -eq 1) then
###
    		newcdr=1
    		break;
            else
	       	newcdr=0
	       	echo "Checking CD write status...."
###
# KLP 11-05-04 IDE cannot give sense key
###
	       	###reply=`$cdrecord dev=$cdr -msinfo 2>&1 | grep 'Sense Key' `
	       	###if (test ${#reply} -gt 0) then
		ide_cd_appendable
		if (test $cd_appendable -eq 0) then
###
		    echo ""
		    echo "------------------------------------------------------------"
		    echo " This CD has been closed and cannot be written to"
		    echo " Please insert a new CD"
		    echo "------------------------------------------------------------"
		    echo ""
		    reply=`$cdrecord dev=$cdr -eject 2>/dev/null` 
		else
		    echo "------------------------------------------------------------"
		    echo " This CD has been written to"
		    echo " Data will be appended to it"
		    echo "------------------------------------------------------------"
		    #echo " Please insert a new CD"
		    break
		fi
	    fi 
 	else
 	    echo ""
 	    echo " Something is wrong with the drive, try again "
	    echo " If you do not want to archive to cd, try:  extract nocd"
 	    echo ""
 	fi
    done
    if (test $gui -eq 0) then
	lockcd=0
	if (test $cdrarchive = 1) then 
	    echo
	    echo -n "Do you wish to lock the CD after writing? (y/n)"
	    read  closecd_response
	    if (test $closecd_response = y) then
		lockcd=1
		multi=`echo `
	    fi
	fi
    else
	closecd=`echo $@ | awk '/closecd/{print}' `
	if (test ${#closecd} -gt 0) then 
	    lockcd=1
	    multi=`echo `
	else
	    lockcd=0
	    multi=`echo -multi`
	fi
    fi
    echo lockcd is $lockcd
fi
#--------------------------------
#See if any series were provided
#--------------------------------
series_array=`echo $argument_list | awk '{$1=""; print}' `
series_provided=`echo $series_array | $tr -cd '0-9 ' `
nospaces=`echo $series_provided | $tr -d ' ' `
series_provided=1
if (test ${#nospaces} -eq 0) then series_provided=0; fi

#----------------------------------------------
#Verify Exam # ($1) and Get Patient Name
#----------------------------------------------
#dbaccess - << EOF > tmpfile$$ 2>&1
#database ctmr_sdc_db;
#select F.d_study_id, P.Patient_name
#FROM EXAMINATION_FOLDER F, PATIENT_FOLDER P
#where  F.d_study_id = ${1} and P.patient_id = F.patient_id
#Group by f.d_study_id, P.Patient_name
#EOF
#--
#--$lookup -Q $1
###cat patients.txt >tmpfile$$
#--sort -nro tmpfile$$ $mojoe_dir/patients.txt

#--e=`cat tmpfile$$ | grep 'No rows found'`
#patient_name=`cat tmpfile$$ | awk '/patient_name/{$1="";print}' `
#--patient_name=`cat tmpfile$$ | cut -c7-37`
#--rm tmpfile$$

#--exam_error=${#e}
#--if (test $exam_error -gt 0) then
#--    echo ERROR:  exam $1 does not exist
#--    exit
#--fi
$mojoe_dir/dicom/gen2 $1
#e=`wc -l dicom_patient1 | awk '{print $1}'`
e=`wc -l $mojoe_dir/dicom_patient1 | awk '{print $1}'`
if (test $e -ne 1) then
    echo ERROR:  exam $1 does not exist
    exit
fi
#--
#patient_name=`cut -c7-37 < dicom_patient1`
patient_name=`cut -c7-37 < $mojoe_dir/dicom_patient1`

#----------------------------------------------
#echo Get total number of series in this exam
#----------------------------------------------
#dbaccess - << EOF > tmpfile$$ 2>&1
#database ctmr_sdc_db;
#select F.d_study_id, Count(S.original_ser_nu)
#FROM EXAMINATION_FOLDER F, SERIES_ENVIRONMENT S 
#where  F.d_study_id = ${1} and S.Folder_id = F.Folder_id and S.gen_timestamp > 0
#Group by f.d_study_id
#EOF
#nseries=`cat tmpfile$$ | grep $examnum | awk '{print $2}' `
#rm tmpfile$$



#----------------------------------------------
# echo Compute actual count of the images in each series.
#----------------------------------------------
#dbaccess - << EOF > tmpfile$$ 2>&1
#database ctmr_sdc_db;
#select F.d_study_id, S.original_ser_nu, S.gen_timestamp,S.Images_in_series, S.series_desc, Count(I.Original_obj_nu) 
#FROM EXAMINATION_FOLDER F, SERIES_ENVIRONMENT S, IMAGE I 
#where  F.d_study_id = ${1} and S.Folder_id = F.Folder_id and S.Series_id = I.Series_id
#Group by f.d_study_id, S.original_ser_nu, S.gen_timestamp, S.Images_in_series, S.series_desc
#ORDER BY S.gen_timestamp
#EOF
#--$lookup -S $1
###cat series.txt > tmpfile$$
#--sort -no tmpfile$$ $mojoe_dir/series.txt

#----------------------------------------------
# echo Compute actual number of original series
#----------------------------------------------
#nseries=`cat tmpfile$$ | grep original_ser_nu | awk '{print $2}' | sort -nr `
#--nseries=`cat tmpfile$$ | sort -nr | wc -l `
##nseries=`echo $nseries | awk '{print $1}' `
nseries=`wc -l $mojoe_dir/serieslist | awk '{print $1}'`

#----------------------------------------------
#echo Generate image list array
#----------------------------------------------
#image_array=`cat tmpfile$$ | grep images_in_series | awk '{print $2}' `
#series_index=`cat tmpfile$$ | grep original_ser_nu | awk '{print $2}' `
#series_description=`cat tmpfile$$ | awk '/series_des*/{$1="";print}' | $tr ' ' '_' | cut -d '_' -f2,3,4,5,6 `

#--series_index=`cat tmpfile$$ | cut -d' ' -f1,1 | awk '{print $1}' `
#--series_description=`cat tmpfile$$ | cut -d' ' -f2,2 | awk '{print $1}' `
#--image_array=`cat tmpfile$$ | cut -d' ' -f3,3 | awk '{print $1}' `

series_index=`cut -d' ' -f1,1 < $mojoe_dir/serieslist | awk '{print $1}' `
series_description=`cut -d' ' -f2,2 < $mojoe_dir/serieslist | awk '{print $1}' `
image_array=`cut -d' ' -f3,3 < $mojoe_dir/serieslist | awk '{print $1}' `

series_array=$series_index
series_descriptor=$series_array

#----------------------------------------------
#echo Generate series list array
#----------------------------------------------
if (test $series_provided -eq 1) then
    series_array=`echo $argument_list | awk '{$1=""; print}' `
    series_descriptor=$series_array
fi

if (test $series_provided -eq 0) then
    series_descriptor=`echo all`
#   series_array=1
#   cnt=2
#   while test $cnt -le $nseries
#   do
#       series_array=`echo $series_array $cnt`
#      	cnt=`expr $cnt + 1`
#   done
fi


#----------------------------------------------
#See if we want to continue
#----------------------------------------------
#--rm tmpfile$$
echo
echo --------------------------------------------------------------------------
echo "patient_name: $patient_name    exam: $examnum     series: $series_descriptor"
echo --------------------------------------------------------------------------
#echo "series description nimages" | awk '{printf("%5s %30s %10s \n", $1, $2, $3)}'
echo "series description nimages" | awk '{printf("%6s %30s %10s \n", $1, $2, $3)}'
cnt=1
for i in $series_description
do
#   nimages=`echo $image_array | awk -v index=$cnt '{print $index }' `
    nimages=`echo $image_array | cut -d' ' -f$cnt`

#   true_series=`echo $series_index | awk -v index=$cnt '{print $index }' `
    true_series=`echo $series_index | cut -d' ' -f$cnt`

    #echo $true_series $i $nimages | awk '{printf("%5s %30s %10s \n", $1, $2, $3)}'	
    echo $true_series $i $nimages | awk '{printf("%6s %30s %10s \n", $1, $2, $3)}'
    #echo "  $cnt		$i			$nimages"
	
    cnt=`expr $cnt + 1`
done

if (test ${#series_array} -eq 0) then
    echo "    Invalid series list: " $@
    exit
fi
#echo
#echo -n "Continue with extract for exam: $examnum series: $series_descriptor ? (y/n)   "
#read extract_response
extract_response=y
#if test $extract_response != y
#	then
#	exit
#fi
if (test ${#destlabel} -eq 0) then
    echo -n "Enter Patient Identifier for Labeling Files:  "
    read patname
else
    patname=$destlabel
fi
if (test "$patname") then 
    ptflag=1
else
    echo
    echo
    echo "------------------------------------------------------------------------------"
    echo "Sorry, you must enter a Patient label"
    echo "Exiting extract"
    echo "------------------------------------------------------------------------------" 
    echo
    echo
    exit
fi

echo ""

#------------------------------------------------------
#Make a temporary loc directory for holding the images
#------------------------------------------------------
#imagedir=/export/home1/mojoe
imagedir=$MOJOE_TEMP
if (test ${#imagedir} -lt 1)
    then
    imagedir=/export/home1/mojoe
fi
locdir=`echo $patient_label"_"$$`
cd_locdir=`echo $patient_label"_tmp"`
cd $imagedir
mkdir $locdir
cd $locdir
mkdir tmp
cd $imagedir
mkloc=`mkdir LOCS 2>/dev/null`
lastsector=0


#---------------------------------------------------
#Now extract the images 
#---------------------------------------------------
case "$extract_response" in
[yY*])
    #************************ Start BAS 03/30/04 Changes **************************************#
    #---------------------------------------------------------------------------
    # Get list of image files and their locations by calling Perl script lx_ximg:
    # (note: list will be in mojoe_dir/tempfile.txt)
    #---------------------------------------------------------------------------
    series_list=`echo $series_array | tr ' ' ','`  #Replace blanks with commas to separate series numbers
#   execute=`$mojoe_dir/lx_ximg_new  'E'$examnum'S'$series_list'I'all | tail +1 >$mojoe_dir/tempfile.txt`
### execute=`$lookup -s -R -X 'E'$examnum'S'$series_list'I'all | tail +1 >$mojoe_dir/tempfile.txt`
    #--execute=`$lookup -s -R -X 'E'$examnum'S'$series_list'I'all | tail +1 | sort -n >$mojoe_dir/tempfile.txt`
    print "examnum = $examnum, series_array = $series_array"
    $mojoe_dir/dicom/gen3 $examnum $series_array
    #--------------------------------------------------------------
    # For each image file, copy it to the correct series subfolder under
    # the tmp folder, creating exam and series subfolders as needed:
    #--------------------------------------------------------------
    #sort -o tempfile.txt $mojoe_dir/tempfile.txt #Sort the list of exams, series and images.
    exec 0<$mojoe_dir/tempfile.txt #Open the list for reading
    read -r order sourcepath exam series image newfilename #Read and discard first record (column headings) 
    imagesExtractedThisSeries=0
    totalImagesExtracted=0
    thisExam=0
    thisSeries=0
    firstImageInSeries=0;
    workdir=`echo $imagedir/$locdir/tmp`
## add for billing
    if (test $ftpflag -eq 1) then
        ftpyesno=yes;
    else
        ftpyesno=no;
    fi
    if (test $cdrflag -eq 1) then
        cdyesno=yes;
    else
        cdyesno=no;
    fi
    billdate=`date '+%m/%d/%y'`
    billextracttime=`date '+%m%d%y%H%M%S'`
    billheader="Exam,Date,Time,E-mail,Scanner,Dir,MoJoe,CD,FTP"
    billtime=`date '+%H:%M:%S'`
    billexamnum=`echo $examnum | awk '{printf("%05d", $1)}'`
    billdetails=$billexamnum","$billdate","$billtime","$destemail","$HOSTNAME","$remotedir/$patient_label","extract","$cdyesno","$ftpyesno
    billexam=$HOSTNAME"_"`echo $examnum | awk '{printf("%05d", $1)}'`"_"$billextracttime
    billheaderfull=$billheader",NumberOfImages"
    let billfirstline=1
    billfile=''
## 
    cd $mojoe_dir
    #------------------------------------------------------------------------
    # This "while" loop executes once for every line in the tempfile.txt file:
    #------------------------------------------------------------------------
    while read -r order sourcepath exam series image examfolder seriesfolder newfilename #Reads next record and parses fields 
    do
		#--------------------------------------------------------------------------
		# Got a tempfile.txt record. Determine what Exam/Series/Image it 
		# represents and create any necessary folders:
		#--------------------------------------------------------------------------
		#echo Path:$sourcepath Exam:$exam Series:$series Image:$image NewFilename:$newfilename
		if (test $exam != $thisExam) then
		    thisExam=$exam
		    cd $workdir
		    #-------------------
		    # Create exam folder:
		    #-------------------
		    mkdir $examfolder 2>/dev/null
		    thisSeries=0
		fi
		if (test $series != $thisSeries) then
		    #-------------------------
		    # Series number is different:
		    #-------------------------
		    if (test $thisSeries != 0) then #Only do if not at start of first series of exam!
			#-------------------------------------------------
			# Print count of images extracted for the series:
			#-------------------------------------------------
			echo Images Extracted for Series $thisSeries: $imagesExtractedThisSeries
## add for billing detail on just-extracted series
                        billdetailsfull=$billdetails","$imagesExtractedThisSeries
  		        $read_dcm_biller $billfile $billfirstline $billexam $billheaderfull $billdetailsfull
                        let billfirstline=0
##
			#echo ------------------------------------------------------
		    fi
		    imagesExtractedThisSeries=0
		    thisSeries=$series
		    cd $workdir/$examfolder
		    #-------------------
		    # Create series folder:
		    #-------------------
		    mkdir $seriesfolder 2>/dev/null
		    firstImageInSeries=1
		fi
		#-------------------------------------------------
		# Copy the image to current folder as $newfilename:
		#-------------------------------------------------
		cd $mojoe_dir
		cp $sourcepath $workdir/$examfolder/$seriesfolder/$newfilename
		#------------------------------------------------------
		# If first image in series, get and display header info:
		#------------------------------------------------------
		if (test $firstImageInSeries = 1) then
		    #Got first image in a series, so must print header info:
		    #-convert the contents of $newfilename to LS format:
		    # There is no reason to convert since a program exists that reads the ls header
		    # directly.

		    # ls2ximg $workdir/$examfolder/$seriesfolder/$newfilename

		    #-now call read_ximg_header to print the header info:
		    echo ------------------------------------------------------
#		    read_ge_ls_header -f $workdir/$examfolder/$seriesfolder/$newfilename | tee -a $infofile  
#		    $read_ge_ls_header -f $workdir/$examfolder/$seriesfolder/$newfilename | tee -a $infofile  
		    $read_dcm_header $workdir/$examfolder/$seriesfolder/$newfilename $examfolder/$seriesfolder/$newfilename | tee -a $infofile  
## add for billing file name
                    billfile=$workdir/$examfolder/$seriesfolder/$newfilename
##
		    #-finally, delete the file created by ls2ximg above
		    #rm -f $workdir/$examfolder/$seriesfolder/$newfilename.MR 

		    firstImageInSeries=0
		#------------------------------------------------------------------
		# Else display a message for every 100 images extracted per series:
		#-------------------------------------------------------------------
		else
		    remainder=`expr $imagesExtractedThisSeries % 100`
		    if (test imagesExtractedThisSeries -gt 99 && test $remainder = 0) then
			#echo Exam_No = $exam,   Series_No = $series,   Image_No = $image
			echo Extracted 100 images...
		    fi
		fi
		imagesExtractedThisSeries=`expr $imagesExtractedThisSeries + 1`
		totalImagesExtracted=`expr $totalImagesExtracted + 1`	
    done
    <&-  #Close input file.
    echo Images Extracted for Series $thisSeries: $imagesExtractedThisSeries
    echo ------------------------------------------------------
## add for billing detail on last series
    billdetailsfull=$billdetails","$imagesExtractedThisSeries
    $read_dcm_biller $billfile $billfirstline $billexam $billheaderfull $billdetailsfull
    let billfirstline=1
    billdetailsfull=$billdetails","$totalImagesExtracted
    $read_dcm_biller 'esummary' $billfirstline $billexam $billheaderfull $billdetailsfull
##
    echo Total Images Extracted: $totalImagesExtracted
    #************************ End BAS 03/30/04 Changes **************************************#


    #---------------------------------------
    #Create a tar file
    #---------------------------------------
    rawdir=`echo $imagedir/$locdir`
    outputdir=`echo $imagedir/LOCS/`
    cd $rawdir
    #label=`date '+%m_%d_%y'`
    label=$MOJOE_DATE
    if (test ${#label} -lt 1)
	then
	label=`date '+%m_%d_%y'`
    fi
    ziptar=1
    #ziptar=0
    if (test $ziptar -eq 1) then
        tarfile=`echo $patient_label"_"$$"_tmp.tar.gz"`
        cdtarfile=`echo $destlabel"_"$$".tgz"`
        zipflag=czvf
    else
        tarfile=`echo $patient_label"_"$$"_tmp.tar"`
        cdtarfile=`echo $destlabel"_"$$".tar"`
        zipflag=cvf
    fi

    echo
    echo
    echo "***************************************************************"
    echo
    echo '' >> $quiet
    echo "***************************************************************" >> $quiet
    echo '' >> $quiet
    echo "Creating tar file $outputdir$tarfile...."
    echo "Creating tar file $outputdir$tarfile ...." >> $quiet
    #tar cvf $outputdir$tarfile tmp 2>>$quiet
    ###tar cvf $outputdir$tarfile tmp >> $quiet 2>>$quiet
    tar $zipflag $outputdir$tarfile tmp >> $quiet 2>>$quiet
	
    #------------------------------------------------
    #For Debugging
    #cp /export/home/sdc/junk.tar $outputdir$tarfile
    #------------------------------------------------
    #####################################################
    #Test to make sure the tar file got written properly
    #####################################################
    echo
    echo "***************************************************************"
    cd $imagedir
    ls -l $outputdir$tarfile >> $quiet
    tarsize=`ls -l $outputdir$tarfile | awk '{print $5}'`
    echo "tarfile size =  $tarsize" >> $quiet
### 01-31-07 KLP must create patient directory since it may not yet exist with correct permissions
#ssh $remotehost -l $user "mkdir -p $remotedir/$patient_label" >/dev/null 2>/dev/null
### 10-31-08 BCW REPORT if the directory is not created
#if [[ $? -gt 0 ]]; then
#	errorLine="!!!!!!!!!!!!!!!!!!!!!! ERROR !!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
#	echo $errorLine
#	echo $errorLine
#	echo
#	echo "UNABLE TO CREATE REMOTE DIRECTORY AT $remotedir/$patient_label"
#	echo
#	echo $errorLine
#	echo $errorLine
#	echo 
#	echo "Please kill this window and select an accesable location."
#	exit 1
#fi
###
    if (test $tarsize = 0) then
      	echo 
      	echo "***************************************************************"
       	echo "Error:  Tarfile size is 0"
       	echo "Disk usage for $outputdir is: "
       	df -k $outputdir
       	echo "Aborting Extract"
       	echo "***************************************************************"
       	echo "***************************************************************" >> $quiet
       	echo "Error:  Tarfile size is 0" >> $quiet
       	echo "Disk usage for $outputdir is: " >> $quiet
       	df -k $outputdir >> $quiet
       	echo "Aborting Extract" >> $quiet
       	echo "***************************************************************" >> $quiet
       	cat $quiet >/dev/null
	cp $servicedir/$servicelog $servicedir/$newservicelog
       	### 12-08-04 KLP $autoftp  $remotehost $user $pass $remotedir $patient_label $servicedir $newservicelog  >/dev/null 2>/dev/null
       	$autoftp  $remotehost $user $pass $remotedir/$patient_label config $servicedir $newservicelog  >/dev/null 2>/dev/null
       	$autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $log_filename  >/dev/null 2>/dev/null
	$autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $log_mojoe  >/dev/null 2>/dev/null
       	exit
    fi	
    echo "***************************************************************" >> $quiet
    echo '' >> $quiet

    #------------------
    #AUTOFTP LOOP
    #------------------
    if (test $ftpflag = 1) then
     	echo "autoftp initiated for $outputdir$tarfile to $remotedir/$patient_label on $remotehostname" | tee -a $quiet
	#echo "autoftp initiated for $outputdir$tarfile to $remotedir/$patient_label on $remotehostname" >> $quiet
	ftpreply=`$autoftp  $remotehost $user $pass $remotedir $patient_label $outputdir $tarfile 2>>$quiet`
      	ftpflag1=`echo $ftpreply | grep "Interactive mode on"`
       	ftpflag2=`echo $ftpreply | grep "Not connected"`
       	ftpflag3=`echo $ftpreply | grep "failed"`
       	if (test "$ftpflag1") then ftp_failed=0; else ftp_failed=1; fi
       	if (test "$ftpflag2") then ftp_failed=1; fi
       	if (test "$ftpflag3") then ftp_failed=1; fi
       	#rm $outputdir$tarfile
       	if (test $ftp_failed = 0) then
	    ###$monkey
	    $monkey&
	    if (test $reconflag = 1) then
		#-----------------------------------------------------------------------
		# Launch /fmri2/fmri/autolocsort_lx instead of autoimagesort_x 5/20/04 BAS:
		#-----------------------------------------------------------------------
	       	### KLP 11-17-04 echo "autolocsort_lx initiated  on $idlhostname ($idlhost)" | tee -a $quiet
	       	### querecon=`$remote_launch autolocsort_lx $idlhost $idluser $remotedir/$patient_label/$tarfile >/dev/null 2>/dev/null`
   	       	echo "autolocsort_excite initiated  on $idlhostname ($idlhost)" | tee -a $quiet
	       	#ssh $idlhost -l $idluser "~/launch_sge ~/autolocsort_excite $remotedir/$patient_label/$tarfile >& /dev/null"&
		### KLP 03-07-05 querecon=`$remote_launch /fmri2/fmri/launch_sge $idlhost $idluser /fmri2/fmri/autolocsort_excite $remotedir/$patient_label/$tarfile >/dev/null 2>/dev/null`
#		echo "RECON COMMAND: $remote_launch $fmri_dir/launch_sge $idlhost $idluser $fmri_dir/autolocsort_excite_paradigm $remotedir/$patient_label/$tarfile"
		querecon=`$remote_launch $fmri_dir/launch_sge $idlhost $idluser $fmri_dir/autolocsort_excite_paradigm $remotedir/$patient_label/$tarfile >/dev/null 2>/dev/null`
	    fi
	else
	    line1=`echo $ftpreply | awk '{print $1}' `
	    echo "ftp failed: $line1" | tee -a $quiet
	fi	
    fi;;
[nN*])
    echo no images extracted
    exit;;
esac
#if (test ${#nowrite} -eq 0) then
if (test $nowrite = 0) then
    #------------------
    #CDR WRITE LOOP
    #------------------
    if (test $cdrarchive = 1) then
	dummy=''
       	if (test $dummyflag = 0) then dummy=''; else dummy=`echo -dummy -nofix `; fi
       	#echo "True write (y/n)"
       	#read true_write
       	#if (test $true_write = y) then dummy=''; else dummy=`echo -dummy -nofix `; fi

       	isofile=cdpfile.iso
       	cdimage=$rawdir$isofile

       	#------------------------------------------------------------------------
       	#Change the name of the tmp directory to allow multiple patient folders
       	#to appear on 1 CD
       	#instead of all images going into a single tmp directory
       	#------------------------------------------------------------------------
       	cd $imagedir/$locdir
       	mv tmp $cd_locdir
       	cd $startdir

       	#allpfiles=$imagedir/$loc
        allpfiles=$tarfile
       	multiflag=1
       			
       	echo '' >> $quiet
       	echo '' >> $quiet
       	echo '**********************************' >> $quiet
       	#echo Generating CD image file for $allpfiles >> $quiet
       	echo Generating CD image file for $cdtarfile >> $quiet
       	echo '**********************************' >> $quiet
       	echo '' >> $quiet
       	echo '' >> $quiet

       	echo "Generating CD image file..."
       	if (test $newcdr = 1) then multiflag=0; fi
	if (test $multiflag = 0) then
	    mkisofs_loop
	else
	    while true
	    do
	       	echo '' >> $quiet
###
# KLP 11-05-04 IDE gives extra msinfo
###
	       	###reply=`$cdrecord dev=$cdr -msinfo`
	       	###echo $reply >>$quiet 2>>$quiet
	       	###startsector=`echo $reply | $tr ',' ' ' | awk '{print $1}'`
	       	###if (test $startsector -ge $lastsector 2>>$quiet) then
		    ###break
		ide_cd_appendable
		echo "appendable = $cd_appendable ... msinfo ($startsector,$endsector)" >> $quiet
		if (test $cd_appendable -eq 1) then
			startsector=$cd_first_sector
			endsector=$cd_last_sector
		else
			startsector=0
			endsector=0
		fi
		if (test $cd_appendable -eq 1 && test $startsector -ge $lastsector) then
		    break 
###
		else 
		    echo 'Bad msinfo read from Cdrecord'
		    echo ''
		    echo 'Retrying...DO NOT KILL ME...'
		    echo 'Bad msinfo read from Cdrecord...will retry...Do not Kill me ...' >> $quiet
		    echo "Resetting CD Mechanism..."
		    echo
		    reply=`$cdrecord dev=$cdr -reset 2>/dev/null`
		    reply=`$cdrecord dev=$cdr -eject 2>/dev/null`
		    reply=`$cdrecord dev=$cdr -load 2>/dev/null`
		fi
	    done
	    ###endsector=`echo $reply | $tr ',' ' ' | awk '{print $2}'`   # KLP 11-05-04 IDE gets value above
	    lastsector=$endsector
	    echo startsector $startsector   endsector $endsector >>$quiet 2>> $quiet
	    mkisofs_loop
	fi

	#-----------------------------------------------------------------------------------------------
       	#Change the name of the directory back to tmp to prevent problems with tape, if also being used
       	#-----------------------------------------------------------------------------------------------
       	cd $imagedir/$locdir
       	mv $cd_locdir tmp
       	cd $startdir
	
       	#echo "cdr command is $cdrecord dev=$cdr -v $driveropts $dummy $multi speed=$cdr_speed $cdimage"
       	echo "Burning CD..."
	if ($cdrecord dev=$cdr -v $driveropts $dummy $multi speed=$cdr_speed $cdimage >>$quiet 2>>$quiet) then
	    ###$monkey 1
	    $monkey 1&
	    echo "Images saved to CDR"
	    #-------------------------------------------------------------------
	    #Close CD
	    #-------------------------------------------------------------------
	    if (test $lockcd = 1) then
	       	echo "CD Locked"
	        #reply=`date`
		#closefile=$HOME/closecd_stamp
		#echo CD closed on $reply > $closefile
		#isofile=cdpfile.iso
		#cdimage=$HOME/$isofile	
	      	#reply=`$cdrecord dev=$cdr -msinfo`
	       	#startsector=`echo $reply | tr ',' ' ' | awk '{print $1}'`
	       	#endsector=`echo $reply | tr ',' ' ' | awk '{print $2}'`
	       	#echo start:$startsector end:$endsector cdr:$cdr closefile:$closefile cdimage:$cdimage isoflags:$isoflags
		#$mkisofs -o $cdimage $isoflags -C $startsector,$endsector -M $cdr $closefile
		
	       	#echo "cdr command is $cdrecord dev=$cdr -v speed=$cdr_speed $cdimage"
	       	#if ($cdrecord dev=$cdr -v speed=$cdr_speed $cdimage) then
		#    echo "CD closed"
	       	#else
		#    echo "Unable to close CD"
	       	#fi
	       	#rm $closefile
	        #rm $cdimage
		echo `$cdrecord dev=$cdr -eject 2>/dev/null`
	    fi
	else
	    #beep
	    echo
	    echo "CDR write error, data not saved to CD!!!!! "
	    echo "CDR write error, data not saved to CD!!!!! " >> $quiet
	    echo
	    #beep
	fi
	    echo '###################################################' >> $quiet
	    echo '###################################################' >> $quiet
	    rm $cdimage
    fi
    if (test $tapearchive = 1) then
      	mtout=mtout$$
       	mt status >/dev/null 2>$mtout
       	if (cat $mtout | grep "Not READY" >/dev/null) then tapeloaded=0; else tapeloaded=1; fi
       	rm mtout$$
       	if (test $tapeloaded = 1) then
	    echo
	    echo ------------------------------------------------------------
	    echo "Writing images to tape..."
	    if (tar -cfb $tapedev 512 -C $imagedir/$locdir tmp) then
	    #if (tar -cfb $tapedev 512 -C /usr/g/insite tmp) then
       		ftp_failed=0
       		echo "DONE:  Tape write successful"	
       		#rm /usr/g/insite/tmp/*.MR 2>/dev/null
	    else
	       	echo "Failure:  Tape write failed"
	    fi
	    echo ------------------------------------------------------------
	fi
    fi
fi
cd $imagedir
unalias rm
if (test $ftp_failed = 0) then
    rm $outputdir$tarfile
else
    echo "Images are stored in $outputdir$tarfile"
    echo "Images are stored in $outputdir$tarfile" >> $quiet
fi
rm -r $locdir
echo "******************************" >> $infofile
echo "End" >> $infofile
echo "******************************" >> $infofile 
if (test $ftpflag = 1) then
    echo Beginning transfer of extract log files...
    $autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $log_filename >/dev/null 2>/dev/null
    $autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $log_mojoe >/dev/null 2>/dev/null
    $autoftp  $remotehost $user $pass $remotedir/$patient_label log $logdir $info_mojoe >/dev/null 2>/dev/null
    if (test ${#destemail} -gt 0) then
	echo `ssh -l $sshuser $sshserver $fmri_dir/email_notification $remotedir/$patient_label/log/$info_mojoe mojoe_extract $destemail`
    fi
    cp $servicedir/$servicelog $servicedir/$newservicelog
    ### 12-08-04 KLP $autoftp  $remotehost $user $pass $remotedir $patient_label $servicedir $newservicelog >/dev/null 2>/dev/null
    $autoftp  $remotehost $user $pass $remotedir/$patient_label config $servicedir $newservicelog >/dev/null 2>/dev/null
    #---------------------------------------------------------------------
    #Upload whatRev info in name 'gradientconfig.cfg to destination folder
    #---------------------------------------------------------------------
    gradientconfig=`echo whatRev.out_extract`
    #whatRev > $mojoe_dir/$gradientconfig
    reply=`which whatRev 2>/dev/null`
    if (test ${#reply} -gt 0) then
        whatRev > $mojoe_dir/$gradientconfig
    else
        cp -p $MOJOE_WHATREV $mojoe_dir/$gradientconfig
    fi
    $autoftp  $remotehost $user $pass $remotedir/$patient_label config $mojoe_dir $gradientconfig >/dev/null 2>/dev/null
    rm $mojoe_dir/$gradientconfig
#
# send the last 1000 lines from /usr/g/service/log/psd_syserr.log 
#
    psd_log=psd_syserr_last1000.log
    tail -1000 $servicedir/psd_syserr.log > $mojoe_dir/$psd_log
    $autoftp  $remotehost $user $pass $remotedir/$patient_label config $mojoe_dir $psd_log >/dev/null 2>/dev/null
    rm $mojoe_dir/$psd_log

#
# send the last 1000 lines from /usr/g/service/log/gesys_*.log 
# BCW 2007-10-15
#
    gesys_log=gesys_last1000.log
    tail -1000 $servicedir/gesys_*.log > $mojoe_dir/$gesys_log
    $autoftp  $remotehost $user $pass $remotedir/$patient_label config $mojoe_dir $gesys_log >/dev/null 2>/dev/null
    rm $mojoe_dir/$gesys_log

#
# send all the same config logs as those for capture (in case there is no capture)
#
    #configdir=/w/config/
    configdir=$MOJOE_CONFIG
    if (test ${#configdir} -lt 1)
	then
	configdir=/w/config/
    fi
    #b_datdir1=/usr/g/bin
    b_datdir1=$MOJOE_DATDIR1
    if (test ${#b_datdir1} -lt 1)
	then
        b_datdir1=/usr/g/bin
    fi
    #b_datdir2=/usr/g/caldir
    b_datdir2=$MOJOE_DATDIR2
    if (test ${#b_datdir2} -lt 1)
	then
        b_datdir2=/usr/g/caldir
    fi
    Gconf_name=GradientConfig.cfg
    Tensorf_name=tensor.dat
    Mconf_name=MRconfig.cfg
    scp $configdir/${Gconf_name} ${user}@${remotehost}:${remotedir}/${patient_label}/config/${Gconf_name}
    scp $b_datdir1/${Tensorf_name} ${user}@${remotehost}:${remotedir}/${patient_label}/config/${Tensorf_name}
    scp $configdir/${Mconf_name} ${user}@${remotehost}:${remotedir}/${patient_label}/config/${Mconf_name}
#
    wildmatch=bcrvs[1-9].dat
    scp ${b_datdir1}/${wildmatch} ${user}@${remotehost}:${remotedir}/${patient_label}/config/ 2>/dev/null
    scp ${b_datdir2}/${wildmatch} ${user}@${remotehost}:${remotedir}/${patient_label}/config/ 2>/dev/null
#
    protocols_filename=protocols_site.tar
    #protocols_top=/usr/g
    protocols_top=$MOJOE_PROTOCOLS_TOP
    if (test ${#protocols_top} -lt 1)
        then
        protocols_top=/usr/g
    fi
    tar cvf $mojoe_dir/$protocols_filename -C $protocols_top protocols/site >/dev/null 2>/dev/null
    cd $mojoe_dir
    gzip $protocols_filename >/dev/null 2>/dev/null
    scp ${protocols_filename}.gz ${user}@${remotehost}:${remotedir}/${patient_label}/config/${protocols_filename}.gz
    rm $protocols_filename.gz >/dev/null 2>/dev/null
    echo Ending transfer of extract log files...
#
# reset permissions on config files (tensor.dat by default is user readonly)
#
    ssh -l $sshuser $sshserver chmod -R ug+w $remotedir/$patient_label/config 
#
# send serieslist to the log directory
#
    scp $mojoe_dir/serieslist ${user}@${remotehost}:${remotedir}/${patient_label}/log/serieslist
#


# send gating
  gatingdir=$MOJOE_GATING
  if [[ ${#gatingdir} -lt 1 ]]; then
		gatingdir=/usr/g/service/log/gating
  fi
	if [[ -d $gatingdir ]]; then
		if [[ `ls -1 $gatingdir | wc -l` -gt 0 ]]; then
			echo Gating information found in $gatingdir.  Sending to ${patient_label}/gating 
			ssh $remotehost -l $user "mkdir -p $remotedir/$patient_label/gating" >/dev/null 2>/dev/null
	    scp $gatingdir/* ${user}@${remotehost}:${remotedir}/${patient_label}/gating
	    if [[ $? -gt 0 ]]; then
	    	echo "Problems copying data files from $gatingdir.  Files in WILL NOT be deleted."
	    else
	    	rm -f $gatingdir/*
	    fi
	  fi
	fi
fi

#echo "$sshuser:$sshserver || ${user} ${remotehost}"

cd $startdir
#
# save log for monitor
#rm -f $infofile
mv $infofile $mojoe_dir/log/monitorlog

rm -f $mojoe_dir/tempfile.txt
rm -f $locdir 

echo ALL DONE
echo "***************************************************************"
exit
