;+
; NAME:
;     WRITE_TPSEG
; PURPOSE:
;     Writes total power calibration results from either TPCALCHEK or
;     CTRCALCHEK to the data (.ARC) file, and updates the INDEX records
;     to point to the new calibration.
; CATEGORY:
;     OVRO APC DATA CALIBRATION
; CALLING SEQUENCE:
;     result = write_tpseg(filename,hrec,segtyp,data1[,data2])
; INPUTS:
;     filename   the name of the file containing the data.
;     hrec       the record number of the scan header for the
;                  calibration scan (either REFTPCAL or TPUPDATE).
;     segtyp     the segmentcode for the type of calibration, either
;                  !SEGM.TPCAL or !SEGM.TPUPD.
;     data1      the binary segment records of the appropriate data,
;                  either 2 TPCAL segment records or 2 TPUPD segment
;                  records, as intarr(1024,2).
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     data2      the binary segment records of the TPCAL data, as
;                  intarr(1024,2).  If SEGTYP is !SEGM.TPCAL, then
;                  data2 is the same data as data1.  If omitted,
;                  no primary total power calibration update is
;                  done.  See comments for further information.
; ROUTINES CALLED:
;     openarc, getdata, tl_decode, ovsa_get_index, put_index
; OUTPUTS:
;     result     a flag indicating success or failure.  0 = fail,
;                  1 = success.
; COMMENTS:
;     The DATA2 argument is used as a switch to indicate that the
;     primary total power calibration should be updated.  If omitted,
;     the TPCAL or TPUPD segment is written only to the area left
;     blank for the purpose (by ARCHIVE) in the REFTPCAL or TPUPDATE
;     scan.  If included, the TPCAL segment will be written as part
;     of a new HOUSEKEEPING scan at the end of the file, and the
;     index record will be set to point to this new HOUSEKEEPING
;     entry.
; SIDE EFFECTS:
;     Changes are made to the data (.ARC) file.
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 12-Nov-2000 by Dale Gary
;     18-Jul-2001 GN
;       Replaced get_index by ovsa_get_index to avoid conflict with Yohkoh
;     27-Aug-2005  DG
;       The number of TPCAL and TPUPD records has increased from 2 to 4, so
;       this routine has been modified accordingly.  It will still work for
;       older data, and keys off the number of records passed in.
;-

function write_tpseg,filename,hrec,segtyp,data1,data2

   ; Open the .ARC file for writing
   lun = openarc(filename,a,nrec,/update)

   ; Get the record after the header record of the CTRCAL scan, and see if it
   ; has a segmentcode of zero or !SEGM.CTRCAL (indicates that it can be written to)
   rec = hrec
   ntot = n_elements(data1[0,*])
   ; Loop over the NTOT records of the TPUPDATE segment
   for i = 0,ntot-1 do begin
      ; Get a record from the .ARC file
      data = getdata(rec,a)
      tlsnew = tl_decode(data)
      ; Check that its segmentcode is as expected
      if (tlsnew.segmentcode eq 0 or tlsnew.segmentcode eq segtyp) then begin
         data1[0,i] = tlsnew.nrc  ; Put record number into SDARYREC (from WRITE_TPUPDREC)
         a(rec) = data1[*,i]      ; Write SDARYREC to the file in place of the current one
         rec = rec + 1             ; Increment to next record
      endif else begin
         CASE segtyp OF
            !SEGM.TPUPD: ans = dialog_message(['WRITE_TPSEG: CTRCAL does not have room for ',$
                               'TPUPDATE segment.','You can fix this by using INSERT_REC',$
                               'to insert new records.'],/error)
            !SEGM.TPCAL: ans = dialog_message(['WRITE_TPSEG: REFTPCAL does not have room for ',$
                               'TPCAL segment.','You can fix this by using INSERT_REC',$
                               'to insert new records.'],/error)
            ELSE:
         ENDCASE
         free_lun,lun
         return,0     ; Wrong segmentcode so bail
      endelse
   endfor

   ; Change INDEX template records for TPUPD to point to the new record
   ; for every scan in the file
   idx = ovsa_get_index(a,nrec)
   i_templ = where(idx.codes eq segtyp)
   for i = 0, idx.nscans-1 do begin
      (*idx.pscan)[i].recs[i_templ] = tlsnew.nrc-(ntot-1)
   endfor

   ; If an update of the primary calibration was called for, find and copy
   ; the HOUSEKEEPING records to the end of the file, then overwrite the
   ; TPCAL segment with the new results.  Finally, change the INDEX template
   ; records to TPCAL to point to the new record for every scan in the file
   if (n_elements(data2) ne 0) then begin
      ntot2 = n_elements(data2[0,*]) ; Number of records to write
      ; The Ephemeris segment is the first segment in the HOUSEKEEPING scan,
      ; so get first Ephemeris segment and then look at next earlier record
      i_templ = where(idx.codes eq !SEGM.EPHEM)
      hskrec = (*idx.pscan)[0].recs[i_templ]-1  ; This is the HOUSEKEEPING header
      data = getdata(hskrec-1,a)
      hsktls = tl_decode(data)
      rec = hskrec
      while(hsktls.scancode eq !SCAN.HSKEEP) do begin
         data = a(rec-1)
         data[0] = nrec+1
         a(nrec) = data
         rec = rec + 1
         nrec = nrec + 1
         data = getdata(rec-1,a)
         hsktls = tl_decode(data)
         if (hsktls.segmentcode eq !SEGM.TPCAL) then begin
            ; The next record is the TPCAL segment so write the two PRIMREC
            ; records and skip the next NTOT2 input records.  NB: We assume
            ; that if the TPUPD records were successfully written, then the
            ; number of TPCAL records is the same, so we do not check the
            ; number here.  If there are only 2, and 4 are written, it will
            ; mangle the file...
            for i = 0, ntot2-1 do begin
               data2[0,i] = nrec+1
               a(nrec) = data2[*,i]
               nrec = nrec+1
               rec = rec+1
            endfor
         endif
      endwhile
      i_templ = where(idx.codes eq !SEGM.TPCAL)
      for i = 0, idx.nscans-1 do begin
         (*idx.pscan)[i].recs[i_templ] = data2[0,0]
      endfor
   endif
   result = put_index(a,nrec,idx)
   free_lun,lun
return,1
end