;+
; NAME:
;       imagr
; PURPOSE:
;       imaging of OVSA visib.
;   does one of [Dirtymap, CLEAN, SELFCAL, MeM, & Fwd_fit]
;   the latter three requires CLEAN done beforehand, or
;   you can do CLEAN here and do it later.
;
; CATEGORY:
;   OVSA APC imaging
; CALLING SEQUENCE:
;       imagr
; INPUTS:
;   (input parameters are set by interaction thru command line inputs.
;   Then this information is passed to one of imaging programs of choice)
;
;   Set parameters
;   contained in inpfile
;   input uv file name  inp.infile  'uvmar22.sav'
;   time range          inp.timer   [d0,h0,m0,s0,d1,h1,m1,s1]
;   polarization        inp.poln    'R'
;   clean box           inp.clbox   [0] or [-10,-10,10,10]
;   frequency range     inp.freqr   [15,16,17,18]
;   imsize              inp.imsiz   64,128,256,512 only
;   cellsize            inp.cellsiz 0 => determine from data
;   output uv file name inp.outfile 'img.sav'
;   etc...
;
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;       Input parameters are read from inpfile rather than keywords
; ROUTINES CALLED:
;   clean.pro
;   selfcal.pro
;   mem.pro
;   fwdfit.pro
; OUTPUTS:
;       im structure containing map, xy-scale, and max TB
; COMMENTS:
;
;  Supposedly functions similar to IMAGR/AIPS but with major differences:
;  1. imsize can be chosen but cellsize is determined accordingly
;   within this code.
;  2. H\"ogbom algorithm rather than BCG's is used for cleaning
;  3. A truncated gaussian is used for Convol-Grdding fcn.
;  4. Multifrequencies at OVSA is handled using freqid array
;   (Linear) Frequency synthesis done as you specify multiple freqids,
;   which needs not be continuous.
;
; SIDE EFFECTS: -
; RESTRICTIONS:
;       1. After imagr_vsel is called, sign of u is flipped & used so elsewhere.
;   2. Works only when there are valid data at all 7 bsl at least 1 time
;           (done so within imagr_vsel.pro)
; MODIFICATION HISTORY:
;     Written 05-JAN-2001 by JL
;     01-Mar-2003  DG
;       Many changes to the general package.  Now can set CELLSIZE (if 0,
;       the cellsize is automatically determined), Clean Gain, Clean Min.
;       Can do all work in setting clean boxes with the mouse, no need to
;       switch between mouse and command line.  After making a map, now
;       goes back to the beginning to await changes to make a new map.  Now
;       runs as a procedure rather than using .RUN.  Now will name the
;       output file automatically (specify OUTNAME default).  Now also
;       plots image as a map, with properly placed solar grid lines.
;   14-Mar-2014  DG
;      Changed some routine names by appending ovsa_ to avoid potential conflict with the copies of the original
;      routines located in the ssw\hessi tree
;-

pro imagr,refmap=refmap

inpexist = 'n'
if ((findfile('imagr.inp'))[0] ne '') then restore,'imagr.inp' $
else begin
 inuvfile='00mar22.uv'
 tbegstr ='184400'
 tendstr ='184410'
 poln    ='R'
 Bif     =1 ; >=1
 Eif     =5 ; <=nf
 imsiz   =256           ; 64,128,256,512 only
 cellsiz =0 ; => determine from data
 clbox   =[-10,-10,10,10]
 niter   =2000
 clgain  =0.05
 clstop  =5.
 dowhat  ='C'
 methodstr  ='CLEAN only'
 outfile ='imagr.fts'
endelse
if (n_elements(clgain) eq 0) then clgain  =0.05
if (n_elements(clstop) eq 0) then clstop  =5.    ; Note clgain should be less or equal to clstop/100.
if (n_elements(cellsiz) eq 0) then cellsiz =0.
partab  =['UV','TB','TE','PO','BI','EI','IM','CE','CG','CM','OU']

print,'======================================================'
print,'IMAGR:  a main imaging routine for OVSA data (2001 JL)'
print,'======================================================'

start:
print,' '
print,' ____I_M_A_G_R_______________________________________'
print,'| Parameters       || List | View | Go | Help | Quit | '
print,' ----------------------------------------------------  '
print,' UVfile name        : ',inuvfile
print,' Tbegin (hhmmss)    : ',tbegstr
print,' Tend  (hhmmss)     : ',tendstr
print,' BIF (>=0)          : ',Bif
print,' EIF (<nf)          : ',Eif
print,' Polarization       : ',poln
print,' Imsize             : ',imsiz
print,' Cellsize (arcsec)  : ',cellsiz
print,' CGain              : ',clgain
print,' CMin  (pct)        : ',clstop
print,' Do [d, c, s, m, f] : ',methodstr
print,' Output map file    : ',outfile
print,' '
print,'To issue a command, type the cmnd (at least 2 characters)'
print,'To modify param, type item & value (separated by a space)'

;----------------------------------------------------
; Prompt for input and read response from operator.
;----------------------------------------------------

;on_ioerror,errorinput

read:
inline=' '
read,inline,prompt='imagr> '
inline = strtrim(inline,2)
cmnd   = strupcase(strmid(inline,0,2))

if cmnd eq 'LI' then begin
 results = findfile('*.uv')
 print,' '
 print,'List of uv files: '
 print,results,format='(2a30)'
 print,' '
 goto,read
 endif

if cmnd eq 'GO' then goto, donow

if (cmnd eq 'VI') or (cmnd eq 'IN') then goto,start

if cmnd eq 'HE' then begin
 spawn,'more imagr.hlp',helptxt
 for i=0,n_elements(helptxt)-1 do print,helptxt[i]
 goto,read
 endif

if cmnd eq 'QU' then goto,getout

if cmnd eq 'DO' then begin
  strbeg=strpos(inline,' ')+1
  strlng=strlen(inline)-strbeg
  reads,strmid(inline,strbeg,1),dowhat
  dowhat=strupcase(dowhat)
  case dowhat of
    'D': methodstr='DIRTY MAP'
    'C': methodstr='CLEAN MAP'
    'S': methodstr='CLEAN + SelfCal'
    'M': methodstr='CLEAN + MEM'
    'F': methodstr='CLEAN + FwdFit'
  endcase
  goto,read
endif

; at this point user want to change a parameter
par_exist=where(cmnd eq partab)
parindx  =par_exist[0]
if (parindx ne -1) then begin
 strbeg=strpos(inline,' ')+1
 strlng=strlen(inline)-strbeg
 case parindx of
  0: reads,strmid(inline,strbeg,strlng),inuvfile
  1: reads,strmid(inline,strbeg,strlng),tbegstr
  2: reads,strmid(inline,strbeg,strlng),tendstr
  3: reads,strmid(inline,strbeg,1),poln
  4: reads,strmid(inline,strbeg,strlng),bif
  5: reads,strmid(inline,strbeg,strlng),eif
  6: reads,strmid(inline,strbeg,strlng),imsiz
  7: reads,strmid(inline,strbeg,strlng),cellsiz
  8: reads,strmid(inline,strbeg,strlng),clgain
  9: reads,strmid(inline,strbeg,strlng),clstop
 10: reads,strmid(inline,strbeg,strlng),outfile
 endcase
    poln=strupcase(poln)
 goto,read
endif

errorinput:
print,'Error in input -- please reenter.'
goto,read

;------------------------------------------
; end setting parameters & organize them
;------------------------------------------
donow:

inp ={inuvfile:inuvfile, tbegstr:tbegstr,tendstr:tendstr, $
    bif:bif, eif:eif, poln:poln, imsiz:imsiz, cellsiz:cellsiz, $
    niter:niter, clgain:clgain, clstop:clstop, $
    method:methodstr, outfile:outfile, clbox:clbox}

;save,filename='imagr.inp',inuvfile,tbegstr,tendstr,poln,Bif,Eif, $
;    imsiz,clbox,niter,clgain,clstop,dowhat,methodstr,outfile

;-----------------------------------------
;  Visibility Data restoration/selection
;-----------------------------------------

imagr_vsel, inp, uv_ij, vis_ij, wgt_ij, vsl

if vsl.chk eq 0 then goto,nodata

;-------------------------------
;   Imaging
;-------------------------------

misc =['Remark: '+methodstr] ; will be altered if not 'D' or 'C'

case dowhat of
'D' : ovsa_clean, uv_ij, vis_ij, inp, vsl, map, cln, /dirty
'C' : ovsa_clean, uv_ij, vis_ij, inp, vsl, map, cln;,clbox=clbox;, show=1
'S' : begin
      ovsa_clean, uv_ij, vis_ij, inp, vsl, cmap, cln
      slfcal, cmap, cln, uv_ij, vis_ij, wgt_ij, map, misc
      end
'M' : begin
      ovsa_clean, uv_ij, vis_ij, inp, vsl, cmap, cln
      ovsa_mem, cmap, cln, uv_ij, vis_ij, wgt_ij, map, misc
      end
'F' : begin
      ovsa_clean, uv_ij, vis_ij, inp, vsl, cmap, cln
      fwdfit, cmap, cln, uv_ij, vis_ij, wgt_ij, map, misc
      end
endcase

;------------------
;  S a v e
;------------------

sav:
  data=map
header=imagr_whdr(inp,vsl,cln,misc)

clbox = inp.clbox
save,filename='imagr.inp',inuvfile,tbegstr,tendstr,poln,Bif,Eif, $
    imsiz,cellsiz,clbox,niter,clgain,clstop,dowhat,methodstr,outfile

if (inp.outfile eq 'default') then begin
   date = sxpar(header,'DATE_OBS')
   time = sxpar(header,'TSTART')
   f = sxpar(header,'FREQ')
   if (f ge 10.) then fstr = string(f,format='(F4.1)') else fstr = '0'+string(f,format='(F3.1)')
   outfile=strmid(date,0,4)+strmid(date,5,2)+strmid(date,8,2)$
           +'_'+time+'_'+fstr+'.fts'
   print,'IMAGR: outfile = ',outfile
endif

if (n_elements(header) eq 0) then writefits,outfile,data $
                             else writefits,outfile,data,header

window,5,xsiz=512,ysiz=512
if (keyword_set(refmap)) then ovsa = display_ovsamap(outfile,refmap=refmap) $
                         else ovsa = display_ovsamap(outfile)
; Plot result with solar grid
;ovsa = ovsa2map(outfile)
;window,5
;plot_map,ovsa,grid=10

;a = sxpar(header,'BMAJ')
;b = sxpar(header,'BMIN')
;phi = sxpar(header,'BPOS')
;solp = sxpar(header,'SOLP')
;phi = phi - solp
;phi = phi*!dtor
;th = findgen(361)*!dtor
;x = a*cos(th)
;y = b*sin(th)
;xp = x*cos(phi) - y*sin(phi)
;yp = x*sin(phi) + y*cos(phi)
;polyfill,!x.crange[0]+xp+2*max(xp),!y.crange[1]+yp-2*max(yp)

print,'IMAGR: successful execution. '
outfile = inp.outfile

 goto,start

;------------------
; E X I T
;------------------

nodata:
  print,'Warning: either no data or wrong time selected.'

getout:
  print,'IMAGR: quit without imaging'

  save,filename='imagr.inp',inuvfile,tbegstr,tendstr,poln,Bif,Eif, $
    imsiz,cellsiz,clbox,niter,clgain,clstop,dowhat,methodstr,outfile

endnow:

end
