' ******************************************************************
' String functions
' ******************************************************************

FUNCTION Extract(S AS STRING, BYREF Index AS INTEGER, Delim AS STRING) AS STRING
' ------------------------------------------------------------------
' Extracts a field from a string. Index is the position of the first
' character of the field. Delim is the character used to separate
' fields (e.g. blank, comma or tabulation). Blanks immediately
' following Delim are ignored. Index is updated to the position of
' the next field.
' ------------------------------------------------------------------

  DIM AS INTEGER I, L

  I = Index
  L = LEN(S)

  ' Search for Delim 
  DO WHILE I <= L AND MID$(S, I, 1) <> Delim
    I = I + 1
  LOOP

  ' Extract field
  IF I = Index THEN
    Extract = ""
  ELSE
    Extract = MID$(S, Index, I - Index)
  END IF

  ' Skip blanks after Delim 
  DO
    I = I + 1
  LOOP UNTIL I > L OR MID$(S, I, 1) <> " "

  ' Update Index
  Index = I
END FUNCTION

SUB Parse(S AS STRING, Delim AS STRING, Elem() AS STRING, BYREF N AS INTEGER)
' ------------------------------------------------------------------
' Parses a string into its constitutive fields. Delim is the field
' separator. The number of fields is returned in N. The fields are
' returned in array Elem().
' ------------------------------------------------------------------

  DIM AS INTEGER Index, L, Lb, Ub

  Lb = LBOUND(Elem)
  Ub = UBOUND(Elem)

  N = Lb
  Index = 1
  L = LEN(S)

  DO
    Elem(N) = Extract(S, Index, Delim)
    N = N + 1
  LOOP UNTIL Index > L OR N > Ub

  N = N - Lb
END SUB
