;+
; NAME:
;     OPENARC
; PURPOSE:
;     Open the archive file of a given filename, and associate
;     the variable A with it, returning the logical unit number.
; CATEGORY:
;     OVRO APC DATA
; CALLING SEQUENCE:
;     lun = openarc(filename,a,nrec[,/update])
; INPUTS:
;     filename  The fully qualified name of the file to open
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     update    A switch to indicate that the file is to be opened
;                 for writing/updating.
; ROUTINES CALLED:
;     widget_message
; OUTPUTS:
;     lun       The logical unit number of the open file.  To
;                 close the file, use the procedure FREE_LUN,lun
;     a         The ASSOC variable associated with the file.
;     nrec      The number of records currently in the file (the
;                 file may grow later)
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 11-Jan-1998 by Dale E. Gary
;     23-Jul-2000  DG
;       Added UPDATE switch to allow open for writing.  Also added
;       error exit if file length is not a multiple of 2048.
;     16-May-2002 GN
;       Added AUTO switch to not display widget message when called in auto mode
;-

function openarc,filename,a,nrec,update=update,auto=auto

   ; Open file and associate variable A to it

   CATCH, err_stat
   if (err_stat eq 0) then begin
      if (keyword_set(update)) then openu,lun,/get_lun,filename $
                               else openr,lun,/get_lun,filename
      CATCH,/CANCEL
   endif else begin
      if not keyword_set(auto) then begin
      if (keyword_set(update)) then ans = widget_message('OPENARC: Could not open file for writing.',/error) $
                               else ans = widget_message('OPENARC: Could not open file for reading.',/error)
      end
      CATCH,/CANCEL
      return, 0
   endelse

   a = assoc(lun,intarr(1024))

   ; Calculate the number of records in the file from
   ; the file size (should be a multiple of 2048)
   fs = fstat(lun)
   nrec = fs.size/2048L

   ; If not a multiple of 2048, bail out
   if (nrec*2048 ne fs.size) then begin
      ans = widget_message(['OPENARC: File length not a multiple of 2048.',$
                            'File structure not consistent with OVSA .ARC file.'],$
                            /error)
;      free_lun,lun
;      return,0
   endif

return,lun
end