!> @file string_utils.f90
!> @brief Small, dependency-free ASCII string helpers.
!!
!! Leaf module (no `use` dependencies) holding the ASCII case helpers that were
!! previously copy-defined in `config`, `config_2d`, and `config_schema`.  Two
!! variants are kept deliberately:
!!
!!   * `to_lower`        — lowercase only, preserving length and surrounding
!!                         whitespace.
!!   * `lowercase_token` — left-justify + trim, then lowercase (token
!!                         normalisation for namelist values and schema keys).

module string_utils
  implicit none
  private

  public :: to_lower, lowercase_token

contains

  !> Return a lowercased copy of an ASCII string, preserving length and whitespace.
  pure function to_lower(s) result(t)
    character(len=*), intent(in) :: s
    character(len=len(s)) :: t
    integer :: i, ic

    t = s
    do i = 1, len(s)
      ic = iachar(s(i:i))
      if (ic >= iachar('A') .and. ic <= iachar('Z')) t(i:i) = achar(ic + 32)
    end do
  end function to_lower

  !> Return a left-justified, trimmed, lowercased copy of `value`.
  !! Pure: has no side effects (usable inside other pure procedures).
  pure function lowercase_token(value) result(normalized)
    character(len=*), intent(in) :: value
    character(len=len(value)) :: normalized
    integer :: i, code

    normalized = adjustl(trim(value))
    do i = 1, len_trim(normalized)
      code = iachar(normalized(i:i))
      if (code >= iachar('A') .and. code <= iachar('Z')) then
        normalized(i:i) = achar(code + 32)
      end if
    end do
  end function lowercase_token

end module string_utils
