;+
; NAME:
;     WRITE_GCPARM
; PURPOSE:
;     Writes the gain parameters determined during gain calibration
;     (GCALCHEK) into a standard database file.
; CATEGORY:
;     OVRO APC ANALYSIS GCALCHEK
; CALLING SEQUENCE:
;     result = write_gcparm(gcparm,tls[,msglun=msglun])
; INPUTS:
;     gcparm   an array of gain parameters as determined by GCALCHEK.
;     tls      a standard time/label structure from the scan header
;                segment record of the GCAL scan.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     msglun   the logical unit number of GCAL.MSG file.  If nonzero,
;                indicates that the routine was called from a command
;                file, so issue no modal messages, and print any error
;                messages to msglun.
; ROUTINES CALLED:
; OUTPUTS:
;     result   gives an indication of the success of the attempt to
;                write the offsets to the file.  If -1, the attempt
;                failed, 0 otherwise.
; COMMENTS:
;     The data are written to the standard file, yyyymm.GNP, where yyyy
;     is the 4-digit year and mm is the 2-digit month.  If the file
;     does not exist, it is created.  If the file exists it is searched
;     for an entry corresponding to the date and time in the header.  If
;     no entry exists a new entry is inserted in the appropriate
;     place.  If an entry for this date does already exist then the
;     user is asked to verify overwriting the existing data.
; SIDE EFFECTS:
;     Data are written to the standard file.
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 14-Mar-1998 by Dale E. Gary
;     15-Mar-1998  DG
;       Added msglun switch for unattended operation.
;     15-Jun-1998  DG
;       Changed name of routine and made slight change to header format
;-
function write_gcparm,gcparm,tls,msglun=msglun

   IF (NOT keyword_set(msglun)) THEN msglun = 0

   ; Strip out year and doy from yrday string, to use as arguments to
   ; CVDOY routine.  CVDOY returns a three element array with year, month,
   ; and day, all numeric.
   year = strmid(tls.yrday,0,4)
   doy = strmid(tls.yrday,5,3)
   out = cvdoy(year,doy)

   ; Read the time/label string time data into numerical variables
   reads,tls.yrday+tls.timstr,yr,day,hr,mn,format='(I4,1X,I3,1X,I2,1X,I2)'

   ; Convert to a double-precision number with the time encoded as
   ; decimal day, then divided by 1000 to add to year.day formatted
   ; number [e.g. 1998.023 + ((hr+mn/60)/24)/1000].  This will be
   ; compared to similar numbers in an existing .OFF file to find
   ; where the current entry should be inserted.
   yrday = double(yr)+double(day + (hr+mn/60.d0)/24.d0)/1.d3

   ; Create filename from elements
   filename = !defaults.dbdir + $
              string(out(0),out(1),format='(I4,I2.2)') + '.GNP'

   ; See if the filename already exists and act accordingly
   f = findfile(filename,count=n)
   if (n ne 0) then begin
      ; File exists.  Open it for reading.
      openr,lun,/get_lun,filename
      line = ' '
      ; Read and save header lines into OUT array
      hline1 = (hline2 = (hline3 = line))
      readf,lun,hline1
      readf,lun,hline2
      readf,lun,hline3
      out = [hline1,hline2,hline3]
      ans = 'No'

      ; Go through the entries in the file one at a time until EOF is
      ; reached.
      while (NOT eof(lun)) do begin

         ; Read a line and convert its time label to year.day as above
         readf,lun,line
         reads,line,lyr,lday,lhr,lmn,format='(I4,1X,I3,1X,I2,1X,I2)'
         lyrday = double(lyr)+double(lday + (lhr+lmn/60.d0)/24.d0)/1.d3

         ; Compare this entry with the new entry to be inserted
         if (lyrday lt yrday) then begin

            ; The new entry is after this one, so just save the line into
            ; the OUT array as is and continue.
            out = [out,line]

         endif else if (lyrday eq yrday) then begin

            ; Assume overwrite if routine was called from a command
            ; file (as indicated by msglun).
            if (msglun NE 0) then ans = 'Yes' else begin

               ; There is already an entry in the file for this
               ; date/time.  Ask the user whether to overwrite it.
               ; This should only happen when the entry is being
               ; redone off-line.
               ans = widget_message(['An entry already exists in '+$
                  filename,'Would you like to overwrite it?'],/QUESTION)

            endelse

            if (ans eq 'Yes') then begin

               ; The user wants to overwrite the line, so insert the
               ; current entry into the out array and continue.
               out = [out,string(tls.yrday,tls.timstr,gcparm,$
                                      format='(A8,A9,5(1X,6f6.3))')]
            endif else begin

               ; The user does not want to overwrite the line, so
               ; write nothing and bail out.
               free_lun,lun
               return,-1
            endelse
         endif else begin

            ; This entry is after the new entry.  If this is the first
            ; entry after the new entry then ans = 'No', so insert the
            ; new entry ahead of it, copy this entry to the OUT
            ; array, set ans = 'Yes', and continue.
            if (ans eq 'No') then begin
               out = [out,string(tls.yrday,tls.timstr,$
                      gcparm,format='(A8,A9,5(1X,6f6.3))'),line]
               ans = 'Yes'
            endif else begin
               out = [out,line]
            endelse
         endelse
      endwhile

      ; We have reached the end of the file.  Either the ans string
      ; is 'Yes' indicating that the line is already written, or it
      ; is 'No' indicating that the new entry is to be written at the
      ; end of the file.  In the latter case, write it to the OUT array.
      if (ans eq 'No') then out = [out,string(tls.yrday,tls.timstr,$
                                   gcparm,format='(A8,A9,5(1X,6f6.3))')]

      free_lun,lun

      ; Open a new file (this deletes the old one) and write the
      ; completed OUT array to it.
      openw,lun,/get_lun,filename
      printf,lun,out,format='(A)'
      free_lun,lun
   endif else begin

      ; File does not already exist, so just open a new file and write
      ; the entry to it.
      openw,lun,/get_lun,filename

      ; Write out the header lines
      hline1 = '--Date-- --Time--  -------------Antenna 1-------------'+$
                                '  -------------Antenna 2-------------'+$
                                '  -------------Antenna 4-------------'+$
                                '  -------------Antenna 5-------------'+$
                                '  -------------Antenna 6-------------'
      hline2 = 'YYYY.DOY HH:MM:SS  Nonln  5 DB 10 DB 20 DB 20*DB RESID'+$
                                '  Nonln  5 DB 10 DB 20 DB 20*DB RESID'+$
                                '  Nonln  5 DB 10 DB 20 DB 20*DB RESID'+$
                                '  Nonln  5 DB 10 DB 20 DB 20*DB RESID'+$
                                '  Nonln  5 DB 10 DB 20 DB 20*DB RESID'
      hline3 = '-------- --------  ----- ----- ----- ----- ----- -----'+$
                                '  ----- ----- ----- ----- ----- -----'+$
                                '  ----- ----- ----- ----- ----- -----'+$
                                '  ----- ----- ----- ----- ----- -----'+$
                                '  ----- ----- ----- ----- ----- -----'

      printf,lun,[hline1,hline2,hline3],format='(a)'
      printf,lun,string(tls.yrday,tls.timstr,$
              gcparm,format='(A8,A9,5(1X,6f6.3))')
      free_lun,lun
   endelse

return,0
end