; Write a section of the OUTPUT amf file, skipping the corresponding
; section of the input file
pro write_sect,lun,olun,out

   nf = n_elements(out[0,*])
   line = ''
   for i = 0,2 do begin
      ; Copy three header lines to output
      readf, lun, line
      printf,olun,line,format='(a)'
   endfor
   for i = 0,nf-1 do begin
      ; Skip data lines of input and print out data to output
      readf,lun,line
      printf,olun,out[*,i],format='(f4.1,1x,2f8.3,1x,3(1x,f6.1))'
   endfor

return
end

; Skip a section of the INPUT amf file, writing nothing to the output file
pro skip_sect,lun,nf

   line = ''
   for i = 0,2 do begin
      ; Skip three header lines of input
      readf, lun, line
   endfor
   for i = 0,nf-1 do begin
      ; Skip data lines of input
      readf,lun,line
   endfor

return
end

pro adjust_amf2

   amfile = dialog_pickfile(filter='*.amf',/read)
   out = readamf(amfile)
   for i = 0, n_elements(out[0,0,0,*])-1 do begin
      calin = out[*,*,*,i]
      out[*,*,*,i] = cal_pclose(calin)
   endfor
   bad = where(out eq -99.9,nbad)
   if (nbad ne 0) then out[bad] = !values.f_nan
   flag = finite(out)

   ; Adjust 1n phases to correct for changes in 12 baseline phase
   dphi = lobe(out[3,*,0,1]-out[3,*,0,0])
   out[3,*,1,1] = lobe(out[3,*,1,1]-dphi)

   dphi = lobe(out[3,*,0,2]-out[3,*,0,0])
   out[3,*,1,2] = lobe(out[3,*,1,2]-dphi)

   dphi = lobe(out[3,*,0,3]-out[3,*,0,0])
   out[3,*,1,3] = lobe(out[3,*,1,3]-dphi)

   ; Take simple average of 12 baseline amplitudes, and stick it into first location
   out[1,*,0,0] = total(reform(out[1,*,0,*]),2)/total(reform(flag[1,*,0,*]),2)

   outfile = dialog_pickfile(filter='*.adj',/write)
   if (outfile eq '') then return

   ; Now read in original amfile and write out new results line by line
   openr,lun,/get_lun,amfile
   openw,olun,/get_lun,outfile

   readf,lun,nf,nbl,nsect
   printf,olun,nf,7,1
   write_sect,lun,olun,out[*,*,0,0]
   write_sect,lun,olun,out[*,*,1,0]
   write_sect,lun,olun,out[*,*,2,0]
   skip_sect,lun,nf
   write_sect,lun,olun,out[*,*,1,1]
   write_sect,lun,olun,out[*,*,2,1]
   skip_sect,lun,nf
   write_sect,lun,olun,out[*,*,1,2]
   write_sect,lun,olun,out[*,*,2,2]

return
end

