;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Brings up a dialog for the user to select a file to open for calibration
;;	then loads that file as a FITS file and if loading worked, displays
;;	the FITS header and the image
;;
;; CALLING SEQUENCE:
;;	gui_openFile, top
;;
;; REQUIRED INPUTS:
;;	top - The top widget of the application
;;
;; OUTPUTS:
;;
;; OPTIONAL INPUT KEYWORDS:
;;
;; EXAMPLE:
;;      IDL> gui_openFile, top
;;
;; PROCEDURES USED (i.e. called directly!):
;;
;; MODIFICATION HISTORY:
;;   2004-07-29  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------
PRO gui_openFile, top
;; Get the current options
widget_control, top, get_uvalue=opts

;; Determine the path
IF opts.infn NE '' THEN BEGIN
	pos = strpos(opts.infn, path_sep(), /reverse_search)
	IF pos NE -1 THEN path = strmid(opts.infn, 0, pos)
ENDIF

;; Create an open file dialog for the user
fn = dialog_pickfile(dialog_parent=top, filter=['*.fit','*.txt','*.csv'], $
	title='Please Choose a File to Calibrate', path=path, file=opts.infn)

IF fn EQ '' THEN GOTO, ret

;; Close any open files first
gui_closeFile, top
widget_control, top, get_uvalue=opts
opts.det = -1

;; Try to open the file as a FITS file
message, /reset
opts.infn = fn
img = readfits(fn,hdr, /SILENT)

;; Try to open the file as a list of filenames
IF !ERROR_STATE.CODE LT 0 THEN BEGIN
	;; Create the structure to read the file
	@batchtemp

	;; Open the ASCII file
	ON_IOERROR, error
	data = read_ascii(fn, template=batchtemp)

	opts.doBatch = 1

	;; Display the filenames
	hdrview = widget_text(top, /scroll, uname='hdrview', xsize=80,$
		ysize=10<(size(data.fn,/dimensions))[0], value=data.fn)

	GOTO, ret
ENDIF

;; Check to make sure the image is either IR or VIS
det = SXPAR(hdr, 'IMGH021', COUNT=cnt)
IF (cnt EQ 0) OR (det LT 0) OR (det GT 1) THEN BEGIN
	!ERROR_STATE.MSG = 'Invalid FITS header'
	GOTO, error
ENDIF
opts.det=det
IF det EQ 1 THEN BEGIN
	opts.mods.geom = 0
	opts.mods.desmear = 0
ENDIF ELSE opts.mods.linDN = 0

;; Display the FITS header in a text box below the options choices
hdrview = widget_text(top, /scroll, uname='hdrview', xsize=80, $
	ysize=10, value=hdr)

;; Open an image display window with the FITS image in it
IF det EQ 1 THEN BEGIN
	xsize=300
	ysize=150
ENDIF
tmp = getBiasCols(hdr, COMPLEMENT=imgCols)
tmp = getPOCRows(hdr, COMPLEMENT=imgRows)
img = img[imgCols[0]+1:imgCols[1]-1, imgRows[0]+1:imgRows[1]-1]
preview = cwimg_preview(group_leader=top, title='Raw Image',retain=2, $
	value=img, kill_notify='gui_preview_close_event', uvalue=top, $
	xsize=xsize,ysize=ysize)
opts.previewWnd = preview

GOTO, ret

;; An error occured so display a message
error:
tmp = dialog_message(!ERROR_STATE.MSG, /ERROR, dialog_parent=top)
!ERROR_STATE.CODE = 0

;; Clean up
ret:
widget_control, top, set_uvalue=opts
gui_updateoptpane, top
gui_updatemodlist, top

RETURN

END