PRO di_file_copy, src, dest, f=f

;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Copies the file from src to dest
;;
;; CALLING SEQUENCE:
;;	di_file_copy, src, dest, f=f
;;
;; REQUIRED INPUTS:
;;	src - String array of source files to copy
;;	dest - String array of the destinations for the copies. Must be the same size as src
;;
;; OUTPUTS:
;;
;; OPTIONAL INPUT KEYWORDS:
;;	F - if the destination file cannot be opened, remove it and try again. If it can't
;;	    be removed, then ignore it
;;
;; EXAMPLE:
;;      IDL> di_file_copy, src, dest, /f
;;
;; PROCEDURES USED (i.e. called directly!):
;;
;; MODIFICATION HISTORY:
;;   2004-12-08  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------

;; Check the inputs
fCnt = n_elements(src)
IF (fCnt NE n_elements(dest)) OR (fCnt EQ 0) THEN $
	message, 'Invalid Parameters'

;; Loop through all the files and copy them
FOR i=0,fCnt-1 DO BEGIN
	on_ioerror, killError
	;; Open the file to read
	openr, rFile, src[i], /get_lun

	;; Open the file to write to
	IF keyword_set(f) THEN on_ioerror, delFile
	openw, wFile, dest[i], /get_lun
	GOTO, copyFile

	;; Force is applied so try to delete the destination file and try again
    delFile:
	on_ioerror, skipFile
	file_delete, dest[i], /quiet
	openw, wFile, dest[i], /get_lun
	GOTO, copyFile

	;; Could not open again, so ignore this file
    skipFile:
	free_lun, rFile
	CONTINUE

	;; Do the actual file copy
    copyFile:
	on_ioerror, killError
	tmp = bytarr((fstat(rFile)).size)
	readu, rFile, tmp
	writeu, wFile, tmp	

	;; Close the files
	free_lun, rFile, wFile
ENDFOR

RETURN

;; There was an error that causes the program to stop
killError:
on_ioerror, NULL
;; Close any open files
IF n_elements(rFile) GT 0 THEN free_lun, rFile
IF n_elements(wFile) GT 0 THEN free_lun, wFile

;; Throw the error
message, !ERROR_STATE.MSG, /ioerror

RETURN

END