!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubemain_aperture
  use cubetools_parameters
  use cubetools_structure
  use cube_types
  use cubeadm_cubeid_types
  use cubeadm_cubeprod_types
  use cubetopology_cuberegion_types
  use cubetopology_spapos_types
  use cubetopology_spaelli_types
  use cubemain_messaging
  !
  public :: aperture
  private
  !
  type :: aperture_comm_t
     type(option_t), pointer :: comm
     type(cuberegion_comm_t) :: region
     type(spaelli_comm_t)    :: ellipse
     type(option_t), pointer :: sum
     type(option_t), pointer :: mean
     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
     logical                 :: domean = .false.
     logical                 :: dosum  = .false.
   contains
     procedure, private :: toprog => cubemain_aperture_user_toprog
  end type aperture_user_t
  !
  type aperture_prog_t
     type(cuberegion_prog_t) :: region
     type(spapos_prog_t)     :: center           ! Aperture center
     type(spaelli_prog_t)    :: ellipse          ! Aperture geometry
     logical                 :: domean = .false. ! Mean or Sum?
     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',&
         'By default the aperture has the size and shape of the beam&
        & and is centered at the projection center. This can be&
        & changed by using options /CENTER and /ELLIPSE. The aperture&
        & can be compute either as a mean (/MEAN) or a sum (/SUM).&
        & When not specified, the program will choose the operation based&
        & on the input cube unit. If it is in K (Tmb), the aperture&
        & will be a mean in K (Tmb) and if it is in Jy/beam the&
        & aperture will be a sum in Jy.',&
         cubemain_aperture_command,&
         comm%comm,error)
    if (error) return
    call cubearg%register(&
         'CUBE',&
         'Signal cube', &
         strg_id,&
         code_arg_optional, &
         [flag_cube],&
         code_read,&
         code_access_imaset,&
         comm%cube,&
         error)
    if (error) return
    !
    call comm%region%register(error)
    if (error) return
!!$    call comm%center%register(&
!!$         'CENTER',&
!!$         'Define aperture center',&
!!$         error)
!!$    if (error) return
    call comm%ellipse%register(&
         'ELLIPSE',&
         'Define aperture ellipse axes and position angle',&
         error)
    if (error) return
    !
    call cubetools_register_option(&
         'SUM','',&
         'A sum over the aperture will be computed',&
         'Output unit is Jy',&
         comm%sum,error)
    if (error) return
    call cubetools_register_option(&
         'MEAN','',&
         'A mean over the aperture will be computed',&
         'Output unit is K(Tmb)',&
         comm%mean,error)
    if (error) return
    !
    ! Product
    call oucube%register(&
         'APERTURE',&
         'The aperture spectrum',&
         strg_id,&
         [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)
    use gkernel_interfaces
    !----------------------------------------------------------------------
    ! APERTURE 
    !----------------------------------------------------------------------
    class(aperture_comm_t), intent(in)    :: comm
    character(len=*),       intent(in)    :: line
    type(aperture_user_t),  intent(out)   :: user
    logical,                intent(inout) :: error
    !
    logical :: domean,dosum
    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%mean%present(line,domean,error)
    if (error) return
    call comm%sum%present(line,dosum,error)
    if (error) return
    !
    if (domean.and.dosum)then
       call cubemain_message(seve%e,rname,'Options /MEAN and /SUM are mutually exclusive')
       error = .true.
       return
    else if (dosum) then
       user%domean = .false.
       user%dosum  = .true.
    else if (domean) then
       user%domean = .true.
       user%dosum  = .false.
    else
       user%domean = .false.
       user%dosum  = .false.
    endif
  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
    use cubemain_stack_spectral
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    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
    !
    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%region%center%toprog(prog%cube,prog%center,error)
    if (error) return
    call user%ellipse%toprog(prog%cube,prog%ellipse,error)
    if (error) return
    !
    if (.not.user%domean.and..not.user%dosum) then
       call cubemain_stack_spectral_domean(prog%cube,prog%domean,error)
       if (error) return
    else if (user%domean.and.user%dosum) then
       call cubemain_message(seve%e,rname,'User%domean and user%dosum are both true')
       error = .true.
       return
    else
       prog%domean = user%domean
    endif
    ! User feedback
    call prog%region%list(error)
    call prog%center%list(error)
    call prog%ellipse%list(error)
  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
    !
    type(spapro_t) :: spapro
    type(axis_t) :: axis
    type(beam_t) :: beam
    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
!!$***JP
!!$    call prog%header_setscale(error)
!!$    if (error) return
!!$***JP
    !
    ! 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%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%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
    spapro%l0 = prog%center%abso(1)
    spapro%m0 = prog%center%abso(2)
    spapro%pa = prog%ellipse%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%major*prog%ellipse%minor) then
       beam%major = prog%ellipse%major
       beam%minor = prog%ellipse%minor
       beam%pang  = prog%ellipse%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
    call ellipse2mask(prog%center,prog%ellipse,mask,error)
    if (error) return
    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 ellipse2mask(center,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 center of
      ! the ellipse, then it includes it in the mask.
      !
      !***JP: This codes does not takes into account projection effects.
      !--------------------------------------------------------------------
      type(spapos_prog_t),  intent(in)    :: center
      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) :: 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%major ! Major radius
      rminor = 0.5*ellipse%minor ! Minor radius
      call cubetopology_spatial_pang_to_fortran(prog%cube,ellipse%pang,angle,error)
      if (error) return
      cosang = cos(angle)
      sinang = sin(angle)
      !
      do iy=1,mask%ny
         ycoord = mask%y%coord(iy)-center%rela(2)
         ycos = ycoord*cosang
         ysin = ycoord*sinang
         do ix=1,mask%nx
            xcoord = mask%x%coord(ix)-center%rela(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 ellipse2mask
  end subroutine cubemain_aperture_prog_loop
  !
  subroutine cubemain_aperture_prog_act(prog,ie,image,mask,weight,spectrum,error)
    use cubeadm_image_types
    use cubemain_stack_spectral
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    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
    !
    type(stack_spectral_prog_t) :: stack
    character(len=*), parameter :: rname='APERTURE>PROG>ACT'
    !
    stack%factor = 1.0
    stack%contaminate = .false.
    call image%get(ie,error)
    if (error) return
    call stack%act_mask(image,weight,mask,spectrum,error)
    if (error) return
    call spectrum%put(ie,error)
    if (error) return
  end subroutine cubemain_aperture_prog_act  
end module cubemain_aperture
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
