!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubefit_residuals
  use cube_types
  use cubetools_structure
  use cubetools_axis_types
  use cubeadm_cubeid_types
  use cubeadm_cubeprod_types
  use cubetopology_sperange_types
  use cubefit_messaging
  use cubefit_hfs
  use cubefit_parameters
  use cubefit_selection
  !
  public :: residuals
  private
  !
  type :: residuals_comm_t
     type(option_t),     pointer :: comm
     type(cubeid_arg_t), pointer :: incube
     type(cubeid_arg_t), pointer :: fitcube
     type(sperange_opt_t)        :: range
     type(option_t),     pointer :: hfs
     type(selection_opt_t)       :: select
     type(cube_prod_t),  pointer :: oucube
   contains
     procedure, public  :: register => cubefit_residuals_register
     procedure, private :: parse    => cubefit_residuals_parse
     procedure, private :: main     => cubefit_residuals_main
  end type residuals_comm_t
  type(residuals_comm_t) :: residuals
  !
  type residuals_user_t
     type(cubeid_user_t)    :: cubeids
     type(sperange_user_t)  :: range
     type(hfs_user_t)       :: hfs
     type(selection_user_t) :: sele
   contains
     procedure, private :: toprog => cubefit_residuals_user_toprog     
  end type residuals_user_t
  type residuals_prog_t
     type(sperange_prog_t)  :: range
     integer(kind=chan_k)   :: fc,lc
     type(hfs_prog_t)       :: hfs
     logical                :: found
     logical                :: overlap
     integer(kind=chan_k)   :: deltachan
     type(selection_prog_t) :: sele
     type(axis_t)           :: axis
     type(cube_t), pointer  :: incube
     type(cube_t), pointer  :: fitcube
     type(cube_t), pointer  :: oucube
   contains
     procedure, private :: header => cubefit_residuals_prog_header
     procedure, private :: data   => cubefit_residuals_prog_data
     procedure, private :: loop   => cubefit_residuals_prog_loop
     procedure, private :: act    => cubefit_residuals_prog_act
  end type residuals_prog_t
  !
contains
  !
  subroutine cubefit_residuals_command(line,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    character(len=*),       intent(in)    :: line
    logical,                intent(inout) :: error
    !
    type(residuals_user_t) :: user
    character(len=*), parameter :: rname='RESIDUALS>COMMAND'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    call residuals%parse(line,user,error)
    if (error) return
    call residuals%main(user,error)
    if (error) return
  end subroutine cubefit_residuals_command
  !
  !----------------------------------------------------------------------
  !
  subroutine cubefit_residuals_register(residuals,error)
    use cubedag_allflags
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(residuals_comm_t), intent(inout) :: residuals
    logical,                 intent(inout) :: error
    !
    type(cubeid_arg_t) :: cubearg
    type(cube_prod_t) :: oucube
    character(len=*), parameter :: rname='RESIDUALS>REGISTER'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    call cubetools_register_command(&
         'RESIDUALS','[signalid [fitid]]',&
         'Subtract fitted profiles from the data cube',&
         'Create a cube of what remains after subtracting the fitted model&
         & from the observed spectra. RESIDUALS rebuilds either the full&
         & fitted profile or one selected method/component from the&
         & fit-results cube produced by FIT\MINIMIZE, subtracts it from&
         & the input signal over the requested /RANGE, and uses the signal&
         & cube to keep the original PPV grid for the output residual&
         & cube. Spectra or channels for which no valid residual can be&
         & computed are written as NaN. Use /HFS when the fit used the HFS&
         & or ABSORPTION methods.',&
         cubefit_residuals_command,&
         residuals%comm,error)
    if (error) return
    call cubearg%register(&
         'SIGNALID',&
         'Signal cube identifier',&
         'If omitted, use the last matching cube (cube flag) in the default&
         & index (DAG by default; see SET\INDEX). RESIDUALS subtracts the&
         & reconstructed model from this signal cube and uses it to clone&
         & the original PPV grid and header for the output residual cube.',&
         code_arg_optional,&
         [flag_cube],&
         code_read,&
         code_access_speset,&
         residuals%incube,&
         error)
    if (error) return
    call cubearg%register(&
         'FITID',&
         'Identifier for the fit-results cube',&
         'If omitted, use the last matching cube (fit,minimize flags) in the&
         & default index (DAG by default; see SET\INDEX).',&
         code_arg_optional,&
         [flag_fit,flag_minimize],&
         code_read,&
         code_access_speset,&
         residuals%fitcube,&
         error)
    if (error) return
    !
    call residuals%range%register(&
         'RANGE',&
         'Define velocity range for residuals',&
         error)
    if (error) return
    !
    call cubefit_hfs_register(residuals%hfs,error)
    if (error) return
    !
    call residuals%select%register(error)
    if (error) return
    !
    ! Product
    call oucube%register(&
         'RESIDUALS',&
         'Cube of residuals',&
         strg_emp,&
         [flag_fit,flag_residuals],&
         residuals%oucube,&
         error)
    if (error) return
  end subroutine cubefit_residuals_register
  !
  subroutine cubefit_residuals_parse(residuals,line,user,error)
    !----------------------------------------------------------------------
    ! RESIDUALS cubname
    ! /RANGE vfirst vlast [unit]
    ! /HFS file.hfs
    ! /SELECT method [ifunc]
    !----------------------------------------------------------------------
    class(residuals_comm_t), intent(in)    :: residuals
    character(len=*),        intent(in)    :: line
    type(residuals_user_t),  intent(out)   :: user
    logical,                 intent(inout) :: error
    !
    character(len=*), parameter :: rname='RESIDUALS>PARSE'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_parse(line,residuals%comm,user%cubeids,error)
    if (error) return
    call residuals%range%parse(line,user%range,error)
    if (error) return
    call cubefit_hfs_parse(line,residuals%hfs,user%hfs,error)
    if (error) return
    call residuals%select%parse(line,user%sele,error)
    if (error) return
  end subroutine cubefit_residuals_parse
  !
  subroutine cubefit_residuals_main(residuals,user,error) 
    use cubeadm_timing
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(residuals_comm_t), intent(in)    :: residuals
    type(residuals_user_t),  intent(in)    :: user
    logical,                 intent(inout) :: error
    !
    type(residuals_prog_t) :: prog
    character(len=*), parameter :: rname='RESIDUALS>MAIN'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    call user%toprog(prog,error)
    if (error) return
    call prog%header(residuals,error)
    if (error) return
    call cubeadm_timing_prepro2process()
    call prog%data(error)
    if (error) return
    call cubeadm_timing_process2postpro()
  end subroutine cubefit_residuals_main
  !
  !----------------------------------------------------------------------
  !
  subroutine cubefit_residuals_user_toprog(user,prog,error)
    use cubetools_header_methods
    use cubetools_disambiguate
    use cubeadm_get
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(residuals_user_t), intent(in)    :: user
    type(residuals_prog_t),  intent(out)   :: prog
    logical,                 intent(inout) :: error
    !
    integer(kind=chan_k) :: nchan,stride
    character(len=*), parameter :: rname='RESIDUALS>USER>TOPROG'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    call cubeadm_get_header(residuals%incube,user%cubeids,&
         prog%incube,error)
    if (error) return
    call cubeadm_get_header(residuals%fitcube,user%cubeids,&
         prog%fitcube,error)
    if (error) return
    !
    call user%range%toprog(prog%incube,code_sperange_truncated,prog%range,error)
    if (error) return
    call prog%range%to_chan_k(prog%fc,prog%lc,stride,error)
    if (error) return
    call cubetools_header_get_axis_head_f(prog%incube%head,prog%axis,error)
    if (error) return
    prog%axis%n = prog%lc-prog%fc+1
    prog%axis%ref = prog%axis%ref-prog%fc+1
    prog%deltachan = prog%fc-1
    call cubetools_header_get_nchan(prog%incube%head,nchan,error)
    if (error) return
    prog%overlap = abs(prog%deltachan).lt.nchan
    !
    call cubefit_hfs_user2prog(user%hfs,prog%hfs,error)
    if (error) return
    call residuals%select%user2prog(user%sele,prog%sele,error)
    if (error) return
    !
  end subroutine cubefit_residuals_user_toprog
  !
  !----------------------------------------------------------------------
  !
  subroutine cubefit_residuals_prog_header(prog,comm,error)
    use cubetools_header_methods
    use cubeadm_clone
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(residuals_prog_t), intent(inout) :: prog
    type(residuals_comm_t),  intent(in)    :: comm
    logical,                 intent(inout) :: error
    !
    character(len=*), parameter :: rname='RESIDUALS>PROG>HEADER'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    call cubeadm_clone_header(comm%oucube,prog%incube,prog%oucube,error)
    if (error) return
    !
    call cubetools_header_update_frequency_from_axis(prog%axis,prog%oucube%head,error)
    if (error) return
  end subroutine cubefit_residuals_prog_header
  !
  subroutine cubefit_residuals_prog_data(prog,error)
    use cubeadm_opened
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(residuals_prog_t), intent(inout) :: prog
    logical,                intent(inout) :: error
    !
    type(cubeadm_iterator_t) :: iter
    character(len=*), parameter :: rname='RESIDUALS>PROG>DATA'
    !
    call cubefit_message(fitseve%trace,rname,'Welcome')
    !
    ! At the start nothing has been found
    prog%found = .false.
    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 ! ie
    !$OMP END SINGLE
    !$OMP END PARALLEL
    !
    if (.not.prog%found) then
       call cubefit_message(seve%w,rname,'No data found under current selection')
    endif
  end subroutine cubefit_residuals_prog_data
  !   
  subroutine cubefit_residuals_prog_loop(prog,iter,error)
    use cubeadm_taskloop
    use cubemain_spectrum_real
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(residuals_prog_t),  intent(inout) :: prog
    type(cubeadm_iterator_t), intent(inout) :: iter
    logical,                  intent(inout) :: error
    !
    type(spectrum_t) :: fitspec,inspec,ouspec
    character(len=*), parameter :: rname='RESIDUALS>PROG>LOOP'
    !
    call fitspec%reassociate_and_init(prog%fitcube,iter,error)
    if (error) return
    call inspec%reassociate_and_init(prog%incube,iter,error)
    if (error) return
    call ouspec%reallocate_and_init(prog%oucube,iter,error)
    if (error) return
    !
    do while (iter%iterate_entry(error))
      call prog%act(iter%ie,fitspec,inspec,ouspec,error)
      if (error) return
    enddo
  end subroutine cubefit_residuals_prog_loop
  !   
  subroutine cubefit_residuals_prog_act(prog,ie,fitspec,inspec,ouspec,error)
    use cubetools_nan
    use cubemain_spectrum_real
    use cubefit_spectral_fit
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(residuals_prog_t), intent(inout) :: prog
    integer(kind=entr_k),    intent(in)    :: ie
    type(spectrum_t),        intent(inout) :: fitspec
    type(spectrum_t),        intent(inout) :: inspec
    type(spectrum_t),        intent(inout) :: ouspec
    logical,                 intent(inout) :: error
    !
    logical :: doprof
    integer(kind=chan_k) :: ichan,jchan
    type(fit_spectral_t) :: fit
    character(len=*), parameter :: rname='RESIDUALS>PROG>ACT'
    !
    if (prog%overlap) then
       call fitspec%get(prog%fitcube,ie,error)
       if (error) return
       call inspec%get(prog%incube,ie,error)
       if (error) return
       doprof = .not.(ieee_is_nan(fitspec%t(icol_status)).or.nint(fitspec%t(icol_status)).eq.code_status_diverged)
       if (prog%sele%imeth.ne.0) then
          doprof = doprof.and.(prog%sele%imeth.eq.nint(fitspec%t(icol_method)))
       endif
       doprof = doprof.and.(prog%sele%ifunc.le.nint(fitspec%t(icol_nfunc)))   
       !
       if (doprof) then
          prog%found = .true.
          call fit%spec_import(prog%hfs,fitspec,error)
          if (error) return
          call fit%profile(prog%sele%ifunc,ouspec,error)
          if (error) return
          !
          do ichan=1,ouspec%n
             jchan = ichan+prog%deltachan
             if (jchan.le.0.or.jchan.gt.inspec%n) then
                ouspec%t(ichan) = gr4nan
             else
                ouspec%t(ichan) = inspec%t(jchan)-ouspec%t(ichan)
             endif
          enddo
       else
          ouspec%t(:) = gr4nan
       endif
    else
       ouspec%t(:) = gr4nan
    endif
    call ouspec%put(prog%oucube,ie,error)
    if (error) return
  end subroutine cubefit_residuals_prog_act
end module cubefit_residuals
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
