;------------------------------------------------------------------------------;
;+
; NAME:
;		DIVA_FILE
; AUTHOR:
;		John A. Rainnie - RAL (j.a.rainnie@rl.ac.uk)
; PURPOSE:
;		This function returns a string array of filenames, selected by
;		means of the IDL "dialog_pickfile" function. Only filenames
;		with extensions: 'fit', 'fits', 'fts', 'dat', 'img', 'raw', 
;		'jpg', and 'jpeg' will be returned. (JPEG files will be checked!)
; INPUTS:
;		def_file	- a default filename (set in "diva_defaults.pro")
;		path		- a default pathname (set in "diva_defaults.pro")
;		func		- either 'preview' or 'adapt'
; OUTPUTS:
;		filenames
; ERROR HANDLING:
;		If the dialog is cancelled, or by any other means a filename is
;		not supplied, a null string will be returned
; PROCEDURES USED:
;       Functions:   DIALOG_PICKFILE
; NOTES:
;		The list of 'allowed' filetypes (as determined from the file
;		extension) may be increased in the future - perhaps to include
;		JPEGs, TIFFs, etc.
;-
;------------------------------------------------------------------------------;
FUNCTION diva_file,def_file,path,func
;------------------------------------------------------------------------------;

CASE func OF
	'preview':	f = DIALOG_PICKFILE(path=path,file=def_file,/multiple)
	'adapt':	f = DIALOG_PICKFILE(path=path,file=def_file)
ENDCASE

;create string array of extensions, and a corresponging integer array
;to contain indicies of subsequent search
ext 		= strarr(n_elements(f))
checks		= intarr(n_elements(f))

;define string array of allowed extensions
CASE func OF
	'preview':	allowed_ext = [ 'fit' , 'fits' , 'fts',						$
								'dat' , 'img'  , 'raw', 					$
								'jpg' , 'jpeg'	,							$
								'bmp'						]
	'adapt':	allowed_ext = ['fit','fits','fts','txt']
ENDCASE

;strip extension from filename, and check if it's allowed (-1 = FAIL)
FOR i = 0, n_elements(f) - 1 DO BEGIN										$
	ext[i]  	= STRLOWCASE(strmid(f[i],strpos(f[i],'.',/reverse_search)+1))
	checks[i] 	= where(ext[i] eq allowed_ext)
	
	;OK, let's make sure the JPEG images are readable before we load them
	;Use 'QUERY_JPEG' to check: if unreadable then set 'checks' to -1 (FAIL)
	IF (func eq 'preview') THEN BEGIN
		IF (ext[i] eq allowed_ext[6]) OR (ext[i] eq allowed_ext[7]) THEN BEGIN
			jpeg_checks = QUERY_JPEG(f[i])
			IF (jpeg_checks eq 0) THEN checks[i] = -1
		ENDIF
		
		IF (ext[i] eq allowed_ext[8]) THEN BEGIN
			bmp_checks = QUERY_BMP(f[i])
			IF (bmp_checks eq 0) THEN checks[i] = -1
		ENDIF
		
	ENDIF


ENDFOR 

allowed_file	= where(checks ne -1)
; -1 if cancelled, otherwise, one or more indicies >= 0

CASE allowed_file[0] OF
	-1: 	filenames = ['']
	ELSE:	filenames = f[allowed_file]
ENDCASE

RETURN,filenames

END;---------------------------------------------------------------------------;
;------------------------------------------------------------------------------;
;+
; NAME: 
;		DIVA_FILE__DEFINE
; AUTHOR:
;		John A. Rainnie - RAL (j.a.rainnie@rl.ac.uk)
; PURPOSE:
;		This procedure defines the "diva_file" (named) structure (see
;		IDL help: "Automatic Stucture Definition").
; INPUTS:
;		None
;-
;------------------------------------------------------------------------------;
Pro diva_file__define
;------------------------------------------------------------------------------;
junk = {     diva_file,	    	    	    	                            $
    	    	    	f   	    :'',     	                            $
		    			pathname    :'',	                            	$
		    	        filename	:'',									$
		    	        file_str	:'',									$
		    	        file_ext	:'',									$
		    	        file_unit	:0,   									$
						file_format :'', 									$
						filesize	:0L 									$
    	}
End;---------------------------------------------------------------------------;
;------------------------------------------------------------------------------;
;+
; NAME:
;		DIVA_FILE_INIT
; AUTHOR:
;		John A. Rainnie - RAL (j.a.rainnie@rl.ac.uk)
; PURPOSE:
;		This procedure assigns real values to 'diva_file' structure tags
; INPUTS:
;		f	- a filename
; OUTPUTS:
;		'diva_file' structure
; PROCEDURE:
;		The input filename is sliced'n'diced to populate 'diva_file'
;		structure.
;-
;------------------------------------------------------------------------------;
Pro diva_file_init, diva_file, f
;------------------------------------------------------------------------------;

;where f = full_filename    		eg; '/home/dir/data/images/data.raw'
diva_file.f 		= f

;pathname   	    	    		eg; '/home/dir/data/images/'
pathname			= strmid(f,0,strpos(f,'/',/reverse_search)+1)  
diva_file.pathname	= pathname

;filename   	    	    		eg; 'data.raw'
filename			= strmid(f,  strpos(f,'/',/reverse_search)+1) 
diva_file.filename	= filename

;strip pathname and extension		eg; 'data'
file_str			= strmid(filename,0,strpos(filename,'.',/reverse_search))
diva_file.file_str	= file_str

;extension  	    	    		eg; 'raw'
file_ext			= STRLOWCASE(strmid(f,  strpos(f,'.',/reverse_search)+1))
diva_file.file_ext	= file_ext

CASE file_ext[0] OF
	'img'	:	diva_file.file_format = 'type_img'
	'dat'	:	diva_file.file_format = 'type_img'
	'raw'	:	diva_file.file_format = 'type_img'
	'fit'	:	diva_file.file_format = 'type_fit'
	'fits'	:	diva_file.file_format = 'type_fit'
	'fts'	:	diva_file.file_format = 'type_fit'
	'jpg'	:	diva_file.file_format = 'type_jpg'
	'jpeg'	:	diva_file.file_format = 'type_jpg'
	'bmp'	:	diva_file.file_format = 'type_bmp'
	ELSE	:	stop
ENDCASE

r = findfile(f,count = count)
IF (count eq 1) THEN BEGIN
	;file size (in bytes)
	openr,1,f
	file_size = FSTAT(1)
	diva_file.filesize = file_size.size
	close,1
ENDIF

End;---------------------------------------------------------------------------;
;------------------------------------------------------------------------------;
;+
; NAME:
;		DIVA_GET_FILENAME
; AUTHOR:
;		John A. Rainnie - RAL (j.a.rainnie@rl.ac.uk)
; PURPOSE:
;		This function returns a filename that will be used to save a file
; PROCEDURE:
;		IDL's DIALOG_PICKFILE is used to retrieve a filename. A guess name
;		is supplied as a default. A 'while' loop is employed to ensure the
;		user-supplied filename is not a null-string and has a valid FITS
;		extension. Furthermore, if the filename already exists, a MODAL
;		dialog will ask the user whether or not it should be overwritten
; INPUTS:
;		guess_name	- a name derived from the original filename combined with
;						another string based on a particular function
;		pathname 	- the pathname of the source file  
;		widget_id	- a parent widget id of DIALOG_PICKFILE 
; OUTPUTS:
;		get_f		- a filename
;-
;------------------------------------------------------------------------------;
FUNCTION diva_get_filename,guess_name,pathname,widget_id
;------------------------------------------------------------------------------;
;initialize 'filename_ok' to zero
filename_ok = 0
WHILE (filename_ok eq 0) DO BEGIN

	get_f 	= dialog_pickfile(file=guess_name,filter='*.f*t',				$
							/write,path = pathname,/fix_filter, 			$
							dialog_parent=widget_id)
	;ensure user can't select a null string!!!
	CASE get_f OF
		'': 	filename_ok = 0
		ELSE:	filename_ok = 1
	ENDCASE
	;check for valid fits extension -->  ".fit", ".fits", ".fts"
	file_ext=strmid(get_f,strpos(get_f,'.',/reverse_search)+1)
	CASE file_ext OF
		'fit':		filename_ok = 1
		'fits':		filename_ok = 1
		'fts':		filename_ok = 1
		ELSE:		filename_ok = 0
	ENDCASE

	;are they any existing filenames with this name??? If so, bring
	;up a QUESTION dialog box to ask for overwriting permission. If
	;declined, then we're still in the WHILE loop...so we revert back
	;to the DIALOG_PICKFILE gui
	r = findfile(get_f,count=c)
	IF (c gt 0) THEN BEGIN
		check = dialog_message('This filename already exists - ' +		$
					'overwrite?',/question,dialog_parent=widget_id,		$
					/default_no)
		CASE check OF
			'Yes':		filename_ok = 1
			'No':		filename_ok = 0
		ENDCASE
	ENDIF

ENDWHILE

return,get_f
END;---------------------------------------------------------------------------;
;------------------------------------------------------------------------------;
