!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubemain_aperture
  use cubetools_parameters
  use cubetools_structure
  use cube_types
  use cubesyntax_keyval_types
  use cubeadm_cubeid_types
  use cubeadm_cubeprod_types
  use cubetopology_cuberegion_types
  use cubetopology_spaelli_types
  use cubemain_messaging
  use cubemain_stack_spectra_tool
  !
  public :: aperture
  private
  !
  type :: aperture_comm_t
     type(option_t), pointer     :: comm
     type(cuberegion_comm_t)     :: region
     type(spaelli_comm_t)        :: ellipse
     type(stack_spectra_comm_t)  :: stack
     type(keyval_dble_comm_t)    :: background
     type(cubeid_arg_t), pointer :: cube
     type(cube_prod_t),  pointer :: spectrum
   contains
     procedure, public  :: register => cubemain_aperture_comm_register
     procedure, private :: parse    => cubemain_aperture_comm_parse
     procedure, private :: main     => cubemain_aperture_comm_main
  end type aperture_comm_t
  type(aperture_comm_t) :: aperture
  !
  type aperture_user_t
     type(cubeid_user_t)        :: cubeids
     type(cuberegion_user_t)    :: region
     type(spaelli_user_t)       :: ellipse
     type(stack_spectra_user_t) :: stack
     type(keyval_dble_user_t)   :: background
   contains
     procedure, private :: toprog => cubemain_aperture_user_toprog
  end type aperture_user_t
  !
  type aperture_prog_t
     type(cuberegion_prog_t)    :: region             ! Cube region of interest
     type(spaelli_prog_t)       :: ellipse            ! Aperture geometry and position
     type(stack_spectra_prog_t) :: stack              ! Stacking options
     real(kind=coor_k)          :: backdiamfact = 0d0 ! Background diameter factor
     type(cube_t), pointer      :: cube               ! Input cube
     type(cube_t), pointer      :: spectrum           ! Output spectrum
   contains
     procedure, private :: header => cubemain_aperture_prog_header
     procedure, private :: data   => cubemain_aperture_prog_data
     procedure, private :: loop   => cubemain_aperture_prog_loop
     procedure, private :: act    => cubemain_aperture_prog_act
  end type aperture_prog_t
  !
contains
  !
  subroutine cubemain_aperture_command(line,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: line
    logical,          intent(inout) :: error
    !
    type(aperture_user_t) :: user
    character(len=*), parameter :: rname='APERTURE>COMMAND'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call aperture%parse(line,user,error)
    if (error) return
    call aperture%main(user,error)
    if (error) continue
  end subroutine cubemain_aperture_command
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_aperture_comm_register(comm,error)
    use cubedag_allflags
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(aperture_comm_t), intent(inout) :: comm
    logical,                intent(inout) :: error
    !
    type(cubeid_arg_t) :: cubearg
    type(cube_prod_t) :: oucube
    character(len=*), parameter :: rname='APERTURE>COMM>REGISTER'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubetools_register_command(&
         'APERTURE','[cubeid]',&
         'Stack spectra within a given aperture',&
         'APERTURE stacks spectra inside a user-defined spatial aperture.'&
         //strg_bl//&
         'Behavior:'//strg_cr//&
         '- Default aperture geometry is beam-driven and centered on the&
         & projection center.'//strg_cr//&
         '- Spatial and spectral selection is controlled by /SIZE, /CENTER,&
         & and /RANGE.'//strg_cr//&
         '- Stacking mode and local background handling are controlled by&
         & /SUM, /MEAN, and /BACKGROUND.'//strg_bl//&
         'Examples:'//strg_cr//&
         'CUBE> APERTURE cube:co'//strg_cr//&
         'CUBE> APERTURE cube:co /DIAMETER 30 arcsec /MEAN'//strg_cr//&
         'CUBE> APERTURE cube:co /CENTER 0 0 relative /RANGE -5 5 km/s',&
         cubemain_aperture_command,&
         comm%comm,error)
    if (error) return
    call cubearg%register(&
         'CUBEID',&
         'Signal cube identifier',&
         'If omitted, use the last matching cube (cube flag) in the&
         & default index (DAG by default; see SET\INDEX).',&
         code_arg_optional,&
         [flag_cube],&
         code_read,&
         code_access_imaset,&
         comm%cube,&
         error)
    if (error) return
    !
    call comm%ellipse%register(&
         'DIAMETER',&
         'Define the aperture ellipse axis diameters and position angle',&
         'POSITION',&
         'Define the aperture position',&
         error)
    if (error) return
    call comm%stack%register(error)
    if (error) return
    call comm%background%register(&
         'BACKGROUND',&
         'Set annulus scale for local background subtraction',&
         'Set the multiplicative factor applied to aperture diameters when&
         & defining the background annulus. Use "*" to keep the default&
         & factor (2.0).',&
         2d0,&
         error)
    if (error) return
    call comm%region%register(error)
    if (error) return
    !
    ! Product
    call oucube%register(&
         'APERTURE',&
         'The aperture spectrum',&
         'Stacked output spectrum for the selected aperture.',&
         [flag_aperture,flag_spectrum],&
         comm%spectrum,&
         error,&
         access=code_access_imaset)
    if (error) return
  end subroutine cubemain_aperture_comm_register
  !
  subroutine cubemain_aperture_comm_parse(comm,line,user,error)
    !----------------------------------------------------------------------
    ! APERTURE [cubeid]
    !----------------------------------------------------------------------
    class(aperture_comm_t), intent(in)    :: comm
    character(len=*),       intent(in)    :: line
    type(aperture_user_t),  intent(out)   :: user
    logical,                intent(inout) :: error
    !
    character(len=*), parameter :: rname='APERTURE>COMM>PARSE'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_parse(line,comm%comm,user%cubeids,error)
    if (error) return
    call comm%region%parse(line,user%region,error)
    if (error) return
    call comm%ellipse%parse(line,user%ellipse,error)
    if (error) return
    call comm%stack%parse(line,user%stack,error)
    if (error) return
    call comm%background%parse(line,user%background,error)
    if (error) return
  end subroutine cubemain_aperture_comm_parse
  !
  subroutine cubemain_aperture_comm_main(comm,user,error)
    use cubeadm_timing
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(aperture_comm_t), intent(in)    :: comm
    type(aperture_user_t),  intent(in)    :: user
    logical,                intent(inout) :: error
    !
    type(aperture_prog_t) :: prog
    character(len=*), parameter :: rname='APERTURE>MAIN'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call user%toprog(comm,prog,error)
    if (error) return
    call prog%header(comm,error)
    if (error) return
    call cubeadm_timing_prepro2process()
    call prog%data(error)
    if (error) return
    call cubeadm_timing_process2postpro()
  end subroutine cubemain_aperture_comm_main
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_aperture_user_toprog(user,comm,prog,error)
    use cubeadm_get
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(aperture_user_t), intent(in)    :: user
    type(aperture_comm_t),  intent(in)    :: comm
    type(aperture_prog_t),  intent(inout) :: prog
    logical,                intent(inout) :: error
    !
    type(keyval_dble_prog_t) :: keyval
    character(len=*), parameter :: rname='APERTURE>USER>TOPROG'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_get_header(comm%cube,user%cubeids,prog%cube,error)
    if (error) return
    call user%region%toprog(prog%cube,prog%region,error)
    if (error) return
    call user%ellipse%toprog(prog%cube,prog%ellipse,error)
    if (error) return
    call user%stack%toprog(prog%cube,prog%stack,error)
    if (error) return
    call user%background%toprog(comm%background,prog%backdiamfact,error)
    if (error) return
    ! User feedback
    call prog%region%list(error)
    if (error) return
    call prog%ellipse%list(error)
    if (error) return
    call prog%stack%list(error)
    if (error) return
    if (user%background%do) then
       call keyval%list(comm%background,prog%backdiamfact,error)
       if (error) return
    endif
  end subroutine cubemain_aperture_user_toprog
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_aperture_prog_header(prog,comm,error)
    use cubetools_header_methods
    use cubetools_axis_types
    use cubetools_beam_types
    use cubetools_spapro_types
    use cubeadm_clone
    !----------------------------------------------------------------------
    ! The following code aproximates the header to describe a shape similar
    ! to the aperture. L axis is aligned with aperture major axis, m axis
    ! with the minor axis, projection angle is the aperture position
    ! angle. This is only an approximation as the projection effects are
    ! not taken into account.
    !----------------------------------------------------------------------
    class(aperture_prog_t), intent(inout) :: prog
    type(aperture_comm_t),  intent(in)    :: comm
    logical,                intent(inout) :: error
    !
    real(kind=coor_k) :: absolute(2)
    type(axis_t) :: axis
    type(beam_t) :: beam
    type(spapro_t) :: spapro
    integer(kind=ndim_k), parameter :: ix = 1
    integer(kind=ndim_k), parameter :: iy = 2
    character(len=*), parameter :: rname='APERTURE>PROG>HEADER'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_clone_header_with_region(comm%spectrum,  &
      prog%cube,prog%region,prog%spectrum,error)
    if (error) return
    call prog%stack%set_unit(prog%spectrum,error)
    if (error) return
    !
    ! l axis
    call cubetools_header_get_axis_head_l(prog%spectrum%head,axis,error)
    if (error) return
    axis%ref = 0.0
    axis%val = 0.0
    axis%inc = sign(max(prog%ellipse%diameter%major,abs(axis%inc)),axis%inc)
    axis%n = 1_pixe_k
    call cubetools_header_update_axset_l(axis,prog%spectrum%head,error)
    if (error) return
    !
    ! m axis
    call cubetools_header_get_axis_head_m(prog%spectrum%head,axis,error)
    if (error) return
    axis%ref = 0.0
    axis%val = 0.0
    axis%inc = sign(max(prog%ellipse%diameter%minor,abs(axis%inc)),axis%inc)
    axis%n = 1_pixe_k
    call cubetools_header_update_axset_m(axis,prog%spectrum%head,error)
    if (error) return
    !
    ! Projection
    call cubetools_header_get_spapro(prog%spectrum%head,spapro,error)
    if (error) return
    call prog%ellipse%center%absolute(absolute,error)
    if (error) return
    spapro%l0 = absolute(ix)
    spapro%m0 = absolute(iy)
    spapro%pa = prog%ellipse%diameter%pang
    call cubetools_header_put_spapro(spapro,prog%spectrum%head,error)
    if (error) return
    !
    ! Beam
    call cubetools_header_get_spabeam(prog%spectrum%head,beam,error)
    if (error) return
    ! VVV is this the correct choice for the output beam?
    if (beam%major*beam%minor.lt.prog%ellipse%diameter%major*prog%ellipse%diameter%minor) then
       beam%major = prog%ellipse%diameter%major
       beam%minor = prog%ellipse%diameter%minor
       beam%pang  = prog%ellipse%diameter%pang
       call cubetools_header_update_spabeam(beam,prog%spectrum%head,error)
       if (error) return
    endif
  end subroutine cubemain_aperture_prog_header
  !
  subroutine cubemain_aperture_prog_data(prog,error)
    use cubeadm_opened
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(aperture_prog_t), intent(inout) :: prog
    logical,                intent(inout) :: error
    !
    type(cubeadm_iterator_t) :: iter
    character(len=*), parameter :: rname='APERTURE>PROG>DATA'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_datainit_all(iter,prog%region,error)
    if (error) return
    !$OMP PARALLEL DEFAULT(none) SHARED(prog,error) FIRSTPRIVATE(iter)
    !$OMP SINGLE
    do while (cubeadm_dataiterate_all(iter,error))
       if (error) exit
       !$OMP TASK SHARED(prog,error) FIRSTPRIVATE(iter)
       if (.not.error) &
         call prog%loop(iter,error)
       !$OMP END TASK
    enddo
    !$OMP END SINGLE
    !$OMP END PARALLEL
  end subroutine cubemain_aperture_prog_data
  !   
  subroutine cubemain_aperture_prog_loop(prog,iter,error)
    use cubeadm_taskloop
    use cubeadm_image_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(aperture_prog_t),   intent(inout) :: prog
    type(cubeadm_iterator_t), intent(inout) :: iter
    logical,                  intent(inout) :: error
    !
    type(image_t) :: image,mask,weight,spectrum
    character(len=*), parameter :: rname='APERTURE>PROG>LOOP'
    !
    call image%associate('image',prog%cube,iter,error)
    if (error) return
    call mask%allocate('mask',prog%cube,error) !***JP: Is this correct with respect to the region?
    if (error) return
    call mask%associate_xy(error)
    if (error) return
    if (prog%backdiamfact.le.0.0) then
       call ellipse2mask1(prog%ellipse,mask,error)
       if (error) return
    else
       call ellipse2mask2(prog%ellipse,prog%backdiamfact,mask,error)
       if (error) return
    endif
    call weight%allocate('weight',prog%cube,error) !***JP: Is this correct with respect to the region?
    if (error) return
    call weight%set(1.0,error) ! => This means uniform weighting
    if (error) return
    call spectrum%allocate('spectrum',prog%spectrum,iter,error)
    if (error) return
    !
    do while (iter%iterate_entry(error))
       call prog%act(iter%ie,image,mask,weight,spectrum,error)
       if (error) return
    enddo ! ie
    !
  contains
    !
    subroutine ellipse2mask1(ellipse,mask,error)
      use cubetools_nan
      use cubetopology_spatial_coordinates
      !--------------------------------------------------------------------
      ! Compute a mask from an ellipse definition. If a pixel is outside
      ! the aperture but it is less than half a pixel from the ellipse
      ! center then it includes it in the mask.
      !
      !***JP: This codes does not takes into account projection effects.
      !--------------------------------------------------------------------
      type(spaelli_prog_t), intent(in)    :: ellipse
      type(image_t),        intent(in)    :: mask
      logical,              intent(inout) :: error
      !
      logical :: inside
      integer(kind=pixe_k) :: ix,iy
      real(kind=coor_k) :: centeroffset(2)
      real(kind=coor_k) :: rmajor,rminor
      real(kind=coor_k) :: angle,cosang,sinang
      real(kind=coor_k) :: xpix,xcoord,xcos,xsin
      real(kind=coor_k) :: ypix,ycoord,ycos,ysin
      !
      xpix = 0.5*abs(mask%x%inc) ! Half pixel size along x
      ypix = 0.5*abs(mask%y%inc) ! Half pixel size along y
      rmajor = 0.5*ellipse%diameter%major ! Major radius
      rminor = 0.5*ellipse%diameter%minor ! Minor radius
      call cubetopology_spatial_pang_to_fortran(prog%cube,ellipse%diameter%pang,angle,error)
      if (error) return
      cosang = cos(angle)
      sinang = sin(angle)
      call ellipse%center%offset(centeroffset,error)
      if (error) return
      !
      do iy=1,mask%ny
         ycoord = mask%y%coord(iy)-centeroffset(2)
         ycos = ycoord*cosang
         ysin = ycoord*sinang
         do ix=1,mask%nx
            xcoord = mask%x%coord(ix)-centeroffset(1)
            xcos = xcoord*cosang
            xsin = xcoord*sinang
            inside = ( ((xcos+ysin)/rmajor)**2 + ((xsin-ycos)/rminor)**2 ).le.1d0
            inside = inside.or.((abs(xcoord).le.xpix).and.abs(ycoord).le.ypix)
            if (inside) then
               mask%val(ix,iy) = 1.0
            else
               mask%val(ix,iy) = gr4nan
            endif
         enddo ! iy
      enddo ! ix
    end subroutine ellipse2mask1
    !
    subroutine ellipse2mask2(ellipse,bgfact,mask,error)
      use cubetools_nan
      use cubetopology_spatial_coordinates
      !--------------------------------------------------------------------
      ! Compute a mask from an ellipse definition. If a pixel is outside
      ! the aperture but it is less than half a pixel from the ellipse
      ! center then it includes it in the mask.
      !
      !***JP: This codes does not takes into account projection effects.
      !--------------------------------------------------------------------
      type(spaelli_prog_t), intent(in)    :: ellipse
      real(kind=coor_k),    intent(in)    :: bgfact
      type(image_t),        intent(in)    :: mask
      logical,              intent(inout) :: error
      !
      logical :: insidesig,insidebg
      integer(kind=pixe_k) :: ix,iy
      real(kind=coor_k) :: centeroffset(2)
      real(kind=coor_k) :: rmajorsig,rminorsig
      real(kind=coor_k) :: rmajorbg, rminorbg
      real(kind=coor_k) :: angle,cosang,sinang
      real(kind=coor_k) :: xpix,xcoord,xcos,xsin
      real(kind=coor_k) :: ypix,ycoord,ycos,ysin
      !
      xpix = 0.5*abs(mask%x%inc)             ! Half pixel size along x
      ypix = 0.5*abs(mask%y%inc)             ! Half pixel size along y
      rmajorsig = 0.5*ellipse%diameter%major ! Major radius of signal region
      rminorsig = 0.5*ellipse%diameter%minor ! Minor radius of signal region
      rmajorbg = rmajorsig*bgfact            ! Major radius of background region
      rminorbg = rminorsig*bgfact            ! Minor radius of background region
      call cubetopology_spatial_pang_to_fortran(prog%cube,ellipse%diameter%pang,angle,error)
      if (error) return
      cosang = cos(angle)
      sinang = sin(angle)
      call ellipse%center%offset(centeroffset,error)
      if (error) return
      !
      do iy=1,mask%ny
         ycoord = mask%y%coord(iy)-centeroffset(2)
         ycos = ycoord*cosang
         ysin = ycoord*sinang
         do ix=1,mask%nx
            xcoord = mask%x%coord(ix)-centeroffset(1)
            xcos = xcoord*cosang
            xsin = xcoord*sinang
            insidebg = ( ((xcos+ysin)/rmajorbg)**2 + ((xsin-ycos)/rminorbg)**2 ).le.1d0
            insidebg = insidebg.or.((abs(xcoord).le.xpix).and.abs(ycoord).le.ypix)
            if (insidebg) then
               insidesig = ( ((xcos+ysin)/rmajorsig)**2 + ((xsin-ycos)/rminorsig)**2 ).le.1d0
               insidesig = insidesig.or.((abs(xcoord).le.xpix).and.abs(ycoord).le.ypix)
               if (insidesig) then               
                  mask%val(ix,iy) = signal
               else
                  mask%val(ix,iy) = background
               endif
            else
               mask%val(ix,iy) = gr4nan
            endif
         enddo ! iy
      enddo ! ix
    end subroutine ellipse2mask2
  end subroutine cubemain_aperture_prog_loop
  !
  subroutine cubemain_aperture_prog_act(prog,ie,image,mask,weight,spectrum,error)
    use cubeadm_image_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(aperture_prog_t), intent(inout) :: prog
    integer(kind=entr_k),   intent(in)    :: ie
    type(image_t),          intent(inout) :: image
    type(image_t),          intent(inout) :: mask
    type(image_t),          intent(inout) :: weight
    type(image_t),          intent(inout) :: spectrum
    logical,                intent(inout) :: error
    !
    character(len=*), parameter :: rname='APERTURE>PROG>ACT'
    !
    call image%get(ie,error)
    if (error) return
    if (prog%backdiamfact.le.0.0) then
       call prog%stack%with_mask(image,weight,mask,spectrum,error)
       if (error) return
    else
       call prog%stack%backsubtract(image,weight,mask,spectrum,error)
       if (error) return
    endif
    call spectrum%put(ie,error)
    if (error) return
  end subroutine cubemain_aperture_prog_act  
end module cubemain_aperture
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
