!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubemain_convert
  use cube_types
  use cubetools_structure
  use cubeadm_cubeid_types
  use cubemain_messaging
  !
  public :: convert
  public :: cubemain_convert_command
  private
  !
  type :: convert_comm_t
     type(option_t),      pointer :: comm
     type(option_t),      pointer :: unit
     type(option_t),      pointer :: efficiencies
     type(option_t),      pointer :: factor
   contains
     procedure, public  :: register           => cubemain_convert_register
     procedure, private :: parse              => cubemain_convert_parse
     procedure, private :: parse_unit         => cubemain_convert_parse_unit
     procedure, private :: parse_factor       => cubemain_convert_parse_factor
     procedure, private :: parse_efficiencies => cubemain_convert_parse_efficiencies
     procedure, private :: main               => cubemain_convert_main
  end type convert_comm_t  
  type(convert_comm_t) :: convert
  !
  integer(kind=4), parameter :: icube = 1
  type convert_user_t
     type(cubeid_user_t)   :: cubeids
     logical               :: dounit
     character(len=argu_l) :: unit
     logical               :: dofactor
     real(kind=sign_k)     :: factor     ! User defined convertion factor
     logical               :: doapplyeff
     real(kind=sign_k)     :: beff       ! Beam Efficiency
     real(kind=sign_k)     :: feff       ! Forward Efficiency
   contains
     procedure, private :: toprog => cubemain_convert_user_toprog
  end type convert_user_t
  !
  type convert_prog_t
     type(cube_t), pointer :: incube     ! Input cube
     type(cube_t), pointer :: converted  ! Output cube
     character(len=unit_l) :: unit_name  ! Name of output unit
     integer(kind=code_k)  :: unit_code  ! Code of output unit
     real(kind=sign_k)     :: factor     ! Convertion factor
   contains
     procedure, private :: header => cubemain_convert_prog_header
     procedure, private :: data   => cubemain_convert_prog_data
     procedure, private :: loop   => cubemain_convert_prog_loop
     procedure, private :: act    => cubemain_convert_prog_act
  end type convert_prog_t
  !
contains
  !
  subroutine cubemain_convert_command(line,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: line
    logical,          intent(inout) :: error
    !
    type(convert_user_t) :: user
    character(len=*), parameter :: rname='CONVERT>COMMAND'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call convert%parse(line,user,error)
    if (error) return
    call convert%main(user,error)
    if (error) continue
  end subroutine cubemain_convert_command
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_convert_register(convert,error)
    use cubedag_allflags
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(convert_comm_t), intent(inout) :: convert
    logical,               intent(inout) :: error
    !
    type(cubeid_arg_t) :: cubearg
    type(standard_arg_t) :: stdarg
    character(len=*), parameter :: comm_abstract = &
         'Convert the unit of the cube data'
    character(len=*), parameter :: comm_help = &
         'The conversion factor can be automatically guessed between known units of&
         &the same kind, eg, K (Tmb) to Jy/beam, or km/s to m/s. Else, the /FACTOR&
         &key allows you to explicitly define a multiplicative conversion factor&
         &between input and output units. The /EFFICIENCIES key allows you to&
         &specify the beam and forward efficiencies required to convert from and &
         &to K (Ta*).'
    character(len=*), parameter :: rname='CONVERT>REGISTER'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubetools_register_command(&
         'CONVERT','[cube]',&
         comm_abstract,&
         comm_help,&
         cubemain_convert_command,&
         convert%comm,error)
    if (error) return
    call cubearg%register(&
         'CUBE',&
         'Input cube',&
         strg_id,&
         code_arg_optional,&
         [flag_cube],&
         error)
    if (error) return
    !
    call cubetools_register_option(&
         'UNIT','name',&
         'Select the desired output unit',&
         strg_id,&
         convert%unit,&
         error)
    if (error) return
    call stdarg%register(&
         'name',&
         'A unit name either known or unknown by the program',&
         strg_id,&
         code_arg_mandatory,&
         error)
    if (error) return
    !
    call cubetools_register_option(&
         'FACTOR','value',&
         'Explicitly define a unit conversion factor',&
         'This key gives the user the ability to do unsupported conversions. The&
         &given value is used as a multiplicative factor over the whole cube and the&
         &new unit is taken to be the unit given with /UNIT key. WARNING: No checks&
         &about the validity of the conversion are performed.',&
         convert%factor,&
         error)
    if (error) return
    call stdarg%register(&
         'value',&
         'Unit conversion factor',&
         strg_id,&
         code_arg_mandatory,&
         error)
    if (error) return
    !
    call cubetools_register_option(&
         'EFFICIENCIES','Beff [Feff]',&
         'Convert to and From K (Ta*)',&
         'Specify the Beam and Forward efficiencies to use when&
         & converting to and from K (Ta*).',&
         convert%efficiencies,&
         error)
    if (error) return
    call stdarg%register(&
         'Beff',&
         'Beam efficiency',&
         strg_id,&
         code_arg_mandatory,&
         error)
    if (error) return
    call stdarg%register(&
         'Feff',&
         'Forward efficiency',&
         strg_id,&
         code_arg_mandatory,&
         error)
    if (error) return
  end subroutine cubemain_convert_register
  !
  !
  subroutine cubemain_convert_parse(convert,line,user,error)
    use cubetools_parse
    !----------------------------------------------------------------------
    ! CONVERT cubname
    !----------------------------------------------------------------------
    class(convert_comm_t), intent(in)    :: convert
    character(len=*),      intent(in)    :: line
    type(convert_user_t),  intent(out)   :: user
    logical,               intent(inout) :: error
    !
    character(len=*), parameter :: rname='CONVERT>PARSE'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_parse(line,convert%comm,user%cubeids,error)
    if (error) return
    call convert%parse_unit(line,user,error)
    if (error) return
    call convert%parse_factor(line,user,error)
    if (error) return
    call convert%parse_efficiencies(line,user,error)
    if (error) return
    if (.not.(user%dounit.or.user%doapplyeff)) then
       call cubemain_message(seve%e,rname,"At least one option must be given")
       error = .true.
       return
    endif
  end subroutine cubemain_convert_parse
  !
  subroutine cubemain_convert_parse_unit(convert,line,user,error)
    !----------------------------------------------------------------------
    ! /UNIT name
    !----------------------------------------------------------------------
    class(convert_comm_t), intent(in)    :: convert
    character(len=*),      intent(in)    :: line
    type(convert_user_t),  intent(inout) :: user
    logical,               intent(inout) :: error
    !
    character(len=*), parameter :: rname='CONVERT>PARSE>UNIT'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call convert%unit%present(line,user%dounit,error)
    if (error) return
    if (user%dounit) then
       call cubetools_getarg(line,convert%unit,1,user%unit,mandatory,error)
       if (error) return
    endif
  end subroutine cubemain_convert_parse_unit
  !
  subroutine cubemain_convert_parse_factor(convert,line,user,error)
    !----------------------------------------------------------------------
    ! /FACTOR value
    !----------------------------------------------------------------------
    class(convert_comm_t), intent(in)    :: convert
    character(len=*),      intent(in)    :: line
    type(convert_user_t),  intent(inout) :: user
    logical,               intent(inout) :: error
    !
    character(len=*), parameter :: rname='CONVERT>PARSE>FACTOR'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call convert%factor%present(line,user%dofactor,error)
    if (error) return
    if (user%dofactor) then
       call cubetools_getarg(line,convert%factor,1,user%factor,mandatory,error)
       if (error) return
    endif
  end subroutine cubemain_convert_parse_factor
  !
  subroutine cubemain_convert_parse_efficiencies(convert,line,user,error)
    !----------------------------------------------------------------------
    ! /EFFICIENCIES beff feff
    !----------------------------------------------------------------------
    class(convert_comm_t), intent(in)    :: convert
    character(len=*),      intent(in)    :: line
    type(convert_user_t),  intent(inout) :: user
    logical,               intent(inout) :: error
    !
    character(len=*), parameter :: rname='CONVERT>PARSE>EFFICIENCIES'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call convert%efficiencies%present(line,user%doapplyeff,error)
    if (error) return
    if (user%doapplyeff) then
       call cubetools_getarg(line,convert%efficiencies,1,user%beff,mandatory,error)
       if (error) return
       call cubetools_getarg(line,convert%efficiencies,2,user%feff,mandatory,error)
       if (error) return
    endif
  end subroutine cubemain_convert_parse_efficiencies
  !
  subroutine cubemain_convert_main(comm,user,error) 
    use cubeadm_timing
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(convert_comm_t), intent(in)    :: comm
    type(convert_user_t),  intent(inout) :: user
    logical,               intent(inout) :: error
    !
    type(convert_prog_t) :: prog
    character(len=*), parameter :: rname='CONVERT>MAIN'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call user%toprog(comm,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_convert_main
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_convert_user_toprog(user,comm,prog,error)
    use cubetools_header_methods
    use cubetools_brightness
    use cubetools_disambiguate
    use cubetools_unit_setup
    use cubetools_unit
    use cubeadm_get
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(convert_user_t), intent(in)    :: user
    type(convert_comm_t),  intent(in)    :: comm 
    type(convert_prog_t),  intent(out)   :: prog
    logical,               intent(inout) :: error
    !
    logical :: converror
    integer(kind=code_k) :: codein,codeou
    character(len=unit_l) :: unitin,unitou
    character(len=mess_l) :: mess
    type(unit_user_t) :: inunit,ouunit
    character(len=*), parameter :: rname='CONVERT>USER>TOPROG'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_cubeid_get_header(comm%comm,icube,user%cubeids,&
         code_access_subset,code_read,prog%incube,error)
    if (error) return
    !
    call cubetools_header_get_array_unit(prog%incube%head,unitin,error)
    if (error) return
    call cubetools_unit_get_code(unitin,codein,error)
    if (error) return
    call cubetools_unit_get_code(user%unit,codeou,error)
    if (error) return
    !
    if (user%dofactor) then
       ! User has given a factor, simple case
       prog%factor = user%factor
       unitou = user%unit
       if (codeou.eq.code_unit_unk) &
            call cubemain_message(seve%w,rname,'Unsupported unit '//trim(user%unit))
    else
       ! Automatic convertion factor 
       converror = .false.
       !
       select case(codein)
       case(code_unit_unk)
          converror = .true.
       case(code_unit_brig)
          if (codeou.eq.code_unit_brig) then
             prog%unit_code = brightness_get(user%unit)  ! NB: user%unit was already tested for invalid names
             unitou = brightness_get(prog%unit_code)
             call cubetools_header_brightness2brightness(prog%incube%head,&
                  user%doapplyeff,user%feff,user%beff,&
                  prog%unit_code,prog%factor,error)
             if (error) return
          else
             converror = .true.
          endif
       case(code_unit_flux)
          if (codeou.eq.code_unit_flux) then
             prog%unit_code = flux_get(user%unit)
             unitou = flux_get(prog%unit_code)
             call cubetools_header_flux2flux(prog%incube%head,prog%unit_code,prog%factor,error)
             if (error) return
          else
             converror = .true.
          endif
       case default
          select case(codein)
          case(code_unit_freq,code_unit_velo,code_unit_wave&
               &,code_unit_pixe,code_unit_chan,code_unit_dist)
             ! Non equivalent units, convertion only possible if kind is
             ! the same
             converror = codein.ne.codeou
          case (code_unit_fov,code_unit_beam)
             ! All unit kinds here are angle units and can hence be
             ! treated together
             converror = .not.(codeou.eq.code_unit_fov.or.codeou.eq.code_unit_beam)
          case default
             call cubemain_message(seve%e,rname,'Programming error')
             error = .true.
             return
          end select
          if (.not.converror) then
             call inunit%get_from_name_for_code(unitin,codein,error)
             if (error) return
             call ouunit%get_from_name_for_code(user%unit,codeou,error)
             if (error) return
             prog%factor = inunit%prog_per_user*ouunit%user_per_prog
             unitou = ouunit%name
          else
             ! Do nothing
          endif
       end select
       !
       if (converror) then
          write(mess,'(8a)') 'Cannot convert from ',trim(unitin),' of kind ',trim(unitkinds(codein)),&
               ' to ',trim(user%unit),' of kind ',trim(unitkinds(codeou))
          call cubemain_message(seve%e,rname,mess)
          error = .true.
          return
       endif
    endif
    !
    ! User feedback
    write(mess,'(5a,1pg14.7)') 'Converting from ',trim(unitin),' to ',trim(unitou),&
         ', factor: ',prog%factor
    call cubemain_message(seve%i,rname,mess)
    prog%unit_name = unitou
  end subroutine cubemain_convert_user_toprog
  !
  !----------------------------------------------------------------------
  !
  subroutine cubemain_convert_prog_header(prog,error)
    use cubetools_header_methods
    use cubedag_allflags
    use cubeadm_clone
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(convert_prog_t), intent(inout) :: prog
    logical,               intent(inout) :: error
    !
    character(len=*), parameter :: rname='CONVERT>PROG>HEADER'
    !
    call cubemain_message(mainseve%trace,rname,'Welcome')
    !
    call cubeadm_clone_header(prog%incube,[flag_convert,flag_cube],prog%converted,error)
    if (error) return
    call cubetools_header_put_array_unit(prog%unit_name,prog%converted%head,error)
    if (error) return
  end subroutine cubemain_convert_prog_header
  !
  subroutine cubemain_convert_prog_data(prog,error)
    use cubeadm_opened
    !----------------------------------------------------------------------
    ! 
    !----------------------------------------------------------------------
    class(convert_prog_t), intent(inout) :: prog
    logical,               intent(inout) :: error
    !
    type(cubeadm_iterator_t) :: itertask
    character(len=*), parameter :: rname='CONVERT>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_convert_prog_data
  !   
  subroutine cubemain_convert_prog_loop(prog,itertask,error)
    use cubeadm_taskloop
    !----------------------------------------------------------------------
    ! The subcube iterator will be shared by all input and output subcubes
    !----------------------------------------------------------------------
    class(convert_prog_t),    intent(inout) :: prog
    type(cubeadm_iterator_t), intent(inout) :: itertask
    logical,                  intent(inout) :: error
    !
    character(len=*), parameter :: rname='CONVERT>PROG>LOOP'
    !
    do while (itertask%iterate_entry(error))
       call prog%act(itertask,error)
       if (error) return
    enddo  ! ientry
  end subroutine cubemain_convert_prog_loop
  !   
  subroutine cubemain_convert_prog_act(prog,itertask,error)
    use cubeadm_taskloop
    use cubeadm_subcube_types
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(convert_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) :: incube,converted
    character(len=*), parameter :: rname='CONVERT>PROG>ACT'
    !
    ! Converts are initialized here as their size (3rd dim) may change from
    ! from one convert to another.
    call incube%associate('incube',prog%incube,itertask,error)
    if (error) return
    call converted%allocate('converted',prog%converted,itertask,error)
    if (error) return
    !
    call incube%get(error)
    if (error) return
    do iz=1,incube%nz
       do iy=1,incube%ny
          do ix=1,incube%nx
             converted%val(ix,iy,iz) = incube%val(ix,iy,iz)*prog%factor
          enddo ! ix
       enddo ! iy
    enddo ! iz
    call converted%put(error)
    if (error) return
  end subroutine cubemain_convert_prog_act
end module cubemain_convert
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
