;---------------------------------------------------------------------------
; Document name: files_handling.pro
; Created by:    Andre Csillaghy, April 1991
;
; Time-stamp: <Sun Sep 05 2004 07:39:02 csillag tournesol.local>
;---------------------------------------------------------------------------
;
;+
; NAME:
; 	Files_Handling
; PURPOSE:
;	User Interface which handle image files. Makes use of
;	a menu to select the file format. For more information
;	about file formats, we refer to the "RagView User's
;	Guide". The formats accepted are: ascii, fortran
;	unformatted, fits, sb4, sc4, sca.
;	Usually, FITS files are used. Therefore, for FITS files
;	the following facilities are implemented:
;		o reads also gzipped FITS files -- with extensions
;		  ".gz" and ".z"
;	Usually, this procedure is called from the system "RagView"
; CALLING SEQUENCE:
;	Files_Handling, image [, xAxis, yAxis] [ ,totalFileName]
; INPUT:
;	totalFileName: if given WITH EXTENTION, 
;		the user interface 
;		is not activated and the file is read directly. 
; OUTPUTS:
;	image: the two-dimensional array. Its type determined
;		from the file format.
;	xAxis, yAxis: axes corresponding to the x- and y-direction
;		of the image.
; KEYWORDS:
;	STATUS: holds the value "Read" if a file was read,
;		"Not Read" otherwise.
;	FILENAME: holds the filename read, if status is "Read"
; SIDE EFFECTS:
;	In the user interface mode, windows are opened to
;	dialog with the user.
;       The environment variable TMPDIR is used for help files. If
;       TMPDIR is not defined, the current directory is used.
; MODIFICATION HISTORY:
;	Created: A.Csillaghy, ETHZ, April 91, csillag@astro.phys.ethz.ch
;	A.Csilaghy, Oct 92: fits format read/write added
;	A.Cs, Dec. 92 FileMenu proc. used
;	1994: added the option to read compressed files.
;	Sept. 1995: added the mechanism to check links
;		(for use with RAG image archive) ACs
;	April 96: IDL version - ACS
;       March 98: IDL5/Ragview/SSW Adaptation - ACS
;       August 04- change the way to deal with directories. Now the
;                  current dir remains the dir where the ragview
;                  session was started. the file selectionis stored
;                  separately (in the var confusingly called currentdir)
;-


PRO SetBounds, boundary, x, y, xMin, xMax, yMin, yMax
   
  IF N_Elements(boundary) EQ 0 THEN BEGIN
    xMin = 0 & xMax = N_Elements( x ) - 1
    yMin = 0 & yMax = N_Elements( y ) - 1
  ENDIF ELSE BEGIN
    xMin = boundary(0) & xMax = boundary(1)
    yMin = boundary(2) & yMax = boundary(3)
  ENDELSE
END ; Set Bounds


PRO Files_Handling, z, x, y, file, STATUS=status, $
         FILENAME=fileName, BOUNDARY=boundary, $
         SIZES_ON=sizes_on

COMMON Filse_handling_COMMON_block, currentDir

status = 'Not Read'
nPars = N_Params()

IF (nPars NE 4 ) THEN BEGIN
    
    menuLength = 16
    menu = StrArr(menuLength)
    rwLimit = 7
    
    menu(0) = 'READ: dat (ASCII) ...'
    menu(1) = '      fits ...'
    menu(2) = '      for (Fortran Unformatted) ... '
    menu(3) = '      sb4 ...'
    menu(4) = '      sb4 transfered from the VMS system ...'
    menu(5) = '      sca ...'
    menu(6) = '      sca transfered from the VMS system ... '
    menu(7) = 'WRITE: sca ... '
    menu(8) = '       sb4 with byte scaling... '
    menu(9) = '       sb4 interval [0 .. 255] ... '
    menu(10) = '       dat (ASCII) ... '
    menu(11) = '       fits bytes (8 bit/pixel) not scaled ...'
    menu(12) = '       fits bytes (8 bit/pixel) scaled ... '
    menu(13) = '       fits reals (32 bit/pixel) ...'
    menu(14) = 'Exit Files Handling'
    menu(15) = 'Redisplay this Menu'

  choice=0
  index=1

  REPEAT BEGIN
  
    choice=General_Menu(menu, $
	'File Read: Choose Operation, Change Directory or Exit' )

    fileWrite = (choice GT rwLimit) AND (choice LE menuLength - 2)
    IF  fileWrite THEN $
      SetBounds, boundary, x, y, xMin, xMax, yMin, yMax
    

    CASE choice OF
      1: fileType = 'dat'
      2: fileType = 'fit'
      3: fileType = 'for'
      4: BEGIN fileType = 'sb4' & vms = 0 & END
      5: BEGIN fileType = 'sb4' & vms = 1 & END
      6: BEGIN fileType = 'sca' & vms = 0 & END
      7: BEGIN fileType = 'sca' & vms = 1 & END
      8: Sca_Write,z( xMin:xMax, yMin: yMax ), $
	x( xMin: xMax) ,y( yMin: yMax ),/INTERACTIVE
      9: SB4_Write, z( xMin:xMax, yMin: yMax ), $
	x( xMin: xMax) ,y( yMin: yMax ),/INTERACTIVE, $
	/BYTSCL
      10: SB4_Write, z( xMin:xMax, yMin: yMax ), $
	x( xMin: xMax) ,y( yMin: yMax ),/INTERACTIVE
      11: ASCII_Write, z( xMin: xMax, yMin: yMax ), /INTERACTIVE
      12: RAGFitsWrite, z( xMin:xMax,yMin:yMax ), x(xMin:xMax), $
	y( yMin: yMax ), /INTERACTIVE, BUNIT = !z.title, $
	CTYPE1 = !x.title, CTYPE2 = !y.title,  $
	CONTENT = !p.title, /BYTE
      13: RAGFitsWrite, z( xMin:xMax,yMin:yMax ), x(xMin:xMax), $
	y( yMin: yMax ), /INTERACTIVE, BUNIT = !z.title, $
	CTYPE1 = !x.title, CTYPE2 = !y.title,  $
	CONTENT = !p.title, SCALING = 'B'
      14: RAGFitsWrite, z( xMin:xMax,yMin:yMax ), x(xMin:xMax), $
	y( yMin: yMax ), /INTERACTIVE, BUNIT = !z.title, $
	CTYPE1 = !x.title, CTYPE2 = !y.title,  $
	CONTENT = !p.title, SCALING = 'L'
      15: RETURN
    ELSE:
  ENDCASE

  compressed = 0
  IF choice LE rwLimit THEN BEGIN
;------
; Also compressed files are searched
;------

; acs 2004-08-25 make current dir unchanged, and use path variable to
; decide where to read data (with PATH / GET_PATH kwds)
;      IF N_Elements( currentDir ) NE 0 THEN CD, currentDir
      file = Dialog_Pickfile( /READ, FILTER='*.'+fileType+ '*', $
                              /NOCONFIRM, PATH = currentDir, GET_PATH=currentdir )
      fileOrig = file
      Break_File, fileOrig, disk, dir, file, ext
; acs 2004-08-25
;      CD, dir
;      currentDir =  dir
      IF StrPos( ext, '.gz' ) NE -1 THEN BEGIN
          compressed = 1
          ext = RepStr( ext, '.gz', '')
      ENDIF ELSE IF StrPos( ext, '.z' ) NE -1 THEN BEGIN
          compressed = 1
          ext = RepStr( ext, '.z', '' )
      ENDIF
      IF compressed THEN BEGIN
          tmpDir = GetEnv('TMPDIR')
          IF tmpDir EQ '' OR NOT File_Exist( tmpDir ) THEN tmpDir = '.'
          file = tmpDir + '/tmp.' + file + ext
          Spawn, 'gunzip -c < ' + fileOrig + '> ' + file
; acs 2004-09-05 add dir
      ENDIF ELSE file = dir + file + ext
  ENDIF ELSE IF fileWrite THEN RETURN 
  
END UNTIL file NE ''

ENDIF ELSE BEGIN 
    
  file = file(0)     
  fileOrig = file
  compressed = StrPos( file, '.gz' ) NE -1 OR $
      StrPos( file, '.z' ) NE -1
  compressed = compressed(0)
  Break_file, fileOrig, disk, dir, file, ext
  CD, dir
  IF compressed THEN BEGIN
      IF StrPos( ext, '.gz' ) NE -1 THEN BEGIN
          ext = RepStr( ext, '.gz', '')
      ENDIF ELSE IF StrPos( ext, '.z' ) NE -1 THEN BEGIN
          ext = RepStr( ext, '.z', '' )
      ENDIF
      tmpDir = GetEnv('TMPDIR')
      file = tmpDir + '/tmp.'+ file + ext
      Spawn, 'gunzip -c < ' + fileOrig + '> ' + file
  ENDIF ELSE file =  file + ext
  
ENDELSE

title = '' & xLab = '' & yLab = '' & zLab = ''
answer = 0
timeObs = 'No Time'


CASE fileType OF
  'sca': SCA_Read,file,z,x,y,VMS = vms, TITLE = title, $
	XLAB = xLab, YLAB = yLab, ZLAB = zLab
  'sb4': BEGIN
               IF 	vms EQ 0 THEN answer = General_Menu( $
 	['No','Yes'],'Is the x-axis in seconds after midnight ? ')-1 $
               ELSE answer = 0
               SB4_Read, file, z, x, y, VMS = vms, TITLE = title, $
	XLAB = xLab, YLAB = yLab, ZLAB = zLab,  $
	SECS = answer
               z = Float( z )
             END
  'dat': BEGIN
              z = 0.0 & header = ''
              ASCII_Read,file, z, header
              Print, header
              x = LIndGen(N_Elements( z(*,0) )) 
              y = LIndGen(N_Elements( z(0,*) ))             
            END
  'fit': BEGIN
              RAGFitsRead, file, z, x, y, CONTENT = title, $
		CTYPE1 = xLab, CTYPE2 = yLab, BUNIT = zLab, $
		TIMEOBS = timeObs, /SILENT
              IF (!err NE 0) OR N_Elements(z) LT 2 THEN BEGIN
		status = 'Not Read'
		RETURN
              ENDIF
              z = Float( z )
            END
  'for': Fortran_Read,file,z,title,xLab,yLab,zLab,$
	nx,ny,dx,dy,x1,y1
  'sc4': 
  ELSE: BEGIN
    Print,' This type is not known ...'
    RETURN
  END
END

  IF Keyword_Set( SIZES_ON ) THEN BEGIN
    IF ((fileType EQ 'sb4') AND answer) OR $
	(timeObs NE 'No Time') THEN PutHms, 1 $
    ELSE PutHms, 0
  ENDIF

!p.title=title
!x.title=xLab & !y.title=yLab & !z.title=zLab

IF nPars EQ 2 THEN  x = file

status = 'Read'

IF NOT compressed THEN fileName = fileOrig $
ELSE fileName = fileOrig

IF compressed AND STRPOS( file, 'tmp.' ) NE -1 THEN $
    Spawn, 'rm ' + file

END

 
