pro close_amf,file

   if (n_elements(file) eq 0) then begin
      filename = pickfile(path=!defaults.workdir,filter='*.amf')
      if (filename eq '') then return
   endif else filename = file

   nhed = 3   ; Number of header lines for each section of AMF file
   nb   = 7   ; Number of baseines in the file

   openr,lun,/get_lun,filename
   ; Find out how many frequencies in the file by looking for
   ; number of lines between two instances of '----'
   line = ''
   k = (k1 = (k2 = 0))
   while (not EOF(lun) and k2 eq 0) do begin
      readf,lun,line
      k = k + 1
      if (strpos(line,'---- ') eq 0) then begin
         if (k1 eq 0) then k1 = k else k2 = k
      endif
   endwhile

   ; k1 now points to the first '---- ' and k2 to the second.  If k2 is
   ; zero, the file did not contain two '---- ' strings.
   if (k2 eq 0) then begin
      print,'CLOSE_AMF: Invalid structure for input file'
      free_lun,lun
      return
   endif

   ; Obtain the number of frequencies
   nf = k2 - k1 - nhed
   ; Rewind the input file
   point_lun,lun,0

   ; Structure of data in an AMPHIT file
   in = {hed:strarr(nhed),data:fltarr(6,nf)}
   calin = fltarr(6,nf,nb)
   hedin = strarr(nhed,nb)

   ; Read and store the data from the file
   for i = 0, nb-1 do begin
      readf,lun,in
      calin(*,*,i) = in.data
      hedin(*,i) = in.hed
   endfor

   free_lun,lun

   bad = where(calin eq -99.9,nbad)
   if (nbad gt 0) then calin[bad] = !values.f_nan
   ; Force phase closure of each scan of data
   calout = cal_pclose(calin)  ; This will remove NaN in the phase column

   break_file,filename,disk,dir,name,ext
   filename = pickfile(path=disk+dir,file=name+'.cal',filter='*.cal',/write)
   if (filename eq '') then return
   if (oktowrite(filename) eq 'Yes') then begin
      openw,lun,/get_lun,filename
      bad = where(finite(calout) eq 0,nbad)
      if (nbad ne 0) then calout[bad] = -99.9
      for i = 0, nb-1 do begin
         printf,lun,hedin(*,i),format='(a)'
         for ifrq = 0, nf-1 do printf,lun,calout(*,ifrq,i),format='(f4.1,1x,2f8.3,1x,3(1x,f6.1))'
      endfor
      free_lun,lun
   endif

return
end