; Convert output of POLN program to a visibility database
; for use by Jeongwoo's mapping program

pro poln2vis,filename,outfile=outfile

   ; Restore the results of POLN
   if (n_elements(filename) eq 0) then begin
      filename = dialog_pickfile(/read,path=!defaults.workdir,filter='*.sav')
      if (filename eq '') then return
   endif

   ; Restore data in variables:
   ; rdat,ldat,tavg,f,uvt,header
   restore,filename

   ; For now, just add polarizations, to produce total intensity
   idat = rdat + ldat

   nt = n_elements(tavg)
   nf = n_elements(f)
   nant = header.nant
   nb = nant*(nant-1)/2

   ; Convert UVT[nant,nant,nt] to an array UV[nant^2,nt]
   uv = reform(uvt,nant*nant,nt)

   ; Develop a list of indexes into the nant x nant array corresponding
   ; to baseline indexes
   upper = (lower = intarr(nb))
   k = 0
   for i = 0, nant-2 do begin
      for j = i+1, nant-1 do begin
         upper[k] = i*nant+j
         lower[k] = j*nant+i
         k = k + 1
      endfor
   endfor

   ; Remove the last three baselines (the small-small baselines)
   ; as an interim test...
   nb = nb - 3
   upper = upper[0:n_elements(upper)-4]
   lower = lower[0:n_elements(lower)-4]

   ; Declare storage for complex representation of visibilities and
   ; corresponding uv values
   visf = complexarr(nb*nt,nf)
   uvf = complexarr(nb*nt,nf)

   ; Loop over frequency
   for k = 0, nf-1 do begin
      for i = 0, nt-1 do begin
         uvf[i*nb:(i+1)*nb-1,k] = complex(uv[upper,i],uv[lower,i])*f[k]
         for j = 0, nb-1 do begin
            visf[i*j,k] = complex(idat[j*2+1,k,i],idat[j*2,k,i])
         endfor
      endfor
   endfor

   if (not keyword_set(outfile)) then outfile = dialog_pickfile(/write,path=!defaults.workdir,filter='*.sav')
   if (outfile eq '') then begin
      print,'POLN2VIS: No outfile specified.  Exiting without save.'
      return
   endif

   mtype = 'AR'
   save,filename=outfile,uvf,visf,f,mtype

return
end