'  (Internal use for FF_Parse and FF_ParseAny)
''
''  FF_PARSE_INTERNAL
''  用于 FF_Parse 和 FF_ParseAny （内部函数）
''
Function FF_Parse_Internal( ByRef sMainString   as String, _
                            ByRef sDelimiter    as String, _
                            ByRef nPosition     as Integer, _
                            ByRef nIsAny        as Integer, _
                            ByRef nLenDelimiter as Integer _
                            ) as String
                   
    ' Returns the nPosition-th substring in a string sMainString with separations sDelimiter (one or more charcters),
    ' beginning with nPosition = 1

    Dim as Integer i, j, count
    Dim s as String 
    Dim fReverse as Integer = IIf(nPosition < 0, True, False)
    
    nPosition = Abs(nPosition)
    count = 0
    i = 1
    s = sMainString 
    
    If fReverse Then 
       ' Reverse search
       ' Get the start of the token (j) by searching in reverse
       If nIsAny Then
          i = InStrRev(sMainString, Any sDelimiter)
       Else
          i = InStrRev(sMainString, sDelimiter)
       End If
       Do While i > 0        ' if not found loop will be skipped
          j = i + nLenDelimiter
          count += 1
          i = i - nLenDelimiter
          If count = nPosition Then Exit Do
          If nIsAny Then
             i = InStrRev(sMainString, Any sDelimiter, i )
          Else
             i = InStrRev(sMainString, sDelimiter, i )
          End If   
       Loop
       If i = 0 Then j = 1

       ' Now continue forward to get the end of the token
       If nIsAny Then
          i = InStr(j, sMainString, Any sDelimiter)
       Else
          i = InStr(j, sMainString, sDelimiter)
       End If
       If (i > 0) Or (count = nPosition) Then
           If i = 0 Then
               s = Mid(sMainString, j)
           Else
               s = Mid(sMainString, j, i - j)
           End If
       End If
    
    Else              
    
       ' Forward search
       Do
           j = i
           If nIsAny Then
              i = InStr(i, sMainString, Any sDelimiter)
           Else
              i = InStr(i, sMainString, sDelimiter)
           End If   
           If i > 0 Then count += 1: i += nLenDelimiter
       Loop Until (i = 0) Or (count = nPosition)

       If (i > 0) Or (count = nPosition - 1) Then
           If i = 0 Then
               s = Mid(sMainString, j)
           Else
               s = Mid(sMainString, j, i - nLenDelimiter - j)
           End If
       End If
    End If
      
    Return s

End Function

