!-----------------------------------------------------------------------
!
!     utilities.f90
!
!     Utilities for handling strings and input parameters
!
!-----------------------------------------------------------------------


module utilities


contains


!=======================================================================
!
!  integer function  indlnb(s)
!
!  I: s                 character string
!
!  O: indlnb            integer
!
!     Returns index of last non-blank character in S.
!     (This routine written by Matthew Choptuik.)
!
!=======================================================================

function indlnb(s)
  character(*) :: s
  integer :: indlnb
  do indlnb = len(s) , 1 , -1
    if( s(indlnb:indlnb) .ne. ' ' ) return
  end do
  indlnb = 0
end function indlnb


!=======================================================================
!
!  integer function  indfnb(s)
!
!  I: s                 character string
!
!  O: indfnb            integer
!
!     Returns index of first non-blank character in S.
!     (Based on routine written by Matthew Choptuik.)
!
!=======================================================================

function indfnb(s)
  character(*) :: s
  integer :: indfnb
  do indfnb = 1, len(s) , 1
    if( s(indfnb:indfnb) .ne. ' ' ) return
  end do
  indfnb = 0
end function indfnb


!=======================================================================
!
!  integer function  s2i 4(s)
!
!  I: s             character string
!
!  O: s2i           integer
!
!     Converts string to integer.
!     (This routine written by Matthew Choptuik.)
!
!=======================================================================

function s2i(s)

   implicit none

   character(*) :: s     
   integer :: s2i


   real*8, parameter :: r8_never = -1.0d-60
   integer, parameter :: i4_never  = -2000000000

   character(32) ::  buffer
   integer :: lens

   integer, parameter :: default = 0

   lens = indlnb(s)
   if( lens .gt. 99 ) then
      write(0,*) '>>> s2i :: String too long for conversion.'
      s2i = default
   else 
     if( lens .le. 9 ) then
       write(buffer,100) lens
     else 
       write(buffer,101) lens
     end if
100  format('(I',i1,')')
101  format('(I',i2,')')
     read(s,fmt=buffer,end=900,err=900) s2i
   end if

   return

900 s2i = i4_never
    return

end function s2i


end module utilities
