!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! @ p_over.greg
! J.Pety 2003
!
! Documentation by S.Guilloteau 2008
!
! Overlay N images 
!
! Argument 
!	&1	Plot sub-directory (unused in default use by GO )
!
! Principle
!   This procedure depends on 4 major global variables
!	NAMES[]      Name of the N images
! TYPES[]     Extension of the N images
!	NREFERENCE	Reference image number 
!	NIMAGES 	  Number of displayed images
!
! When more than 1 image is plotted, only the first one can be
! a background image (bitmap).
!
! All images are resampled to the same 3rd axis grid
! The reference image is the one defining the plot 
!( Limits, 3rd axis sampling)
!
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
@ window_tools.greg
!
!
! Work in specified Plot Directory
define character directory*24
if ("&1none".eq."none") then
   let directory "<greg"
   gtvl\destroy all
else
   let directory "&1"
   change directory <greg
   create directory 'directory'
   change directory 'directory'
   let directory "<greg<"'directory'
endif
gtvl\clear alpha
!
! Setup color table
if (do_color) then
   @ p_color.greg ! Setup a nice color table
endif
!
define logical do_cross
define integer true_first true_last true_step nplanes nadd nbox imark
!
! Load reference image and plot header.
!
let name 'names[nreference]'
let type 'types[nreference]'
symbol aaaref aaa'nreference'
@ header_position
@ p_load.greg   'aaaref'
let spacing     'spacings[nreference]'
@ p_scale.greg  'aaaref'
@ p_level.greg  'aaaref'
@ p_header.greg 'aaaref'
define logical resample
!
! This seems useles here
!SG! greg2\rgdata 'aaaref' /variable
!
if (('aaaref'%x_axis.ne.1).or.('aaaref'%y_axis.ne.2)) then
   let do_cross no
else
   let do_cross yes
endif
!
if .not.exist(aaaref_dim) then
   define integer aaaref_dim /like 'aaaref'%dim /global
endif
if .not.exist(aaaref_convert) then
   define double aaaref_convert /like 'aaaref'%convert /global
endif
let aaaref_dim     'aaaref'%dim
let aaaref_convert 'aaaref'%convert
!
! Definition of size of plotted image.
!
greg1\limits (0.5-aaaref_convert[1,1])*aaaref_convert[3,1]+aaaref_convert[2,1] -
   (0.5+aaaref_dim[1]-aaaref_convert[1,1])*aaaref_convert[3,1]+aaaref_convert[2,1] -
   (0.5-aaaref_convert[1,2])*aaaref_convert[3,2]+aaaref_convert[2,2] -
   (0.5+aaaref_dim[2]-aaaref_convert[1,2])*aaaref_convert[3,2]+aaaref_convert[2,2] 
!
if ((size[1].ne.0).or.(size[2].ne.0)) then
   if (size[1].eq.0) then
      greg1\limits = = (center[2]-size[2]/2) (center[2]+size[2]/2) seconds
   else if (size[2].eq.0) then
      greg1\limits (center[1]+size[1]/2) (center[1]-size[1]/2) = = seconds
   else
      greg1\limits (center[1]+size[1]/2) (center[1]-size[1]/2) (center[2]-size[2]/2) (center[2]+size[2]/2) seconds
   endif
endif
!
! Definition of red and blue-shifted channels
!
if (do_vsys) then
   define integer ivsys vsys_pens['aaaref_dim[3]',2]
   define integer black[2] blue[2] red[2]
   pen 10 /col 0 /dash 3
   pen 11 /col 1 /dash 3
   pen 13 /col 3 /dash 3
   pen 0
   let black 0 10
   if (aaaref_convert[3,3].gt.0) then
      let red  1 11
      let blue 3 13
   else
      let red  3 13
      let blue 1 11
   endif
   let ivsys aaaref_convert[1,3]+(vsys-aaaref_convert[2,3])/aaaref_convert[3,3]
   if (ivsys.le.1) then
      let vsys_pens red
      if (ivsys.eq.1) then
         let vsys_pens[1,1:2] black[1:2]
      endif
   else if (ivsys.ge.aaaref_dim[3]) then
      let vsys_pens blue
      if (ivsys.eq.aaaref_dim[3]) then
         let vsys_pens[aaaref_dim[3],1:2] black[1:2]
      endif
   else
      let vsys_pens[ivsys:'aaaref_dim[3]',1] red[1]
      let vsys_pens[ivsys:'aaaref_dim[3]',2] red[2]
      let vsys_pens[1:ivsys,1]               blue[1]
      let vsys_pens[1:ivsys,2]               blue[2]
      let vsys_pens[ivsys,1]                 black[1]
      let vsys_pens[ivsys,2]                 black[2]
   endif
   delete /var black blue red
endif
!
! Definition of first and last plotted planes.
!
if (first.eq.0) then
   let true_first 1
else
   let true_first first
endif
if (last.eq.0) then
   let true_last max(1,aaaref_dim[3])
else
   let true_last last
endif
!
if (true_first.gt.true_last) then
   let true_step -max(1,step)
else
   let true_step +max(1,step)
endif
!
! Draw wedge corresponding to background image when asked
!
if (do_wedge.and.do_header) then
   let name 'names[1]'
   let type 'types[1]'
   let spacing 'spacings[1]'
   @ p_load.greg aaa1
   @ p_scale.greg aaa1
   @ p_level.greg aaa1
   @ p_wedge.greg
endif
!
! Definition of number of additional boxes.
!
let nadd 0
if (do_weight) then
   let nadd nadd+1
endif
if (do_dirty) then
   let nadd nadd+1
endif
if (do_coverage) then
   let nadd nadd+1
endif
!
! Compute number of plotted planes and total number of box.
!
let nplanes abs((true_last-true_first)/true_step)+1
let nbox nplanes+nadd
!
! Definition of box characteristics.
!
let aspect abs((user_xmax-user_xmin)/(user_ymax-user_ymin))
if (aspect.lt.0.1.or.aspect.gt.10) then
   message w go "box aspect ratio > 10: ignored"
   let aspect 1.0
endif
let aspect_ratio yes ! Respect aspect ratio
let fixed_trc yes    ! Top right corner is fixed
let inter 0.0 0.0    ! No interspace between individual boxes (unit: % of box sizes)
@ plot_position      ! Definition of total available plotting place
@ find_nx_ny 'nbox'  ! Compute number of boxes in the x and y direction
@ find_size_margin 'nx_box' 'ny_box'   ! Compute individual box size and margin needed to keep aspect
if (expand.eq.0) then
   greg1\set expand min(6.0/(nx_box+ny_box),1.) ! Automatic definition character size
else
   greg1\set expand 'expand' ! User defined character size
endif
!
! Loop over images to be overplotted
!
define double pos_tole pos_diff[2]
for iimage 1 to nimages
   !
   ! Load image.
   !
   let name 'names[iimage]'
   let type 'types[iimage]'
   if (iimage.ne.nreference) then
      @ p_load.greg aaa'iimage'
      !
      ! Basic consistency checks:
      ! - projection center and projection kind must match. There is no
      !   way a different combination results to the same grid on sky.
      !   We could have some tolerance e.g. for "small" fields, but that's
      !   some work.
      ! - XY increments may not match, as PLOT and RGMAP know how to
      !   plot the RG data within the current box.
      !
      ! Position tolerance is set to 1/10th of the smallest pixel
      let pos_tole min(abs(aaa'iimage'%convert[3,aaa'iimage'%x_axis]),abs(aaa'nreference'%convert[3,aaa'nreference'%x_axis]))
      let pos_diff[1] aaa'iimage'%a0-aaa'nreference'%a0
      let pos_diff[2] aaa'iimage'%d0-aaa'nreference'%d0
      if any(pos_diff.gt.pos_tole) then
        message E OVER "Images #"'iimage'" and #"'nreference'" are misaligned (tolerance" -
                       'nint(pos_tole/sec*1e6)/1e6' "arcsec)"
        message E OVER "Use 'run reproject' to reproject the images on the same spatial grid"
        return base
      endif
      if aaa'iimage'%ptype.ne.aaa'nreference'%ptype then
        message E OVER "Images #"'iimage'" and #"'nreference'" do not use the same projection system"
        message E OVER "Use 'run reproject' to reproject the images on the same spatial grid"
        return base
      endif
   endif
   !
   ! Resample velocity axis when needed.
   !
   let resample (iimage.ne.nreference).and.(aaa'iimage'%dim[3].gt.1)
   let resample resample.and.(aaa'iimage'%convert[,3].ne.aaa'nreference'%convert[,3])
   let resample resample.and.(aaa'iimage'%dim[3].ne.aaa'nreference'%dim[3])
   if (resample) then
      vector\run map_inter gag_scratch:map_inter.init /nowin
      let name 'name'"-resampled"
      @ p_load.greg aaa'iimage'
   endif
   !
   ! Compute levels and scaling.
   !
   let spacing 'spacings[iimage]'
   @ p_scale.greg aaa'iimage'
   @ p_level.greg aaa'iimage'
   !
   ! Plot planes.
   !
   for iplane true_first to true_last by true_step
      !
      ! Define current box position and create corresponding directory
      ! or directly go to this directory
      !
      if (iimage.eq.1) then
         gtvl\change directory 'directory'
         @ find_window_position 'abs((iplane-true_first+true_step)/true_step)'
         gtvl\create directory p'iplane'
         gtvl\change directory p'iplane'
      else
         gtvl\change directory 'directory'<p'iplane'
      endif
      !
      ! Load plane 'iplane'.
      !
      if (aaa'iimage'%ndim.le.2) then
         greg2\rgdata aaa'iimage' /variable
      else if (aaa'iimage'%ndim.eq.3) then
         if (aaa'iimage'%dim[3].eq.1) then
            greg2\rgdata aaa'iimage'[1] /variable
         else
            greg2\rgdata aaa'iimage'[iplane] /variable
         endif
      else
         greg2\rgdata aaa'iimage'[iplane,1] /variable
      endif
      !
      ! Plot plane 'iplane'.
      !
      if (iimage.eq.1) then
         if (do_bit) then
            greg2\plot /scaling linear true_scale[1] true_scale[2]
         endif
         if (do_grey) then
            greg2\rgmap quiet /abs 1.0 /grey /only posi
         endif
         if (do_contour) then
            if (do_vsys) then
               greg2\rgmap quiet /abs 1.0 /pens 'vsys_pens[iplane,1]' 'vsys_pens[iplane,2]'
            else
               greg2\rgmap quiet /abs 1.0 /pens 'pens[1,1]' 'pens[2,1]'
            endif
         endif
         !
         ! Plot a cross at the phase center when asked.
         ! Plot it here, this way it will be under the contours of others images.
         !
         if (do_cross) then
            if (file("my_cross.map")) then
               @ my_cross.map
            else
               greg1\draw relo 0 cross*sec /user /clip
               greg1\draw line 0 -cross*sec /user /clip
               greg1\draw relo cross*sec 0 /user /clip
               greg1\draw line -cross*sec 0 /user /clip
            endif
         endif
         !
      else
!!$         pen 'pens[1,iimage]' /weight 5
!!$         pen 'pens[2,iimage]' /weight 5
         greg1\pencil 7 /weight 2
         greg2\rgmap quiet /abs 1.0 /pens 7
         greg2\rgmap quiet /abs 1.0 /pens 'pens[1,iimage]' 'pens[2,iimage]'
         greg1\pencil 0
      endif
   next
next
!
! Draw box, mark.
!
let mark 'mark' /lower
for iplane true_first to true_last by true_step
   !
   ! Go to directory.
   !
   gtvl\change directory 'directory'<p'iplane'
   !
   ! Plot the clean beam in the bottom,left corner when asked.
   !
   if (do_nice) then
      @ p_beam.greg 'aaaref'
   endif
   !
   ! Make a white mask in the top left corner when asked.
   !
   if (exist(do_mask)) then
      if (do_mask) then
         @ p_mask.greg 7 0.3 0.15
      endif
   endif
   !
   ! Print the channel or frequency or velocity when asked.
   !
   if (mark.ne."none") then
      @ p_mark.greg 'aaaref' 'iplane'
   endif
   !
   ! Plot box without labels.
   !
   @ p_box.greg no 'aaaref'
   !
next
!
! Plot x and y axis labels on the bottom, right corner.
! Try to be clever to avoid wrongly labelling the uv coverage!
!
let name 'names[nreference]'
!
gtvl\change directory 'directory'
!
! Try to put the legends in the middle, to avoid
! overlap with the labels...
@ p_legend.greg X 'aaaref'
@ p_legend.greg Y 'aaaref'
!  
if (do_coverage) then
   define integer nx_cover
   let nx_cover nbox-(ny_box-1)*nx_box
   if (nx_cover.ne.1) then
      @ window_xy 'nx_box' 'ny_box' 1 1
   else
      let nx_cover nx_box
      @ window_xy 'nx_box' 'ny_box' 1 2
   endif
else
   @ window_xy 'nx_box' 'ny_box' 1 1
endif
!
@ p_box.greg label 'aaaref'
!
! Plot weight image when asked.
!
if (do_weight.and.file("'name'.wei")) then
   gtvl\change directory 'directory'
   @ window_xy 'nx_box' 'ny_box' 'nplanes+1'
   gtvl\create directory weight
   gtvl\change directory weight
   define image wei 'name'".wei" read
   greg2\rgdata wei /variable
   greg2\extrema quiet /blanking wei%blank[1] wei%blank[2] /compute
   if (do_bit) then
      greg2\plot wei /scaling linear rgmin rgmax
   endif
   if (do_contour) then
      greg2\levels 3.33 6.66
      greg2\rgmap quiet /percent 10
      greg2\wedge /scaling linear rgmin rgmax /level
   else
      greg2\wedge /scaling linear rgmin rgmax
   endif
   @ p_box.greg no 'aaaref'
   greg1\draw text 0 -1.25 "Weight image" 5 /char 2
   delete /var wei
endif
!
! Plot dirty beam when asked.
!
if (do_dirty.and.file("'name'.beam")) then
   gtvl\change directory 'directory'
   @ window_xy 'nx_box' 'ny_box' 'nplanes+1'
   gtvl\create directory dirty
   gtvl\change directory dirty
   define image lob 'name'".beam" read
   greg2\levels -0.5 to -0.1 by 0.1 0.1 to 0.5 by 0.1
   greg2\rgdata lob /variable
   if (do_bit) then
      greg2\plot lob /scaling linear -0.5 1.0
   endif
   if (do_contour) then
      greg2\rgmap quiet
   endif
   @ p_box.greg no 'aaaref'
   greg1\draw text -0.2 0.2 "Dirty Beam" 7 /box 3
   delete /var lob
endif
!
! Plot uv coverage when asked.
!
if (do_coverage.and.file("'name'.uvt")) then
   !
   ! Check dates and transpose when needed.
   !
   define integer uvt__date tuv__date
   sic\compute uvt__date date 'name'.uvt
   define character ctest*40
   let ctest 'name'.tuv
   if (file(ctest)) then
      sic\compute tuv__date date 'name'.tuv
   else
      let tuv__date -1
   endif
   delete /var ctest
   if (tuv__date.le.uvt__date) then
      vector\transpose 'name'.uvt 'name'.tuv 21
   endif
   !
   ! Plot uv coverage.
   !
   gtvl\change directory 'directory'
   @ window_xy 'nx_box' 'ny_box' 'nx_cover' 1
   gtvl\create directory coverage
   gtvl\change directory coverage
   define uv uvt 'name'.tuv read
   define real max_p max_n umax vmax uvmax
   compu max_p max uvt[1]
   compu max_n min uvt[1]
   let umax max(-max_n,max_p)
   compu max_p max uvt[2]
   compu max_n min uvt[2]
   let vmax max(-max_n,max_p)
   let uvmax 1.05*max(umax,vmax)
   !
   greg1\limits uvmax -uvmax uvmax -uvmax 
   greg1\points uvt[1] uvt[2]
   greg1\limits -uvmax uvmax -uvmax uvmax
   greg1\points uvt[1] uvt[2]
   greg1\box p n
   greg1\axis yr /label o
   greg1\draw text -0.2 0.2 "uv Coverage" 7 /box 3
   delete /variable uvt uvt__date tuv__date
   !
endif
!
! Change to the last plane directory and reload the corresponding plane to
! allow the user to use facilities like poly and mean when they plot only
! one plane.
!
gtvl\change directory 'directory'
!@ plot_position
@ window_xy 'nx_box' 'ny_box' 'nplanes'
if (aaa1%ndim.le.2) then
   greg2\rgdata aaa1 /variable
else if (aaa1%ndim.eq.3) then
   if (aaa1%dim[3].eq.1) then
      greg2\rgdata aaa1[1] /variable
   else
      greg2\rgdata aaa1[true_last] /variable
   endif
else
   greg2\rgdata aaa1[true_last,1] /variable
endif
!
! Reset
!
!@ window_init
greg1\set expand 1.0
!
! Temporary to avoid problem with old routines
!
let aspect 0.0
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
begin data gag_scratch:map_inter.init
  !
  ! Parameter file for map_inter
  !
  task\character "Input File "            INPUT_MAP$ 'name'"."'type'
  task\character "Output File "          OUTPUT_MAP$ 'name'"-resampled."'type'
  task\integer "Number of output channels "      NX$ 'aaaref_dim[3]'
  task\real "New reference channel "      REFERENCE$ 'aaaref_convert[1,3]'
  task\real "New value at reference channel " VALUE$ 'aaaref_convert[2,3]'
  task\real "New increment per channel "  INCREMENT$ 'aaaref_convert[3,3]'
  task\go
  !
end data gag_scratch:map_inter.init
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
