!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubemain_detect
  use cube_types
  use cubetools_structure
  use cubeadm_cubeid_types
  use cubetopology_sperange_types
  use cubemain_messaging
  !
  public :: detect
  public :: cubemain_detect_command
  private
  !
  type :: detect_comm_t
     type(option_t), pointer :: comm  
     type(option_t), pointer :: islands
     type(sperange_opt_t)    :: sperange
   contains
     procedure, public  :: register => cubemain_detect_register
     procedure, private :: parse    => cubemain_detect_parse
     procedure, private :: main     => cubemain_detect_main
  end type detect_comm_t
  type(detect_comm_t) :: detect
  !
  integer(kind=4), parameter :: icube = 1
  integer(kind=4), parameter :: ilabeled = 2
  type detect_user_t
     type(cubeid_user_t)   :: cubeids
     type(sperange_user_t) :: sperange
     character(len=argu_l) :: islrange(2)
   contains
     procedure, private :: toprog => cubemain_detect_user_toprog
  end type detect_user_t
  !
  type detect_prog_t
     type(sperange_prog_t) :: sperange
     integer(kind=data_k)  :: islrange(2)
     type(cube_t), pointer :: cube
     type(cube_t), pointer :: labeled
     type(cube_t), pointer :: detected
     type(cube_t), pointer :: residuals
   contains
     procedure, private :: header => cubemain_detect_prog_header
!!$     procedure, private :: data   => cubemain_detect_prog_data
!!$     procedure, private :: loop   => cubemain_detect_prog_loop
!!$     procedure, private :: act    => cubemain_detect_prog_act
     procedure, private :: data   => cubemain_detect_image_prog_data
     procedure, private :: loop   => cubemain_detect_image_prog_loop
     procedure, private :: act    => cubemain_detect_image_prog_act
  end type detect_prog_t
  !
contains
  !
  subroutine cubemain_detect_command(line,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: line
    logical,          intent(inout) :: error
    !
    type(detect_user_t) :: user
    character(len=*), parameter :: rname='DETECT>COMMAND'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call detect%parse(line,user,error)
    if (error) return
    call detect%main(user,error)
    if (error) continue
  end subroutine cubemain_detect_command
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_detect_register(detect,error)
    use cubedag_allflags
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(detect_comm_t), intent(inout) :: detect
    logical,              intent(inout) :: error
    !
    type(cubeid_arg_t) :: cubearg
    type(standard_arg_t) :: stdarg
    character(len=*), parameter :: comm_abstract='Split the data into detected signal voxels and residual ones'
    character(len=*), parameter :: comm_help = &
         'Select from a segmented SNR cube a segment range and create a&
         & cube of detected signal inside the corresponding island mask.&
         & The remainder is output into a residual cube.'
    character(len=*), parameter :: rname='DETECT>REGISTER'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubetools_register_command(&
         'DETECT','[cube]',&
         comm_abstract,&
         comm_help,&
         cubemain_detect_command,&
         detect%comm,error)
    if (error) return
    call cubearg%register(&
         'DATA',&
         'data cube',&
         strg_id,&
         code_arg_optional,&
         [flag_cube],&
         error)
    if (error) return
    call cubearg%register(&
         'SEGMENTS',&
         'Segment labels',&
         strg_id,&
         code_arg_optional,&
         [flag_segments],&
         error)
    if (error) return
    !
    call cubetools_register_option(&
         'SEGMENTS','first last',&
         'First and last segments to form the detection mask',&
         strg_id,&
         detect%islands,error)
    if (error) return
    call stdarg%register(&
         'first',&
         'first',&
         'Default to 1',&
         code_arg_mandatory, error)
    if (error) return
    call stdarg%register(&
         'last',&
         'last',&
         'Default to the number of segments minus 1',&
         code_arg_mandatory, error)
    if (error) return
    !
    call detect%sperange%register(&
         'RANGE',&
         'Set the velocity range of the spectral region of interest',&
         error)
    if (error) return
  end subroutine cubemain_detect_register
  !
  subroutine cubemain_detect_parse(detect,line,user,error)
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(detect_comm_t), intent(in)    :: detect
    character(len=*),     intent(in)    :: line
    type(detect_user_t),  intent(out)   :: user
    logical,              intent(inout) :: error
    !
    character(len=*), parameter :: rname='DETECT>PARSE'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_parse(line,detect%comm,user%cubeids,error)
    if (error) return
    call cubemain_detect_parse_twoarg(line,detect%islands,user%islrange,error)
    if (error) return
    call detect%sperange%parse(line,user%sperange,error)
    if (error) return
  end subroutine cubemain_detect_parse
  !
  subroutine cubemain_detect_parse_twoarg(line,key,args,error)
    !----------------------------------------------------------------------
    ! /KEY first last
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: line
    type(option_t),   intent(in)    :: key
    character(len=*), intent(out)   :: args(2)
    logical,          intent(inout) :: error
    !
    logical :: present
    integer(kind=4) :: iarg
    character(len=*), parameter :: rname='DETECT>PARSE>TWOARG'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call key%present(line,present,error)
    if (error) return
    if (present) then
       do iarg=1,2
          call cubetools_getarg(line,key,iarg,args(iarg),mandatory,error)
          if (error) return
       enddo ! iarg
    else
       do iarg=1,2
          args(iarg) = strg_star
       enddo ! iarg
    endif
  end subroutine cubemain_detect_parse_twoarg
  !
  subroutine cubemain_detect_main(detect,user,error) 
    use cubeadm_timing
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(detect_comm_t), intent(in)    :: detect
    type(detect_user_t),  intent(inout) :: user
    logical,              intent(inout) :: error
    !
    type(detect_prog_t) :: prog
    character(len=*), parameter :: rname='DETECT>MAIN'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call user%toprog(prog,error)
    if (error) return
    call prog%header(error)
    if (error) return
    call cubeadm_timing_prepro2process()
    call prog%data(error)
    if (error) return
    call cubeadm_timing_process2postpro()
  end subroutine cubemain_detect_main
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_detect_user_toprog(user,prog,error)
    use cubetools_arrelt_types
    use cubetools_header_methods    
    use cubetools_user2prog
    use cubeadm_get
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(detect_user_t), intent(in)    :: user
    type(detect_prog_t),  intent(out)   :: prog
    logical,              intent(inout) :: error
    !
    integer(kind=4) :: iarg
    type(arrelt_t) :: min,max
    integer(kind=data_k) :: default(2)
    character(len=*), parameter :: rname='DETECT>USER>TOPROG'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
!!$    call cubeadm_cubeid_get_header(detect%comm,icube,user%cubeids,&
!!$         code_access_subset,code_read,prog%cube,error)
    call cubeadm_cubeid_get_header(detect%comm,icube,user%cubeids,&
         code_access_imaset,code_read,prog%cube,error)
    if (error) return
    call cubeadm_cubeid_get_header(detect%comm,ilabeled,user%cubeids,&
         code_access_imaset,code_read,prog%labeled,error)
    if (error) return
    !
    call cubetools_header_get_array_minmax(prog%labeled%head,min,max,error)
    if (error) return
    default(1) = 1
    default(2) = max%val-1
    do iarg=1,2
       call cubetools_user2prog_resolve_star(user%islrange(iarg),default(iarg),default(iarg),error)
       if (error) return
    enddo ! iarg
    prog%islrange(1) = max%val-default(2)+1
    prog%islrange(2) = max%val-default(1)+1
    !
    call user%sperange%toprog(prog%cube,prog%sperange,error)
    if (error) return
  end subroutine cubemain_detect_user_toprog
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_detect_prog_header(prog,error)
    use cubedag_allflags
    use cubeadm_clone
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(detect_prog_t), intent(inout) :: prog
    logical,              intent(inout) :: error
    !
    character(len=*), parameter :: rname='DETECT>PROG>HEADER'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_clone_header(prog%cube,flag_detected,prog%detected,error)
    if (error) return
    call cubeadm_clone_header(prog%cube,flag_residuals,prog%residuals,error)
    if (error) return
  end subroutine cubemain_detect_prog_header
  !
!!$  subroutine cubemain_detect_prog_data(prog,error)
!!$    use cubeadm_opened
!!$    !----------------------------------------------------------------------
!!$    ! 
!!$    !----------------------------------------------------------------------
!!$    class(detect_prog_t), intent(inout) :: prog
!!$    logical,              intent(inout) :: error
!!$    !
!!$    type(cubeadm_iterator_t) :: itertask
!!$    character(len=*), parameter :: rname='DETECT>PROG>DATA'
!!$    !
!!$    call cubemain_message(mainseve%trace,rname,'Welcome')
!!$    !
!!$    call cubeadm_datainit_all(itertask,error)
!!$    if (error) return
!!$    !$OMP PARALLEL DEFAULT(none) SHARED(prog,error) FIRSTPRIVATE(itertask)
!!$    !$OMP SINGLE
!!$    do while (cubeadm_dataiterate_all(itertask,error))
!!$       if (error) exit
!!$       !$OMP TASK SHARED(prog,error) FIRSTPRIVATE(itertask)
!!$       if (.not.error) &
!!$         call prog%loop(itertask,error)
!!$       !$OMP END TASK
!!$    enddo ! itertask
!!$    !$OMP END SINGLE
!!$    !$OMP END PARALLEL
!!$  end subroutine cubemain_detect_prog_data
!!$  !
!!$  subroutine cubemain_detect_prog_loop(prog,itertask,error)
!!$    use cubeadm_taskloop
!!$    !----------------------------------------------------------------------
!!$    ! The subcube iterator will be shared by all input and output subcubes
!!$    !----------------------------------------------------------------------
!!$    class(detect_prog_t),     intent(inout) :: prog
!!$    type(cubeadm_iterator_t), intent(inout) :: itertask
!!$    logical,                  intent(inout) :: error
!!$    !
!!$    character(len=*), parameter :: rname='DETECT>PROG>LOOP'
!!$    !
!!$    do while (itertask%iterate_entry(error))
!!$       call prog%act(itertask,error)
!!$       if (error) return
!!$    enddo  ! ientry
!!$  end subroutine cubemain_detect_prog_loop
!!$  !   
!!$  subroutine cubemain_detect_prog_act(prog,itertask,error)
!!$    use cubetools_nan
!!$    use cubeadm_taskloop
!!$    use cubeadm_subcube_types
!!$    !----------------------------------------------------------------------
!!$    !
!!$    !----------------------------------------------------------------------
!!$    class(detect_prog_t),     intent(inout) :: prog
!!$    type(cubeadm_iterator_t), intent(in)    :: itertask
!!$    logical,                  intent(inout) :: error
!!$    !
!!$    integer(kind=indx_k) :: ix,iy,iz
!!$    type(subcube_t) :: cube,labeled,detected,residuals
!!$    character(len=*), parameter :: rname='DETECT>PROG>ACT'
!!$    !
!!$    ! Detects are initialized here as their size (3rd dim) may change from
!!$    ! from one detect to another.
!!$    call cube%associate('cube',prog%cube,itertask,error)
!!$    if (error) return
!!$    call labeled%associate('labeled',prog%labeled,itertask,error)
!!$    if (error) return
!!$    call detected%allocate('detected',prog%detected,itertask,error)
!!$    if (error) return
!!$    call residuals%allocate('residuals',prog%residuals,itertask,error)
!!$    if (error) return
!!$    !
!!$    call cube%get(error)
!!$    if (error) return
!!$    call labeled%get(error)
!!$    if (error) return
!!$    do iz=1,cube%nz
!!$       if ((prog%sperange%p(1).le.iz).and.(iz.le.prog%sperange%p(2))) then
!!$          do iy=1,cube%ny
!!$             do ix=1,cube%nx
!!$                if (ieee_is_nan(cube%val(ix,iy,iz))) then
!!$                   detected%val(ix,iy,iz)  = gr4nan
!!$                   residuals%val(ix,iy,iz) = gr4nan
!!$                else
!!$                   if ((prog%islrange(1).le.labeled%val(ix,iy,iz)).and.&
!!$                        (labeled%val(ix,iy,iz).le.prog%islrange(2))) then
!!$                      detected%val(ix,iy,iz)  = cube%val(ix,iy,iz)
!!$                      residuals%val(ix,iy,iz) = 0
!!$                   else
!!$                      detected%val(ix,iy,iz)  = gr4nan
!!$                      residuals%val(ix,iy,iz) = cube%val(ix,iy,iz)
!!$                   endif
!!$                endif
!!$             enddo ! ix
!!$          enddo ! iy
!!$       else
!!$          do iy=1,cube%ny
!!$             do ix=1,cube%nx
!!$                detected%val(ix,iy,iz)  = 0
!!$                residuals%val(ix,iy,iz) = cube%val(ix,iy,iz)
!!$             enddo ! ix
!!$          enddo ! iy
!!$       endif
!!$    enddo ! iz
!!$    call detected%put(error)
!!$    if (error) return
!!$    call residuals%put(error)
!!$    if (error) return
!!$  end subroutine cubemain_detect_prog_act
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_detect_image_prog_data(prog,error)
    use cubeadm_opened
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(detect_prog_t), intent(inout) :: prog
    logical,              intent(inout) :: error
    !
    type(cubeadm_iterator_t) :: iter
    character(len=*), parameter :: rname='DETECT>IMAGE>PROG>DATA'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    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 ! iter
    !$OMP END SINGLE
    !$OMP END PARALLEL
  end subroutine cubemain_detect_image_prog_data
  !   
  subroutine cubemain_detect_image_prog_loop(prog,iter,error)
    use cubeadm_taskloop
    use cubeadm_image_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(detect_prog_t),     intent(inout) :: prog
    type(cubeadm_iterator_t), intent(inout) :: iter
    logical,                  intent(inout) :: error
    !
    type(image_t) :: image,labeled,detected,residuals
    character(len=*), parameter :: rname='DETECT>IMAGE>PROG>LOOP'
    !
    call image%associate('image',prog%cube,iter,error)
    if (error) return
    call labeled%associate('labeled',prog%labeled,iter,error)
    if (error) return
    call detected%allocate('detected',prog%detected,iter,error)
    if (error) return
    call residuals%allocate('residuals',prog%residuals,iter,error)
    if (error) return
    !
    do while (iter%iterate_entry(error))
      call prog%act(iter%ie,image,labeled,detected,residuals,error)
      if (error) return
    enddo ! ie
  end subroutine cubemain_detect_image_prog_loop
  !   
  subroutine cubemain_detect_image_prog_act(prog,ie,image,labeled,detected,residuals,error)
    use cubetools_nan
    use cubeadm_image_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(detect_prog_t), intent(inout) :: prog
    integer(kind=entr_k), intent(in)    :: ie
    type(image_t),        intent(inout) :: image
    type(image_t),        intent(inout) :: labeled
    type(image_t),        intent(inout) :: detected
    type(image_t),        intent(inout) :: residuals
    logical,              intent(inout) :: error
    !
    integer(kind=pixe_k) :: ix,iy
    character(len=*), parameter :: rname='DETECT>IMAGE>PROG>ACT'
    !
    call image%get(ie,error)
    if (error) return
    call labeled%get(ie,error)
    if (error) return
    if ((prog%sperange%p(1).le.ie).and.(ie.le.prog%sperange%p(2))) then
       do iy=1,image%ny
          do ix=1,image%nx
             if (ieee_is_nan(image%val(ix,iy))) then
                detected%val(ix,iy)  = gr4nan
                residuals%val(ix,iy) = gr4nan
             else
                if ((prog%islrange(1).le.labeled%val(ix,iy)).and.&
                     (labeled%val(ix,iy).le.prog%islrange(2))) then
                   detected%val(ix,iy)  = image%val(ix,iy)
                   residuals%val(ix,iy) = 0
                else
                   detected%val(ix,iy)  = gr4nan
                   residuals%val(ix,iy) = image%val(ix,iy)
                endif
             endif
          enddo ! ix
       enddo ! iy
    else
       do iy=1,image%ny
          do ix=1,image%nx
             detected%val(ix,iy)  = 0
             residuals%val(ix,iy) = image%val(ix,iy)
          enddo ! ix
       enddo ! iy
    endif
    call detected%put(ie,error)
    if (error) return
    call residuals%put(ie,error)
    if (error) return
  end subroutine cubemain_detect_image_prog_act
end module cubemain_detect
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
