;+
; NAME:
;     WRITE_OFF
; PURPOSE:
;     Writes the offsets determined during gain calibration (GCALCHEK)
;     into a standard database file.
; CATEGORY:
;     OVRO APC ANALYSIS GCALCHEK
; CALLING SEQUENCE:
;     result = write_off(offsets,header[,msglun=msglun])
; INPUTS:
;     offsets  an array of channel offsets as determined by GCALCHEK.
;     tls      a standard time/label structure, from the scan header
;                record of the GCAL scan.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     msglun   the logical unit number of GCAL.MSG.  If nonzero, it
;                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.OFF, 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 keyword for unattended operation.
;     15-Jun-1998  DG
;       Slight change to header format
;     18-Jan-2004  DG
;       Write out header according to number of antennas
;-
function write_off,offsets,tls,msglun=msglun

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

   ; Set any NaN values to zero, to avoid problems reading the data
   bad = where(finite(offsets) eq 0,nbad)
   if (nbad ne 0) then offsets(bad) = 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)') + '.OFF'

   ; 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,offsets,$
                                      format='(A8,A9,64f5.1)')]
            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,$
                      offsets,format='(A8,A9,64f5.1)'),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,$
                                   offsets,format='(A8,A9,64f5.1)')]

      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

      nbl = n_elements(offsets)
      case nbl of
        25: begin
              ; Create the header lines
              hline1 = '--Date-- --Time-- Ant1 Ant2 Ant4 Ant5 Ant 6'+$
               ' --BL1-2-- --BL1-4-- --BL1-5-- --BL1-6-- --BL2-4--'+$
               ' --BL2-5-- --BL2-6-- --BL4-5-- --BL4-6-- --BL5-6--'
              hline2 = 'YYYY.DOY HH:MM:SS  TP   TP   TP   TP   TP '+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'
              hline3 = '-------- -------- ---- ---- ---- ---- ----'+$
               ' --------- --------- --------- --------- ---------'+$
               ' --------- --------- --------- --------- ---------'
            end
        36: begin
              ; Create the header lines
              hline1 = '--Date-- --Time-- Ant1 Ant2 Ant4 Ant5 Ant6 Ant7'+$
               ' --BL1-2-- --BL1-4-- --BL1-5-- --BL1-6-- --BL1-7--'+$
               ' --BL2-4-- --BL2-5-- --BL2-6-- --BL2-7-- --BL4-5--'+$
               ' --BL4-6-- --BL4-7-- --BL5-6-- --BL5-7-- --BL6-7--'
              hline2 = 'YYYY.DOY HH:MM:SS  TP   TP   TP   TP   TP   TP '+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'
              hline3 = '-------- -------- ---- ---- ---- ---- ---- ----'+$
               ' --------- --------- --------- --------- ---------'+$
               ' --------- --------- --------- --------- ---------'+$
               ' --------- --------- --------- --------- ---------'
            end
        49: begin
              ; Create the header lines
              hline1 = '--Date-- --Time-- Ant1 Ant2 Ant4 Ant5 Ant6 Ant7 Ant8'+$
               ' --BL1-2-- --BL1-4-- --BL1-5-- --BL1-6-- --BL1-7-- --BL1-8--'+$
               ' --BL2-4-- --BL2-5-- --BL2-6-- --BL2-7-- --BL2-8-- --BL4-5--'+$
               ' --BL4-6-- --BL4-7-- --BL4-8-- --BL5-6-- --BL5-7-- --BL5-8--'+$
               ' --BL6-7-- --BL6-8-- --BL7-8--'
              hline2 = 'YYYY.DOY HH:MM:SS  TP   TP   TP   TP   TP   TP   TP '+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'+$
               '  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos  sin  cos'
              hline3 = '-------- -------- ---- ---- ---- ---- ---- ---- ----'+$
               ' --------- --------- --------- --------- ---------'+$
               ' --------- --------- --------- --------- ---------'+$
               ' --------- --------- --------- --------- ---------'+$
               ' --------- --------- --------- --------- --------- ---------'
            end
      else: begin
                print,'WRITE_OFF: Unexpected number of offsets (should be '
                print,'one of 25, 36, or 49.'
                free_lun,lun
                return,-1
            end
      endcase
      printf,lun,[hline1,hline2,hline3],format='(a)'
      printf,lun,string(tls.yrday,tls.timstr,$
              offsets,format='(A8,A9,64f5.1)')
      free_lun,lun
   endelse

return,0
end