;+
; NAME:
;     WRITE_FCPARM
; PURPOSE:
;     Writes the frequency parameters determined during gain calibration
;     (FCALCHEK) into standard database files, one for each antenna.
; CATEGORY:
;     OVRO APC ANALYSIS FCALCHEK
; CALLING SEQUENCE:
;     result = write_fcparm(TC_tab,sigma,tls[,msglun=msglun])
; INPUTS:
;     TC_tab     the updated table of tuning current coefficients, of size [NANT,5,NOSC]
;     sigma      an array of standard deviations of the data relative
;                  to the fits (from POLY_FIT routine called in TCFIT2), of size [NANT,NOSC]
;     header     the HEADER structure from the header segment of the FCAL scan.
;     tls        a standard time/label structure from the scan header
;                  segment record of the FCAL scan.
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     msglun   the logical unit number of FCAL.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 files, yyyymm_n.FCH, where yyyy
;     is the 4-digit year, mm is the 2-digit month, and n is the antenna
;     number.  If a 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 standard files.
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 15-Jun-1998 by Dale E. Gary
;     14-Jan-2001  DG
;       Completely rewritten for the new FCAL scheme, which uses a 4th-degree
;       polynomial fit.
;-
function write_fcparm,tc_tab,sigma,header,tls,msglun=msglun

   ; Get the number of antennas from the size of the FC_TAB array
   nant = header.nant
   nosc = n_elements(sigma(0,*))

   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)
   datestr = 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

   for i = 0,nant-1 do begin

      ; Create the output line for this antenna.  Line starts with date
      ; and time
      newline = tls.yrday+strmid(tls.timstr,0,9)
      ; Loop over oscillators
      entries = strarr(3)
      for j = 0,nosc-1 do begin
         ; For each oscillator, encode tuning current coefficients into an entries array of strings.
         entry = string(tc_tab(i,*,j)*10^[-1D,-3D,-5D,-6D,-8D],format='(2(1X,F6.1),3(1X,E10.2))')
         ; Remove extraneous 0's written in E-002, etc., to make them just E-2.
         entry = strmid(entry,0,22)+strmid(entry,24,9)+strmid(entry,35,9)+strmid(entry,46)
         ; Concatenate all of the strings, plus sigma for this oscillator,
         ; and append to the line.
         newline = newline+string(entry,sigma(i,j),format='(A,1X,F4.2)')
      endfor
      thisant = string(header.aatab(i),format='(i1)')
      ; Create filename from elements
      filename = !defaults.dbdir + $
              string(datestr(0),datestr(1),format='(I4,I2.2)') + '_'+thisant+'.FCH'

      ; 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,newline]
               endif else begin

                  ; The user does not want to overwrite the line, so
                  ; write nothing and bail out.
                  free_lun,lun
                  goto,next_ant
               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,newline,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,newline]

         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-- ---------------Low Oscillator----------------'+$
                                   ' ---------------Mid Oscillator----------------'+$
                                   ' ---------------High Oscillator---------------'
         hline2 = 'YYYY.DOY HH:MM:SS TC_off TC_slp   TC(3)    TC(4)    TC(5)  SGMA'+$
                                   ' TC_off TC_slp   TC(3)    TC(4)    TC(5)  SGMA'+$
                                   ' TC_off TC_slp   TC(3)    TC(4)    TC(5)  SGMA'
         hline3 = '-------- -------- ------ ------ -------- -------- -------- ----'+$
                                   ' ------ ------ -------- -------- -------- ----'+$
                                   ' ------ ------ -------- -------- -------- ----'

         printf,lun,[hline1,hline2,hline3],format='(a)'
         printf,lun,newline
         free_lun,lun
      endelse

   next_ant:

   endfor
return,0
end