!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
module cubedag_flag
  use gkernel_interfaces
  use cubetools_parameters
  use cubetools_list
  use cubedag_parameters
  use cubedag_messaging
  !---------------------------------------------------------------------
  ! Support module for flags and list of flags
  !---------------------------------------------------------------------
  !
  ! Flag related symbols
  public :: flag_t
  public :: dag_flagl
  public :: code_flag_technical,code_flag_action,code_flag_product,code_flag_user
  public :: flag_unknown
  public :: cubedag_flag_ptr,cubedag_flag_init,cubedag_flag_register_user
  public :: operator(.eq.),operator(.ne.)
  ! Flaglist related symbols
  public :: flag_list_t
  public :: cubedag_flaglist_sort
  public :: cubedag_flaglist_tostr,cubedag_flaglist_list_all,cubedag_flag_debug
  public :: cubedag_string_toflaglist
  private
  !
  ! Kinds
  integer(kind=code_k), parameter :: nkinds = 4
  character(len=*), parameter :: kinds(nkinds) = ['technic','action ','product','user   ']
  integer(kind=code_k), parameter :: code_flag_technical = 1
  integer(kind=code_k), parameter :: code_flag_action    = 2
  integer(kind=code_k), parameter :: code_flag_product   = 3
  integer(kind=code_k), parameter :: code_flag_user      = 4
  !
  integer(kind=4), parameter :: dag_flagl=24
  character(len=1), parameter :: flagsep_strg=','
  !
  type, extends(tools_object_t) :: flag_t
     character(len=dag_flagl), private :: name
     character(len=dag_flagl), private :: key
     integer(kind=code_k),     private :: kind
     integer(kind=list_k),     private :: id
   contains
     procedure, public :: register   => cubedag_flag_register_program  ! For program-defined flags only
     procedure, public :: list       => cubedag_flag_list
     procedure, public :: get_id     => cubedag_flag_get_id
     procedure, public :: get_name   => cubedag_flag_get_name
     procedure, public :: get_key    => cubedag_flag_get_key
     procedure, public :: get_kind   => cubedag_flag_get_kind
     procedure, public :: get_suffix => cubedag_flag_get_suffix
  end type flag_t
  !
  interface operator(.eq.)  ! Offers syntax e.g. "myflag.eq.flag_any" to programmers
    module procedure cubedag_flag_eq
  end interface
  !
  interface operator(.ne.)  ! Offers syntax e.g. "myflag.ne.flag_any" to programmers
    module procedure cubedag_flag_ne
  end interface
  !
  ! One technical flag
  type(flag_t), target :: flag_unknown
  !
  type, extends(tools_list_t) :: flag_list_t
  contains
    procedure, private :: copy     => cubedag_flaglist_copy
    procedure, public  :: create   => cubedag_flaglist_create
    procedure, public  :: remove   => cubedag_flaglist_remove
    procedure, public  :: prepend  => cubedag_flaglist_prepend
    procedure, public  :: append   => cubedag_flaglist_append
    procedure, public  :: contains => cubedag_flaglist_contains
    procedure, public  :: repr     => cubedag_flaglist_repr
    procedure, public  :: write    => cubedag_flaglist_write
    procedure, public  :: read     => cubedag_flaglist_read
    procedure, public  :: export   => cubedag_flaglist_export
  end type flag_list_t
  !
  integer(kind=4), parameter :: key_l=24  ! Note the T26 tab below
  character(len=*), parameter :: form_na ='(A,T26,I11,(20(1X,A)))'  ! String array
  character(len=*), parameter :: form_nac='(A,T26,I11,A)'           ! String array (decoding)
  !
  ! The global list of flags
  type(tools_list_t) :: flag_list
  integer(kind=list_k), allocatable :: flag_list_sort(:)
  !
contains
  !
  !---------------------------------------------------------------------
  ! Support for scalar flags
  !---------------------------------------------------------------------
  !
  subroutine cubedag_flag_init(error)
    !-------------------------------------------------------------------
    ! Register the technical flags
    !-------------------------------------------------------------------
    logical, intent(inout) :: error
    !
    call flag_unknown%register('unknown',code_flag_technical,error)
    if (error) return
    !
    call cubedag_flaglist_sort(error)  ! Compute the sorting array
    if (error)  return
  end subroutine cubedag_flag_init
  !
  subroutine cubedag_flag_list(flag,error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(flag_t), target, intent(inout) :: flag
    logical,               intent(inout) :: error
    !
    character(mess_l) :: mess
    !
    write(mess,'(2x,a,i4,2x,3(2a,2x))')  &
      'id=',  flag%id, &
      'name=',flag%name, &
      'key=', flag%key, &
      'kind=',kinds(flag%kind)
    call cubedag_message(seve%r,'FLAG>LIST',mess)
  end subroutine cubedag_flag_list
  !
  function cubedag_flag_get_id(flag) result(id)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(flag_t), intent(in) :: flag
    integer(kind=list_k)      :: id
    !
    id = flag%id
  end function cubedag_flag_get_id
  !
  function cubedag_flag_get_name(flag) result(name)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(flag_t), intent(in) :: flag
    character(len=dag_flagl)  :: name
    !
    name = flag%name
  end function cubedag_flag_get_name
  !
  function cubedag_flag_get_key(flag) result(key)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(flag_t), intent(in) :: flag
    character(len=dag_flagl)  :: key
    !
    key = flag%key
  end function cubedag_flag_get_key
  !
  function cubedag_flag_get_kind(flag) result(kind)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(flag_t), intent(in) :: flag
    integer(kind=code_k)      :: kind
    !
    kind = flag%kind
  end function cubedag_flag_get_kind
  !
  function cubedag_flag_get_suffix(flag) result(suffix)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    class(flag_t), intent(in)  :: flag
    character(len=dag_flagl+1) :: suffix
    !
    suffix = '-'//flag%name
  end function cubedag_flag_get_suffix
  !
  function cubedag_flag_eq(flag1,flag2)
    logical :: cubedag_flag_eq
    type(flag_t), intent(in) :: flag1,flag2
    cubedag_flag_eq = flag1%id.eq.flag2%id
  end function cubedag_flag_eq
  !
  function cubedag_flag_ne(flag1,flag2)
    logical :: cubedag_flag_ne
    type(flag_t), intent(in) :: flag1,flag2
    cubedag_flag_ne = flag1%id.ne.flag2%id
  end function cubedag_flag_ne
  !
  function cubedag_flag_ptr(tot,error)
    !-------------------------------------------------------------------
    ! Check if the input class is of type(flag_t), and return a
    ! pointer to it if relevant.
    !-------------------------------------------------------------------
    type(flag_t), pointer :: cubedag_flag_ptr
    class(tools_object_t), pointer       :: tot
    logical,               intent(inout) :: error
    !
    character(len=*), parameter :: rname='FLAG>PTR'
    !
    select type(tot)
    type is (flag_t)
      cubedag_flag_ptr => tot
    class default
      cubedag_flag_ptr => null()
      call cubedag_message(seve%e,rname,  &
        'Internal error: object is not a flag_t type')
      error = .true.
      return
    end select
  end function cubedag_flag_ptr
  !
  subroutine cubedag_flag_name2flag(name,found,flag)
    use gkernel_interfaces
    !-------------------------------------------------------------------
    ! Resolve the flag given its name. Raising an error or not is the
    ! responsibility of the caller.
    !-------------------------------------------------------------------
    character(len=*), intent(in)  :: name
    logical,          intent(out) :: found
    type(flag_t),     intent(out) :: flag
    ! Local
    character(len=dag_flagl) :: lname
    integer(kind=list_k) :: iflag
    type(flag_t), pointer :: lflag
    logical :: error
    !
    lname = name
    call sic_lower(lname)
    found = .false.
    flag = flag_unknown
    error = .false.
    !
    if (flag_list%n.le.0)  return
    !
    if (flag_list_gt(1_list_k) .or. flag_list_lt(flag_list%n)) then
      ! The name we are looking for is before the 1st sorted flag, or
      ! after the last sorted flag: no need for dichotomic search (which
      ! would complain anyway in this case)
      return
    endif
    !
    call gi0_dicho_with_user_ltgt(flag_list%n,.true.,iflag,  &
      flag_list_lt,flag_list_gt,error)
    if (error)  return
    ! In return jflag is the flag lower or equal to the request
    ! in the sorted array (flag_list_sort)
    !
    lflag => cubedag_flag_ptr(flag_list%list(flag_list_sort(iflag))%p,error)
    if (error)  return
    if (lflag%name.eq.lname) then
      found = .true.
      flag = lflag
    endif
    !
  contains
    function flag_list_lt(m)
      logical :: flag_list_lt
      integer(kind=list_k), intent(in) :: m
      ! 'lname', 'flag', and 'error' shared with main routine
      lflag => cubedag_flag_ptr(flag_list%list(flag_list_sort(m))%p,error)
      if (error)  return
      flag_list_lt = flag_name_lt(lflag%name,lname)
    end function flag_list_lt
    function flag_list_gt(m)
      logical :: flag_list_gt
      integer(kind=list_k), intent(in) :: m
      ! 'lname', 'flag', and 'error' shared with main routine
      lflag => cubedag_flag_ptr(flag_list%list(flag_list_sort(m))%p,error)
      if (error)  return
      flag_list_gt = flag_name_gt(lflag%name,lname)
    end function flag_list_gt
  end subroutine cubedag_flag_name2flag
  !
  function flag_name_gt(name1,name2)
    !-------------------------------------------------------------------
    ! Compare 2 flag names, i.e. if name1 > name2
    ! Typically used for lexicographical sorting
    !-------------------------------------------------------------------
    logical :: flag_name_gt
    character(len=*), intent(in) :: name1
    character(len=*), intent(in) :: name2
    ! Local
    integer(kind=4) :: len1,len2
    !
    if (isnumeric(name1(1:1)) .and. isnumeric(name2(1:1))) then
      ! Compare numerics as character strings, ensuring "2" < "10".
      ! NB: this won't work if mixing numerics and letters e.g. "123ABC",
      ! but what do we want in this case?
      len1 = len_trim(name1)
      len2 = len_trim(name2)
      if (len1.gt.len2) then
        flag_name_gt = .true.
      elseif (len1.lt.len2) then
        flag_name_gt = .false.
      else
        flag_name_gt = lgt(name1,name2)
      endif
    else
      flag_name_gt = lgt(name1,name2)
    endif
  end function flag_name_gt
  !
  function flag_name_lt(name1,name2)
    !-------------------------------------------------------------------
    ! Compare 2 flag names, i.e. if name1 < name2
    ! Typically used for lexicographical sorting
    !-------------------------------------------------------------------
    logical :: flag_name_lt
    character(len=*), intent(in) :: name1
    character(len=*), intent(in) :: name2
    ! Local
    integer(kind=4) :: len1,len2
    !
    if (isnumeric(name1(1:1)) .and. isnumeric(name2(1:1))) then
      ! Compare numerics as character strings, ensuring "2" < "10".
      ! NB: this won't work if mixing numerics and letters e.g. "123ABC",
      ! but what do we want in this case?
      len1 = len_trim(name1)
      len2 = len_trim(name2)
      if (len1.gt.len2) then
        flag_name_lt = .false.
      elseif (len1.lt.len2) then
        flag_name_lt = .true.
      else
        flag_name_lt = llt(name1,name2)
      endif
    else
      flag_name_lt = llt(name1,name2)
    endif
  end function flag_name_lt
  !
  function flag_name_ge(name1,name2)
    !-------------------------------------------------------------------
    ! Compare 2 flag names, i.e. if name1 >= name2
    ! Typically used for lexicographical sorting
    !-------------------------------------------------------------------
    logical :: flag_name_ge
    character(len=*), intent(in) :: name1
    character(len=*), intent(in) :: name2
    !
    flag_name_ge = .not.flag_name_lt(name1,name2)
  end function flag_name_ge
  !
  function isnumeric(c1)
    !-------------------------------------------------------------------
    ! Return .true. if the given character is an ASCII character in the
    ! range [0-9]
    !-------------------------------------------------------------------
    logical :: isnumeric
    character(len=1), intent(in) :: c1
    ! Local
    integer(kind=4) :: ichara
    !
    ichara = ichar(c1)-ichar('0')
    isnumeric = ichara.ge.0 .and. ichara.le.9
  end function isnumeric
  !
  !---------------------------------------------------------------------
  ! Support for list of flags
  !---------------------------------------------------------------------
  !
  subroutine cubedag_flag_register_program(flag,name,kind,error)
    !----------------------------------------------------------------------
    ! Register a program-defined flag in the global flag list
    !----------------------------------------------------------------------
    class(flag_t), target, intent(inout) :: flag
    character(len=*),      intent(in)    :: name
    integer(kind=code_k),  intent(in)    :: kind
    logical,               intent(inout) :: error
    !
    call cubedag_flag_register(flag,name,kind,error)
    if (error)  return
    ! Sorting is done once by caller
  end subroutine cubedag_flag_register_program
  !
  subroutine cubedag_flag_register_user(name,error)
    !----------------------------------------------------------------------
    ! Create and register a user-defined flag in the global flag list
    !----------------------------------------------------------------------
    character(len=*), intent(in)    :: name
    logical,          intent(inout) :: error
    !
    type(flag_t) :: otherflag
    logical :: found
    type(flag_t), pointer :: flag
    character(len=*), parameter :: rname='FLAG>REGISTER>USER'
    !
    ! Sanity (only checked for user inputs)
    if (len_trim(name).gt.dag_flagl) then
      call cubedag_message(seve%e,rname,'Flag name is too long')
      error = .true.
      return
    endif
    call cubedag_flag_name2flag(name,found,otherflag)
    if (found) then
      call cubedag_message(seve%w,rname,'Flag named '''//trim(name)//''' already exists')
      return
    endif
    !
    allocate(flag)
    call cubedag_flag_register(flag,name,code_flag_user,error)
    if (error) then
      deallocate(flag)
      return
    endif
    call cubedag_flaglist_sort(error)  ! Compute the sorting array
    if (error)  return
  end subroutine cubedag_flag_register_user
  !
  subroutine cubedag_flag_register(flag,name,kind,error)
    use gkernel_interfaces
    !----------------------------------------------------------------------
    ! Register a flag in the global flag list
    !----------------------------------------------------------------------
    class(flag_t), target, intent(inout) :: flag
    character(len=*),      intent(in)    :: name
    integer(kind=code_k),  intent(in)    :: kind
    logical,               intent(inout) :: error
    !
    ! Attributes
    flag%name = name
    call sic_lower(flag%name)
    flag%key = name
    call sic_upper(flag%key)
    flag%kind = kind
    flag%id = flag_list%n+1
    !
    ! Inser in global flag list
    call flag_list%realloc(flag%id,error)
    if (error)  return
    call flag_list%list(flag%id)%associate(flag,error)
    if (error)  return
    flag_list%n = flag%id  ! Only when everything ok
  end subroutine cubedag_flag_register
  !
  subroutine cubedag_flaglist_copy(list,flags,start,error)
    !-------------------------------------------------------------------
    ! Copy an array of flag_t to a tools_list_t, starting at given
    ! position.
    ! This subroutine DOES NOT CARE for list allocation or list%n.
    ! Because of this, it should not be used out of this module.
    !-------------------------------------------------------------------
    class(flag_list_t),   intent(inout) :: list
    type(flag_t),         intent(in)    :: flags(:)
    integer(kind=list_k), intent(in)    :: start
    logical,              intent(inout) :: error
    !
    character(len=*), parameter :: rname='FLAGLIST>COPY'
    integer(kind=list_k) :: iflag,oflag
    type(flag_t), pointer :: flag
    type(flag_t) :: template
    !
    do iflag=1,size(flags)
      oflag = start+iflag-1  ! Position in list
      call list%list(oflag)%allocate(template,error)
      if (error)  return
      flag => cubedag_flag_ptr(list%list(oflag)%p,error)
      if (error)  return
      flag = flags(iflag)
    enddo
  end subroutine cubedag_flaglist_copy
  !
  subroutine cubedag_flaglist_create(list,flags,error)
    !-------------------------------------------------------------------
    ! Create a tools_list_t of flag_t from an array of flag_t
    ! This creates copies of the flags. The list MUST be cleaned with
    ! the list%free() method.
    !-------------------------------------------------------------------
    class(flag_list_t), intent(inout) :: list
    type(flag_t),       intent(in)    :: flags(:)
    logical,            intent(inout) :: error
    !
    character(len=*), parameter :: rname='FLAGLIST>CREATE'
    integer(kind=list_k) :: nflag
    !
    nflag = size(flags)
    call list%realloc(nflag,error)
    if (error)  return
    !
    call list%copy(flags,1_list_k,error)
    if (error)  return
    !
    list%n = nflag
  end subroutine cubedag_flaglist_create
  !
  subroutine cubedag_flaglist_remove(list,flags,error)
    !-------------------------------------------------------------------
    ! Free and pop the matching flags from a flag_list_t
    !-------------------------------------------------------------------
    class(flag_list_t), intent(inout) :: list
    type(flag_t),       intent(in)    :: flags(:)
    logical,            intent(inout) :: error
    !
    character(len=*), parameter :: rname='FLAGLIST>REMOVE'
    integer(kind=list_k) :: iflag,jflag
    type(flag_t), pointer :: flag
    !
    ! Start from the end because list%pop() compresses the list from the
    ! right and changes list%n
    iflag = list%n
    do while (iflag.ge.1)
      flag => cubedag_flag_ptr(list%list(iflag)%p,error)
      if (error)  return
      do jflag=1,size(flags)  ! This is a N^2 loop... on small numbers (<10 or so).
        if (flag.eq.flags(jflag)) then
          call list%pop(iflag,error)
          if (error)  return
          exit  ! Matched and removed from the list, go to next iflag in the list
        endif
      enddo
      iflag = iflag-1
    enddo
  end subroutine cubedag_flaglist_remove
  !
  subroutine cubedag_flaglist_prepend(list,flags,error)
    !-------------------------------------------------------------------
    ! Prepend a list of flags to a flag_list_t. Note that duplicates
    ! are allowed.
    !-------------------------------------------------------------------
    class(flag_list_t), intent(inout) :: list
    type(flag_t),       intent(in)    :: flags(:)
    logical,            intent(inout) :: error
    !
    ! Enlarge list to the left
    call list%enlarge(size(flags,kind=list_k),1_list_k,error)
    if (error)  return
    !
    ! Insert new ones in front
    call list%copy(flags,1_list_k,error)
    if (error)  return
    !
    ! Finally update the size
    list%n = list%n+size(flags)
  end subroutine cubedag_flaglist_prepend
  !
  subroutine cubedag_flaglist_append(list,flags,error)
    !-------------------------------------------------------------------
    ! Append a list of flags to a flag_list_t. Note that duplicates are
    ! allowed.
    !-------------------------------------------------------------------
    class(flag_list_t), intent(inout) :: list
    type(flag_t),       intent(in)    :: flags(:)
    logical,            intent(inout) :: error
    !
    ! Enlarge list to the right
    call list%enlarge(size(flags,kind=list_k),list%n+1,error)
    if (error)  return
    !
    ! Insert new ones to the end
    call list%copy(flags,list%n+1,error)
    if (error)  return
    !
    ! Finally update the size
    list%n = list%n+size(flags)
  end subroutine cubedag_flaglist_append
  !
  function cubedag_flaglist_contains(list,flag)
    !-------------------------------------------------------------------
    ! Return .true. if the flag_list_t contains the named flag.
    !-------------------------------------------------------------------
    logical :: cubedag_flaglist_contains
    class(flag_list_t), intent(in) :: list
    type(flag_t),       intent(in) :: flag
    ! Local
    logical :: error
    integer(kind=4) :: iflag
    type(flag_t), pointer :: pflag
    !
    error = .false.
    cubedag_flaglist_contains = .false.
    do iflag=1,list%n
      pflag => cubedag_flag_ptr(list%list(iflag)%p,error)
      if (error)  return
      if (pflag.eq.flag) then
        cubedag_flaglist_contains = .true.
        return
      endif
    enddo
  end function cubedag_flaglist_contains
  !
  subroutine cubedag_flaglist_tostr(flags,nflag,strflag,lstrflag,error)
    !-------------------------------------------------------------------
    ! Concatenate the flags list into a string.
    ! ---
    ! This version with a flat 'flag_t' array as argument
    !-------------------------------------------------------------------
    type(flag_t),               intent(in)    :: flags(:)
    integer(kind=4),            intent(in)    :: nflag
    character(len=*), optional, intent(out)   :: strflag
    integer(kind=4),  optional, intent(out)   :: lstrflag
    logical,                    intent(inout) :: error
    ! Local
    type(flag_list_t) :: tmp
    !
    call tmp%create(flags(1:nflag),error)
    if (error)  return
    call tmp%repr(strflag=strflag,lstrflag=lstrflag,error=error)
    if (error)  return
    call tmp%free(error)
    if (error)  return
  end subroutine cubedag_flaglist_tostr
  !
  subroutine cubedag_flaglist_repr(list,strflag,lstrflag,error)
    !-------------------------------------------------------------------
    ! Concatenate the flags list into a string. This subroutine can be
    ! used to:
    !   1) concatenate the flags into an output list
    ! AND/OR
    !   2) return the length of the concatenatation
    ! ---
    ! This version with a tools_list_t as argument
    !-------------------------------------------------------------------
    class(flag_list_t),         intent(in)    :: list
    character(len=*), optional, intent(out)   :: strflag
    integer(kind=4),  optional, intent(out)   :: lstrflag
    logical,          optional, intent(inout) :: error
    ! Local
    integer(kind=4) :: iflag,nc,mc
    type(flag_t), pointer :: flag
    !
    if (list%n.le.0) then
      if (present(strflag))   strflag = ''
      if (present(lstrflag))  lstrflag = 0
      return
    endif
    !
    nc = 0
    if (present(strflag)) then
      mc = len(strflag)
    else
      mc = huge(mc)
    endif
    do iflag=1,list%n
      if (nc.gt.0) then
        nc = nc+1
        if (present(strflag)) strflag(nc:nc) = flagsep_strg
      endif
      flag => cubedag_flag_ptr(list%list(iflag)%p,error)
      if (error)  return
      ! ZZZ There used to be a specific support for flag_any
      if (present(strflag)) strflag(nc+1:mc) = flag%name
      nc = nc+len_trim(flag%name)
      if (nc.gt.mc) then
        if (present(strflag)) strflag(mc-1:mc) = '..'
        nc = mc
        exit
      endif
    enddo
    !
    if (present(lstrflag))  lstrflag = nc
    !
  end subroutine cubedag_flaglist_repr
  !
  subroutine cubedag_string_toflaglist(string,allownew,flags,error,sep)
    use gkernel_interfaces
    !----------------------------------------------------------------------
    ! Parse a string (e.g. "flag1,flag2,flag3") into a list of flags
    !----------------------------------------------------------------------
    character(len=*),           intent(in)    :: string
    logical,                    intent(in)    :: allownew  ! Allow creation of new (user-defined) flags?
    type(flag_t), allocatable,  intent(out)   :: flags(:)
    logical,                    intent(inout) :: error
    character(len=*), optional, intent(in)    :: sep       ! Override default separator
    !
    integer(kind=list_k) :: nflag,iflag
    integer(kind=4) :: ichar,seppos(20),ierr
    character(len=1) :: lsep
    character(len=argu_l) :: oneflag
    character(len=mess_l) :: mess
    logical :: found,lerror
    character(len=*), parameter :: rname='STRING>TOFLAGLIST'
    !
    ! call cubedag_message(dagseve%trace,rname,'Welcome')
    !
    if (len_trim(string).eq.0) then ! No flags given return
      return
    endif
    !
    if (present(sep)) then
      lsep = sep
    else
      lsep = flagsep_strg
    endif
    !
    nflag = 0
    seppos(:) = -1
    seppos(1) = 0
    do ichar=1,len_trim(string)
      if (string(ichar:ichar).eq.lsep) then
        nflag = nflag+1
        seppos(nflag+1) = ichar
      endif
    enddo
    nflag = nflag+1
    seppos(nflag+1) = len_trim(string)+1
    !
    lerror = .false.
    allocate(flags(nflag),stat=ierr)
    if (failed_allocate(rname,'flags',ierr,error)) return
    do iflag=1,nflag
      oneflag = string(seppos(iflag)+1:seppos(iflag+1)-1)
      if (oneflag.eq.'') then
        write(mess,'(3(a,i0))') 'Flag ',iflag,'/',nflag,' is empty'
        call cubedag_message(seve%e,rname,mess)
        lerror = .true.
        cycle
      endif
      call cubedag_flag_name2flag(oneflag,found,flags(iflag))
      if (.not.found) then
        if (allownew) then
          call cubedag_flag_register_user(oneflag,error)
          if (error)  return
          call cubedag_flag_name2flag(oneflag,found,flags(iflag))
        else
          write(mess,'(3a)') 'Flag "',trim(oneflag),'" not recognized'
          call cubedag_message(seve%e,rname,mess)
          lerror = .true.
          cycle
        endif
      endif
    enddo
    if (lerror) then
      call cubedag_message(seve%e,rname,'Undecipherable flag list: "'//trim(string)//'"')
      error = .true.
      return
    endif
  end subroutine cubedag_string_toflaglist
  !
  subroutine cubedag_flag_debug(error)
    !-------------------------------------------------------------------
    ! Display the full list of flags registered
    !-------------------------------------------------------------------
    logical, intent(inout) :: error
    ! Local
    integer(kind=list_k) :: iflag
    type(flag_t), pointer :: flag
    !
    do iflag=1,flag_list%n
      flag => cubedag_flag_ptr(flag_list%list(iflag)%p,error)
      if (error) return
      call flag%list(error)
      if (error) return
    enddo
  end subroutine cubedag_flag_debug
  !
  subroutine cubedag_flaglist_sort(error)
    !-------------------------------------------------------------------
    ! Compute the sorting array of the flag list (by alphabetical order
    ! of names)
    !-------------------------------------------------------------------
    logical, intent(inout) :: error
    ! Local
    character(len=*), parameter :: rname='FLAGLIST>SORT'
    integer(kind=list_k) :: iflag
    integer(kind=4) :: ier
    !
    if (allocated(flag_list_sort))  deallocate(flag_list_sort)
    allocate(flag_list_sort(flag_list%n),stat=ier)
    if (failed_allocate(rname,'flag_list_sort',ier,error)) return
    do iflag=1,flag_list%n
      flag_list_sort(iflag) = iflag
    enddo
    !
    call gi0_quicksort_index_with_user_gtge(flag_list_sort,flag_list%n,  &
      flag_list_sort_gt,flag_list_sort_ge,error)
    if (error)  return
  end subroutine cubedag_flaglist_sort
  !
  function flag_list_sort_gt(m,l)
    logical :: flag_list_sort_gt
    integer(kind=list_k), intent(in) :: m,l
    ! Local
    logical :: error
    type(flag_t), pointer :: flagm,flagl
    !
    error = .false.
    flagm => cubedag_flag_ptr(flag_list%list(m)%p,error)
    if (error)  return
    flagl => cubedag_flag_ptr(flag_list%list(l)%p,error)
    if (error)  return
    flag_list_sort_gt = flag_name_gt(flagm%name,flagl%name)
  end function flag_list_sort_gt
  !
  function flag_list_sort_ge(m,l)
    logical :: flag_list_sort_ge
    integer(kind=list_k), intent(in) :: m,l
    ! Local
    logical :: error
    type(flag_t), pointer :: flagm,flagl
    !
    error = .false.
    flagm => cubedag_flag_ptr(flag_list%list(m)%p,error)
    if (error)  return
    flagl => cubedag_flag_ptr(flag_list%list(l)%p,error)
    if (error)  return
    flag_list_sort_ge = flag_name_ge(flagm%name,flagl%name)
  end function flag_list_sort_ge
  !
  subroutine cubedag_flaglist_list_all(error)
    !----------------------------------------------------------------------
    !
    !----------------------------------------------------------------------
    logical, intent(inout) :: error
    !
    integer(kind=list_k) :: iflag
    integer(kind=4) :: nlp,nla,nlu
    type(flag_t), pointer :: pflag
    character(len=2048) :: products,actions,users
    !
    character(len=*), parameter :: rname='FLAGLIST>LIST>ALL'
    !
    ! call cubedag_message(dagseve%trace,rname,'Welcome')
    !
    products = ''
    actions  = ''
    users    = ''
    nlp = 0
    nla = 0
    nlu = 0
    do iflag=1,flag_list%n
       pflag => cubedag_flag_ptr(flag_list%list(flag_list_sort(iflag))%p,error)
       if (error) return
       select case(pflag%kind)
       case(code_flag_product)
          call format_line_break(pflag%key,products,nlp)
       case(code_flag_action)
          call format_line_break(pflag%key,actions,nla)
       case(code_flag_user)
          call format_line_break(pflag%key,users,nlu)
       case default
          ! Do nothing
       end select
    enddo
    call cubedag_message(seve%r,rname,'Product flags:')
    call cubedag_message(seve%r,rname,products(1:len_trim(products)-1))
    call cubedag_message(seve%r,rname,blankstr)
    call cubedag_message(seve%r,rname,'Action flags:')    
    call cubedag_message(seve%r,rname,actions(1:len_trim(actions)-1))
    call cubedag_message(seve%r,rname,blankstr)
    call cubedag_message(seve%r,rname,'User flags:')
    call cubedag_message(seve%r,rname,users(1:len_trim(users)-1))
  contains
    subroutine format_line_break(key,line,nl)
      use cubetools_terminal_tool
      !----------------------------------------------------------------------
      !
      !----------------------------------------------------------------------
      character(len=*), intent(in)    :: key
      character(len=*), intent(inout) :: line
      integer(kind=4),  intent(inout) :: nl
      !
      integer(kind=4) :: nc
      character(len=*), parameter :: sep = ','
      !
      nc = len_trim(key)
      if (nl+nc+2.gt.terminal%width()) then
         write(line,'(2a)') trim(line),strg_cr
         nl = 0
      endif
      write(line,'(a,x,2a)') trim(line),trim(key),sep
      nl = nl+nc+2
    end subroutine format_line_break
  end subroutine cubedag_flaglist_list_all

  subroutine cubedag_flaglist_write(fl,lun,error)
    !-------------------------------------------------------------------
    !
    !-------------------------------------------------------------------
    class(flag_list_t), intent(in)    :: fl
    integer(kind=4),    intent(in)    :: lun
    logical,            intent(inout) :: error
    !
    integer(kind=4) :: iflag,nc
    character(len=dag_flagl), allocatable :: lflags(:)
    character(len=*), parameter :: rname='FLAGLIST>WRITE'
    !
    ! Flags
    call fl%export(lflags,error)
    if (error)  return
    ! Cosmetics: find the smallest length needed
    nc = 0
    do iflag=1,fl%n
      nc = max(nc,len_trim(lflags(iflag)))
    enddo
    write(lun,form_na) 'FLAG',fl%n,(/ (lflags(iflag)(1:nc),iflag=1,fl%n) /)
  end subroutine cubedag_flaglist_write

  subroutine cubedag_flaglist_export(fl,flags,error)
    !-------------------------------------------------------------------
    ! Export the flag list to character array
    !-------------------------------------------------------------------
    class(flag_list_t), intent(in)    :: fl
    character(len=*),   allocatable   :: flags(:)
    logical,            intent(inout) :: error
    !
    integer(kind=4) :: iflag,ier
    type(flag_t), pointer :: flag
    character(len=*), parameter :: rname='FLAGLIST>EXPORT'
    !
    allocate(flags(fl%n),stat=ier)
    if (failed_allocate(rname,'flags',ier,error)) return
    do iflag=1,fl%n
      flag => cubedag_flag_ptr(fl%list(iflag)%p,error)
      if (error)  return
      flags(iflag) = flag%get_name()
    enddo
  end subroutine cubedag_flaglist_export

  subroutine cubedag_flaglist_read(fl,lun,error)
    class(flag_list_t), intent(inout) :: fl
    integer(kind=4),   intent(in)    :: lun
    logical,           intent(inout) :: error
    ! Local
    character(len=*), parameter :: rname='FLAGLIST>READ'
    character(len=dag_flagl) :: chflags(dag_mflags)
    integer(kind=4) :: nflag,iflag
    type(flag_t), pointer :: flag
    type(flag_t) :: template
    logical :: found
    !
    call cubedag_read_nch(lun,nflag,chflags,error)
    if (error)  return
    call fl%realloc(nflag,error)
    if (error)  return
    ! Resolving codes from names below is inefficient. Solutions:
    !  1) Sort the main list, and use dichotomic search, OR
    !  2) Get rid of the integer codes (as we want flexibility
    !     e.g. user-defined flags)
    do iflag=1,nflag
      call fl%list(iflag)%allocate(template,error)
      if (error)  return
      flag => cubedag_flag_ptr(fl%list(iflag)%p,error)
      if (error)  return
      call cubedag_flag_name2flag(chflags(iflag),found,flag)
      if (.not.found) then
        ! Implicitly recreate a user-defined flag in the main list
        call cubedag_flag_register_user(chflags(iflag),error)
        if (error)  return
        ! And search for it again. Not efficient but robust.
        call cubedag_flag_name2flag(chflags(iflag),found,flag)
      endif
    enddo
    fl%n = nflag
  end subroutine cubedag_flaglist_read

  subroutine cubedag_read_nch(lun,nch,ch,error)
    !-------------------------------------------------------------------
    !-------------------------------------------------------------------
    integer(kind=4),  intent(in)    :: lun
    integer(kind=4),  intent(out)   :: nch
    character(len=*), intent(out)   :: ch(:)
    logical,          intent(inout) :: error
    ! Local
    character(len=key_l) :: key
    character(len=128) :: tmp
    !
    read(lun,form_nac) key,nch,tmp
    if (nch.gt.0) then
      read(tmp,*)  ch(1:nch)
    endif
  end subroutine cubedag_read_nch

end module cubedag_flag
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
