!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubecompute_cumulant
  use cube_types
  use cubetools_structure
  use cubeadm_cubeid_types
  use cubeadm_cubeprod_types
  use cubetopology_cuberegion_types
  use cubecompute_messaging
  use cubecompute_operdir_types
  !
  public :: cumulant
  private
  !
  type :: cumulant_comm_t
     type(option_t), pointer :: comm
     type(cuberegion_comm_t) :: region
     type(operdir_comm_t)    :: direction
     type(cubeid_arg_t), pointer :: cube
     type(cube_prod_t),  pointer :: cumulant ! Approx cube prod registered at start-up
   contains
     procedure, public  :: register => cubecompute_cumulant_comm_register
     procedure, private :: parse    => cubecompute_cumulant_comm_parse
     procedure, private :: main     => cubecompute_cumulant_comm_main
  end type cumulant_comm_t
  type(cumulant_comm_t) :: cumulant  
  !
  type cumulant_user_t
     type(cubeid_user_t)     :: cubeids
     type(cuberegion_user_t) :: region
     type(operdir_user_t)    :: direction
   contains
     procedure, private :: toprog => cubecompute_cumulant_user_toprog
  end type cumulant_user_t
  !
  type cumulant_prog_t
     !***JP: Why cubeprod needs to be global?
     type(cube_prod_t)       :: cubeprod ! Exact cube product evaluated at run time
     type(cuberegion_prog_t) :: region
     type(operdir_prog_t)    :: direction
     type(cube_t), pointer   :: cube
     type(cube_t), pointer   :: cumulant
     procedure(cubecompute_cumulant_prog_act_from_blc), pointer :: act => null()
   contains
     procedure, private :: header => cubecompute_cumulant_prog_header
     procedure, private :: data   => cubecompute_cumulant_prog_data
     procedure, private :: loop   => cubecompute_cumulant_prog_loop
  end type cumulant_prog_t
  !
contains
  !
  subroutine cubecompute_cumulant_command(line,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: line
    logical,          intent(inout) :: error
    !
    type(cumulant_user_t) :: user
    character(len=*), parameter :: rname='CUMULANT>COMMAND'
    !
    call cubecompute_message(computeseve%trace,rname,'Welcome')
    !
    call cumulant%parse(line,user,error)
    if (error) return
    call cumulant%main(user,error)
    if (error) continue
  end subroutine cubecompute_cumulant_command
  !
  !----------------------------------------------------------------------
  !
  subroutine cubecompute_cumulant_comm_register(comm,error)
    use cubedag_allflags
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(cumulant_comm_t), intent(inout) :: comm
    logical,                intent(inout) :: error
    !
    type(cubeid_arg_t) :: cube
    type(cube_prod_t) :: cumulant
    character(len=*), parameter :: rname='CUMULANT>COMM>REGISTER'
    !
    call cubecompute_message(computeseve%trace,rname,'Welcome')
    !
    ! Syntax
    call cubetools_register_command(&
         'CUMULANT','[cubeid]',&
         'Compute cumulative sums in each image plane of a real cube',&
         'Compute 2D cumulative sums within each selected image plane of a&
         & real cube. The output cube matches the selected region of the&
         & input cube. Each output pixel stores the cumulative sum from the&
         & chosen corner to that pixel.'//strg_bl//&
         'Behavior:'//strg_cr//&
         '- /DIRECT accumulates from the bottom-left corner. If neither&
         & /DIRECT nor /INVERSE is given, the command defaults to /DIRECT.'&
         //strg_cr//&
         '- /INVERSE accumulates from the top-right corner.'//strg_cr//&
         '- In inverse mode, zero cumulative values are converted to NaN by&
         & the current implementation.'//strg_bl//&
         'Examples:'//strg_cr//&
         '- CUBE> CUMULANT cube /DIRECT.'//strg_cr//&
         '- CUBE> CUMULANT cube /INVERSE /RANGE -5km/s 5km/s.',&
         cubecompute_cumulant_command,&
         comm%comm,&
         error)
    if (error) return
    call cube%register(&
         'INPUT',&
         'Signal cube',&
         strg_emp,&
         code_arg_optional,&
         [flag_any],&
         code_read,&
         code_access_imaset,&
         comm%cube,&
         error)
    if (error) return
    call comm%direction%register(&
         'Cumulate from bottom left  corner',&
         'Cumulate from    top right corner',&
         error)
    if (error) return
    call comm%region%register(error)
    if (error) return
    !
    ! Products
    call cumulant%register(&
         'CUMULANT',&
         'CUMULANT cube',&
         strg_emp,&
         [flag_any,flag_cumulant],&! flag_any resolved at run time
         comm%cumulant,&
         error)
    if (error)  return
  end subroutine cubecompute_cumulant_comm_register
  !
  subroutine cubecompute_cumulant_comm_parse(comm,line,user,error)
    !----------------------------------------------------------------------
    ! CUMULANT cubname [ /DIRECT | /INVERSE ]
    !----------------------------------------------------------------------
    class(cumulant_comm_t), intent(in)    :: comm
    character(len=*),       intent(in)    :: line
    type(cumulant_user_t),  intent(out)   :: user
    logical,                intent(inout) :: error
    !
    character(len=*), parameter :: rname='CUMULANT>COMM>PARSE'
    !
    call cubecompute_message(computeseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_parse(line,comm%comm,user%cubeids,error)
    if (error) return
    call comm%direction%parse(line,user%direction,error)
    if (error) return
    call comm%region%parse(line,user%region,error)
    if (error) return
  end subroutine cubecompute_cumulant_comm_parse
  !
  subroutine cubecompute_cumulant_comm_main(comm,user,error)
    use cubeadm_timing
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(cumulant_comm_t), intent(in)    :: comm
    type(cumulant_user_t),  intent(inout) :: user
    logical,                intent(inout) :: error
    !
    type(cumulant_prog_t) :: prog
    character(len=*), parameter :: rname='CUMULANT>MAIN'
    !
    call cubecompute_message(computeseve%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 cubecompute_cumulant_comm_main
  !
  !----------------------------------------------------------------------
  !
  subroutine cubecompute_cumulant_user_toprog(user,comm,prog,error)
    use cubeadm_get
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(cumulant_user_t), intent(in)    :: user
    type(cumulant_comm_t),  intent(in)    :: comm
    type(cumulant_prog_t),  intent(out)   :: prog
    logical,                intent(inout) :: error
    !
    character(len=*), parameter :: rname='CUMULANT>USER>TOPROG'
    !
    call cubecompute_message(computeseve%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%direction%toprog(comm%direction,prog%direction,error)
    if (error) return
    select case (prog%direction%code)
    case (code_operdir_direct,code_operdir_default)
       prog%direction%code = code_operdir_direct
       prog%act => cubecompute_cumulant_prog_act_from_blc
    case (code_operdir_inverse)
       prog%act => cubecompute_cumulant_prog_act_from_trc
    case default
       call cubecompute_message(seve%e,rname,'Unknown operation direction')
       error = .true.
       return
    end select
    ! User feedback about the interpretation of his command line
    call prog%direction%list(error)
    if (error) return
    call prog%region%list(error)
    if (error) return
  end subroutine cubecompute_cumulant_user_toprog
  !
  !----------------------------------------------------------------------
  !
  subroutine cubecompute_cumulant_prog_header(prog,comm,error)
    use cubedag_allflags
    use cubeadm_clone
    use cubetools_header_methods
    !----------------------------------------------------------------------
    !***JP: Maybe this one could be factorized in type-operdir.f90???
    ! Create cumulant cube with proper flags
    !----------------------------------------------------------------------
    class(cumulant_prog_t), intent(inout) :: prog
    type(cumulant_comm_t),  intent(in)    :: comm
    logical,                intent(inout) :: error
    !
    !***JP: Why cubeprod needs to be global?
    !type(cube_prod_t) :: cubeprod ! Exact cube product evaluated at run time
    character(len=*), parameter :: rname='CUMULANT>PROG>HEADER'
    !
    call cubecompute_message(computeseve%trace,rname,'Welcome')
    !
    call comm%cumulant%copy(prog%cubeprod,error)
    if (error) return
    if (prog%direction%code.eq.code_operdir_direct) then
      call prog%cubeprod%flag_to_flag(flag_any,flag_direct,error)
      if (error) return
    else
      call prog%cubeprod%flag_to_flag(flag_any,flag_inverse,error)
      if (error) return
    endif
    call cubeadm_clone_header_with_region(prog%cubeprod,&
      prog%cube,prog%region,prog%cumulant,error)
    if (error) return
  end subroutine cubecompute_cumulant_prog_header
  !
  subroutine cubecompute_cumulant_prog_data(prog,error)
    use cubeadm_opened
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(cumulant_prog_t), intent(inout) :: prog
    logical,                intent(inout) :: error
    !
    type(cubeadm_iterator_t) :: iter
    character(len=*), parameter :: rname='CUMULANT>PROG>DATA'
    !
    call cubecompute_message(computeseve%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 ! iter
    !$OMP END SINGLE
    !$OMP END PARALLEL
  end subroutine cubecompute_cumulant_prog_data
  !   
  subroutine cubecompute_cumulant_prog_loop(prog,iter,error)
    use cubeadm_taskloop
    use cubeadm_image_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(cumulant_prog_t),   intent(inout) :: prog
    type(cubeadm_iterator_t), intent(inout) :: iter
    logical,                  intent(inout) :: error
    !
    type(image_t) :: image
    type(image_t) :: cumul
    character(len=*), parameter :: rname='CUMULANT>PROG>LOOP'
    !
    call image%associate('image',prog%cube,iter,error)
    if (error) return
    call cumul%allocate('cumul',prog%cumulant,iter,error)
    if (error) return
    !
    do while (iter%iterate_entry(error))
      call prog%act(iter%ie,image,cumul,error)
      if (error) return
    enddo ! ie
  end subroutine cubecompute_cumulant_prog_loop
  !
  subroutine cubecompute_cumulant_prog_act_from_blc(prog,ie,image,cumul,error)
    use cubetools_nan
    use cubetools_parameters
    use cubeadm_image_types
    !----------------------------------------------------------------------
    ! Start computation from bottom left corner
    !----------------------------------------------------------------------
    class(cumulant_prog_t), intent(inout) :: prog
    integer(kind=entr_k),   intent(in)    :: ie
    type(image_t),          intent(inout) :: image
    type(image_t),          intent(inout) :: cumul
    logical,                intent(inout) :: error
    !
    integer(kind=pixe_k) :: ix,iy
    real(kind=sign_k) :: value
    character(len=*), parameter :: rname='CUMULANT>PROG>ACT>FROM>BLC'
    !
    call image%get(ie,error)
    if (error) return
    call cumul%set(0.0,error)
    if (error) return
    ! Bottom left corner
    if (ieee_is_nan(image%val(1,1))) then
       cumul%val(1,1) = 0.0
    else
       cumul%val(1,1) = image%val(1,1)
    endif
    ! First row
    do ix=2,image%nx
       if (ieee_is_nan(image%val(ix,1))) then
          value = 0.0
       else
          value = image%val(ix,1)
       endif
       cumul%val(ix,1) = cumul%val(ix-1,1)+value
    enddo ! ix
    ! Other raws
    do iy=2,image%ny
       ! Cumulate along x axis
       if (ieee_is_nan(image%val(1,iy))) then
          cumul%val(1,iy) = 0.0
       else
          cumul%val(1,iy) = image%val(1,iy)
       endif
       do ix=2,image%nx
          if (ieee_is_nan(image%val(ix,iy))) then
             value = 0.0
          else
             value = image%val(ix,iy)
          endif
          cumul%val(ix,iy) = cumul%val(ix-1,iy)+value
       enddo ! ix
       ! Now cumulate current and previous raw
       do ix=1,image%nx
          cumul%val(ix,iy) = cumul%val(ix,iy)+cumul%val(ix,iy-1)
       enddo ! ix
    enddo ! iy
    do iy=1,image%ny
       do ix=1,image%nx
          if (ieee_is_nan(image%val(ix,iy))) cumul%val(ix,iy) = gr4nan
       enddo !ix
    enddo !iy
    call cumul%put(ie,error)
    if (error) return
  end subroutine cubecompute_cumulant_prog_act_from_blc
  !
  subroutine cubecompute_cumulant_prog_act_from_trc(prog,ie,image,cumul,error)
    use cubetools_nan
    use cubetools_parameters
    use cubeadm_image_types
    !----------------------------------------------------------------------
    ! Start computation from top right corner
    !----------------------------------------------------------------------
    class(cumulant_prog_t), intent(inout) :: prog
    integer(kind=entr_k),   intent(in)    :: ie
    type(image_t),          intent(inout) :: image
    type(image_t),          intent(inout) :: cumul
    logical,                intent(inout) :: error
    !
    integer(kind=pixe_k) :: ix,nx
    integer(kind=pixe_k) :: iy,ny
    real(kind=sign_k) :: value
    character(len=*), parameter :: rname='CUMULANT>PROG>ACT>FROM>TRC'
    !
    call image%get(ie,error)
    if (error) return
    call cumul%set(0.0,error)
    if (error) return
    ! Top right corner
    nx = image%nx
    ny = image%ny
    if (ieee_is_nan(image%val(nx,ny))) then
       cumul%val(nx,ny) = 0.0
    else
       cumul%val(nx,ny) = image%val(nx,ny)
    endif
    ! Last raw
    do ix=image%nx-1,1,-1
       if (ieee_is_nan(image%val(ix,ny))) then
          value = 0.0
       else
          value = image%val(ix,ny)
       endif
       cumul%val(ix,ny) = cumul%val(ix+1,ny)+value
    enddo ! ix
    ! Other raws
    do iy=image%ny-1,1,-1
       ! Cumulate along x axis
       if (ieee_is_nan(image%val(nx,iy))) then
          cumul%val(nx,iy) = 0.0
       else
          cumul%val(nx,iy) = image%val(nx,iy)
       endif
       do ix=image%nx-1,1,-1
          if (ieee_is_nan(image%val(ix,iy))) then
             value = 0.0
          else
             value = image%val(ix,iy)
          endif
          cumul%val(ix,iy) = cumul%val(ix+1,iy)+value
       enddo ! ix
       ! Now cumulate current and previous raw
       do ix=1,image%nx
          cumul%val(ix,iy) = cumul%val(ix,iy)+cumul%val(ix,iy+1)
       enddo ! ix
    enddo ! iy
    do iy=1,image%ny
       do ix=1,image%nx
          !if (ieee_is_nan(image%val(ix,iy))) cumul%val(ix,iy) = gr4nan
          if (cumul%val(ix,iy).eq.0) cumul%val(ix,iy) = gr4nan
       enddo !ix
    enddo !iy
    call cumul%put(ie,error)
    if (error) return
  end subroutine cubecompute_cumulant_prog_act_from_trc
end module cubecompute_cumulant
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
