! This function compares two strings 
! Input, 5 variables out of which 3 optionals
! Line: the line to search in
! String: the stuff to search in Line
! Case [optional]: if present and true, the case is respected
! Clean [optional]: if present, Line is cleaned 
! Back [optional] if present and true, the string is seach backwards

    FUNCTION InString(Line,String,Case,Clean,Back)  Result(Pos)

      Use VarTypes
      Use io_module

      implicit none


  INTERFACE
     function valid(string) result (isValid)
       CHARACTER(*), intent(in) :: string
       logical                  :: isValid
     END function VALID
  END INTERFACE

! Input
      CHARACTER(*), INTENT(IN) :: Line
      CHARACTER(*), INTENT(IN) :: String
      LOGICAL, OPTIONAL, INTENT(IN) :: Case
      LOGICAL, OPTIONAL, INTENT(IN) :: Back
      CHARACTER(*), OPTIONAL, INTENT(IN) :: Clean

! Output
! the position of String in Line (the first one) unless Back is present
      INTEGER(KINT) :: Pos

      CHARACTER(LCHARS) :: LineUp,UpString
      LOGICAL :: LCase, LBack, debug

      Debug=valid('InString')

      if (debug) Call header('Entering InString')

      if (present(Case)) THEN
         LCase=Case
      else 
         LCase=.FALSE.
      END IF

      if (present(Back)) THEN
         LBack=Back
      ELSE
         LBack=.FALSE.
      END IF

      UpString=String
      if (.NOT.LCase) Call upcase(UpString)

      if (debug) WRITE(*,*) 'Looking for:',Upstring

      IF (present(Clean)) THEN
         Call CleanString(UpString,Clean)
      END IF

      if (debug) WRITE(*,*) 'Looking for clean:',TRIM(Upstring)

      LineUp=Line
      if (.NOT.LCase) Call UpCase(LineUp)
      IF (present(Clean)) THEN
         Call CleanString(LineUp,Clean)
      END IF
      if (debug) WRITE(*,*) 'Comparing with:',Trim(LineUp)

      Pos=INDEX(LineUp,TRIM(UpString),Back=LBack)

      if (debug) Call header('Exiting InString')

      Return

    END FUNCTION InString
