module cubetools_cubeid_types
  use cubetools_parameters
  use cubeheader_messaging
  use cubetools_flag_types
  !---------------------------------------------------------------------
  ! Support module for CubeID strings, i.e. family:flag1,flag2,...
  !---------------------------------------------------------------------
  !
  public :: cubeid_separ
  public :: cubetools_cubeid_string2familyflags
  public :: cubetools_cubeid_familyflags2string
  private
  !
  character(len=1), parameter :: cubeid_separ=':'  ! Family/flags separator
  !
  ! As of today there is no specific type defined for CubeID
  !
contains
  !
  subroutine cubetools_cubeid_string2familyflags(string,family,flags,error)
    !-------------------------------------------------------------------
    ! Transform a string into family name + list of flag_t
    !-------------------------------------------------------------------
    character(len=*),          intent(in)    :: string
    character(len=*),          intent(out)   :: family
    type(flag_t), allocatable, intent(out)   :: flags(:)
    logical,                   intent(inout) :: error
    !
    integer(kind=4) :: sep
    character(len=argu_l) :: stflags
    character(len=*), parameter :: rname='CUBEID>STRING2FAMILYFLAGS'
    !
    call cubeheader_message(headseve%trace,rname,'Welcome')
    !
    sep = index(string,cubeid_separ)
    if (sep.eq.0) sep = len_trim(string)+1  ! No flags
    if (sep.eq.1) then
      call cubeheader_message(seve%e,rname,'Family name is empty')
      error =.true.
      return
    endif
    !
    family  = string(1:sep-1)
    stflags = string(sep+1:)
    !
    call cubetools_string_toflaglist(stflags,.false.,flags,error)
    if (error) return
  end subroutine cubetools_cubeid_string2familyflags
  !
  subroutine cubetools_cubeid_familyflags2string(family,flags,string,error)
    !-------------------------------------------------------------------
    ! From family name and flag codes, build the CubeID string
    !-------------------------------------------------------------------
    character(len=*), intent(in)    :: family
    type(flag_t),     intent(in)    :: flags(:)
    character(len=*), intent(out)   :: string
    logical,          intent(inout) :: error
    !
    call cubetools_flaglist_tostr(flags,size(flags,kind=flag_k),strflag=string,error=error)
    if (error) return
    string = trim(family)//cubeid_separ//string
  end subroutine cubetools_cubeid_familyflags2string
end module cubetools_cubeid_types
