!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubestatistics_percentile
  use cube_types
  use cubetools_parameters
  use cubetools_structure
  use cubesyntax_keyval_types
  use cubeadm_cubeid_types
  use cubeadm_cubeprod_types
  use cubetopology_cuberegion_types
  use cubestatistics_messaging
  !
  public :: percentile
  private
  !
  type :: percentile_comm_t
     type(option_t), pointer :: comm
     type(cuberegion_comm_t) :: region
     type(keyvalunit_real_comm_t) :: percentage
     type(cubeid_arg_t), pointer :: cube
     type(cube_prod_t),  pointer :: qlow
     type(cube_prod_t),  pointer :: qhigh
   contains
     procedure, public  :: register => cubestatistics_percentile_comm_register
     procedure, private :: parse    => cubestatistics_percentile_comm_parse
     procedure, private :: main     => cubestatistics_percentile_comm_main
  end type percentile_comm_t
  type(percentile_comm_t) :: percentile  
  !
  type percentile_user_t
     type(cubeid_user_t)     :: cubeids
     type(cuberegion_user_t) :: region
     type(keyvalunit_real_user_t) :: percentage
   contains
     procedure, private :: toprog => cubestatistics_percentile_user_toprog
  end type percentile_user_t
  !
  type percentile_prog_t
     type(cuberegion_prog_t) :: region
     real(kind=sign_k)       :: plow  = 10 ! [%] Percentage of low  percentile
     real(kind=sign_k)       :: phigh = 90 ! [%] Percentage of high percentile (100-plow)
     type(cube_t), pointer   :: cube
     type(cube_t), pointer   :: qlow
     type(cube_t), pointer   :: qhigh
   contains
     procedure, private :: header => cubestatistics_percentile_prog_header
     procedure, private :: data   => cubestatistics_percentile_prog_data
     procedure, private :: loop   => cubestatistics_percentile_prog_loop
     procedure, private :: act    => cubestatistics_percentile_prog_act
  end type percentile_prog_t
  !
contains
  !
  subroutine cubestatistics_percentile_command(line,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: line
    logical,          intent(inout) :: error
    !
    type(percentile_user_t) :: user
    character(len=*), parameter :: rname='PERCENTILE>COMMAND'
    !
    call cubestatistics_message(statisticsseve%trace,rname,'Welcome')
    !
    call percentile%parse(line,user,error)
    if (error) return
    call percentile%main(user,error)
    if (error) continue
  end subroutine cubestatistics_percentile_command
  !
  !----------------------------------------------------------------------
  !
  subroutine cubestatistics_percentile_comm_register(comm,error)
    use cubetools_unit
    use cubedag_allflags
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(percentile_comm_t), intent(inout) :: comm
    logical,                  intent(inout) :: error
    !
    type(cubeid_arg_t) :: incube
    type(cube_prod_t) :: oucube
    type(percentile_prog_t) :: prog
    character(len=*), parameter :: rname='PERCENTILE>COMM>REGISTER'
    !
    call cubestatistics_message(statisticsseve%trace,rname,'Welcome')
    !
    ! Syntax
    call cubetools_register_command(&
         'PERCENTILE','[cubeid]',&
         'Compute the percentile spectra over the selected spectral channels',&
         'Both the P and 100-P percentile spectra will be computed.&
         & The /SIZE and /CENTER keys are accepted for interface consistency&
         & but ignored during execution.'//strg_bl//&
         'Input/output cubes must be/will be real.',&
         cubestatistics_percentile_command,&
         comm%comm,&
         error)
    if (error) return
    call incube%register(&
         'INPUT',&
         'Signal cube',&
         strg_emp,&
         code_arg_optional,&
         [flag_any],&
         code_read,&
         code_access_imaset,&
         comm%cube,&
         error)
    if (error) return
    call comm%percentage%register(&
         'AT',&
         'Define the percentile P in percent (0..100)',&
         'Default is 10% if /AT is omitted.',&
         prog%plow,&
         code_unit_unk,&
         strg_emp,&
         error)
    call comm%region%register(error)
    if (error) return
    !
    ! Products
    call oucube%register(&
         'LOW PERCENTILE',&
         'Low percentile min(P,100-P)%',&
         strg_emp,&
         [flag_low,flag_percentile,flag_spectrum],&
         comm%qlow,&
         error)
    if (error)  return
    call oucube%register(&
         'HIGH PERCENTILE',&
         'High percentile max(P,100-P)%',&
         strg_emp,&
         [flag_high,flag_percentile,flag_spectrum],&
         comm%qhigh,&
         error)
    if (error)  return
  end subroutine cubestatistics_percentile_comm_register
  !
  subroutine cubestatistics_percentile_comm_parse(comm,line,user,error)
    !----------------------------------------------------------------------
    ! PERCENTILE cubeid /PERCENTAGE val
    !----------------------------------------------------------------------
    class(percentile_comm_t), intent(in)    :: comm
    character(len=*),         intent(in)    :: line
    type(percentile_user_t),  intent(out)   :: user
    logical,                  intent(inout) :: error
    !
    character(len=*), parameter :: rname='PERCENTILE>COMM>PARSE'
    !
    call cubestatistics_message(statisticsseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_parse(line,comm%comm,user%cubeids,error)
    if (error) return
    call comm%percentage%parse(line,user%percentage,error)
    if (error) return
    call comm%region%parse(line,user%region,error)
    if (error) return
  end subroutine cubestatistics_percentile_comm_parse
  !
  subroutine cubestatistics_percentile_comm_main(comm,user,error)
    use cubeadm_timing
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(percentile_comm_t), intent(in)    :: comm
    type(percentile_user_t),  intent(inout) :: user
    logical,                  intent(inout) :: error
    !
    type(percentile_prog_t) :: prog
    character(len=*), parameter :: rname='PERCENTILE>MAIN'
    !
    call cubestatistics_message(statisticsseve%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 cubestatistics_percentile_comm_main
  !
  !----------------------------------------------------------------------
  !
  subroutine cubestatistics_percentile_user_toprog(user,comm,prog,error)
    use cubeadm_get
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(percentile_user_t), intent(in)    :: user
    type(percentile_comm_t),  intent(in)    :: comm
    type(percentile_prog_t),  intent(out)   :: prog
    logical,                  intent(inout) :: error
    !
    real(kind=sign_k) :: percentage
    character(len=*), parameter :: rname='PERCENTILE>USER>TOPROG'
    !
    call cubestatistics_message(statisticsseve%trace,rname,'Welcome')
    !
    call cubeadm_get_header(comm%cube,user%cubeids,prog%cube,error)
    if (error) return
    call user%percentage%toprog(comm%percentage,percentage,error)
    if (error) return
    if ((percentage.lt.0).or.(100.lt.percentage)) then
       call cubestatistics_message(seve%e,rname,'Percentage outside the [0,100] range')
       error = .true.
       return
    endif
    if (percentage.gt.50) then
       prog%plow  = 100-percentage
       prog%phigh = percentage
    else
       prog%plow  = percentage
       prog%phigh = 100-percentage
    endif
    call user%region%toprog(prog%cube,prog%region,error)
    if (error) return
    ! User feedback about the interpretation of his command line
    call prog%region%list(error)
    if (error) return
  end subroutine cubestatistics_percentile_user_toprog
  !
  !----------------------------------------------------------------------
  !
  subroutine cubestatistics_percentile_prog_header(prog,comm,error)
    use cubeadm_clone
    use cubetools_header_methods
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(percentile_prog_t), intent(inout) :: prog
    type(percentile_comm_t),  intent(in)    :: comm
    logical,                  intent(inout) :: error
    !
    integer(kind=chan_k), parameter :: one=1
    character(len=*), parameter :: rname='PERCENTILE>PROG>HEADER'
    !
    call cubestatistics_message(statisticsseve%trace,rname,'Welcome')
    !
    call one_header(comm%qlow,prog%cube,prog%region,prog%qlow,error)
    if (error) return
    call one_header(comm%qhigh,prog%cube,prog%region,prog%qhigh,error)
    if (error) return
    !
  contains
    !
    subroutine one_header(oucomm,incube,region,oucube,error)
      use cubeadm_clone
      use cubetools_header_methods
      !----------------------------------------------------------------------
      !
      !----------------------------------------------------------------------
      type(cube_prod_t),       intent(in)    :: oucomm
      type(cube_t), pointer,   intent(in)    :: incube
      type(cuberegion_prog_t), intent(inout) :: region
      type(cube_t), pointer,   intent(inout) :: oucube
      logical,                 intent(inout) :: error
      !
      character(len=unit_l) :: unit
      integer(kind=chan_k), parameter :: one=1
      !
      call cubeadm_clone_header(oucomm,incube,oucube,error)
      if (error) return
      call region%header(oucube,error)
      if (error) return
      call cubetools_header_put_nxny(one,one,oucube%head,error)
      if (error) return
      !
      call cubetools_header_get_array_unit(incube%head,unit,error)
      if (error) return
      call cubetools_header_put_array_unit(trim(unit),oucube%head,error)
      if (error) return
    end subroutine one_header    
  end subroutine cubestatistics_percentile_prog_header
  !
  subroutine cubestatistics_percentile_prog_data(prog,error)
    use cubeadm_opened
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(percentile_prog_t), intent(inout) :: prog
    logical,                  intent(inout) :: error
    !
    type(cubeadm_iterator_t) :: iter
    character(len=*), parameter :: rname='PERCENTILE>PROG>DATA'
    !
    call cubestatistics_message(statisticsseve%trace,rname,'Welcome')
    !
    !***JP: The iterator does not know how to handle a subregion for the input
    !***JP: and another size of the output
!    call cubeadm_datainit_all(iter,prog%region,error)
    call cubeadm_datainit_all(iter,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 cubestatistics_percentile_prog_data
  !   
  subroutine cubestatistics_percentile_prog_loop(prog,iter,error)
    use cubetools_array_types
    use cubeadm_taskloop
    use cubeadm_image_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(percentile_prog_t), intent(inout) :: prog
    type(cubeadm_iterator_t), intent(inout) :: iter
    logical,                  intent(inout) :: error
    !
    type(image_t) :: image,qlow,qhigh
    type(real_1d_t) :: good
    character(len=*), parameter :: rname='PERCENTILE>PROG>LOOP'
    !
    call image%associate('cube',prog%cube,iter,error)
    if (error) return
    call good%reallocate('good',image%nx*image%ny,error)
    if (error) return
    call qlow%allocate('qlow',prog%qlow,iter,error)
    if (error) return
    call qhigh%allocate('qhigh',prog%qhigh,iter,error)
    if (error) return
    !
    do while (iter%iterate_entry(error))
      call prog%act(iter%ie,image,good,qlow,qhigh,error)
      if (error) return
    enddo ! ie
  end subroutine cubestatistics_percentile_prog_loop
  !   
  subroutine cubestatistics_percentile_prog_act(prog,ie,image,good,qlow,qhigh,error)
    use cubetools_array_types
    use cubeadm_image_types
    use cubemain_statistics_tool
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(percentile_prog_t), intent(inout) :: prog
    integer(kind=entr_k),     intent(in)    :: ie
    type(image_t),            intent(inout) :: image
    type(real_1d_t),          intent(inout) :: good
    type(image_t),            intent(inout) :: qlow
    type(image_t),            intent(inout) :: qhigh
    logical,                  intent(inout) :: error
    !
    type(real_1d_t) :: reshaped
    integer(kind=pixe_k), parameter :: one=1
    character(len=*), parameter :: rname='PERCENTILE>PROG>ACT'
    !
    call image%get(ie,error)
    if (error) return
    call reshape%from_2d_to_1d(image,reshaped,'reshaped',error)
    if (error) return
    call good%unblank(reshaped,error)
    if (error) return
    ! qlow must be computed before qhigh
    qlow%val(one,one) = statistics%percentile(good%val,good%n,prog%plow)
    call qlow%put(ie,error)
    if (error) return
    qhigh%val(one,one) = statistics%percentile(good%val,good%n,prog%phigh)
    call qhigh%put(ie,error)
    if (error) return    
  end subroutine cubestatistics_percentile_prog_act
end module cubestatistics_percentile
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
