REM
REM Contributed by James C. Fuller - April 2009.
REM
REM' bacon ParseStr
REM' Delim$ can include more than one delimiter by using ANY followed by delimiters
REM' example: S1$ = ParseStr("one,two,three;four,five","Any;,",3)
REM' INCLUDE tally.bac
REM' INCLUDE replace.bac
REM' redisigning to return in a var
FUNCTION ParseStr(STRING Main$,STRING Delim$,int Index)
    LOCAL i,j,k,mlen,dlen,dcount TYPE int
    LOCAL sRet$ TYPE STRING
    LOCAL S1$ TYPE STRING
    LOCAL dl$ TYPE STRING
    
    sRet$=""
    mlen = LEN(Main$)
    dlen = LEN(Delim$)
    IF mlen EQ 0 THEN
       RETURN "mlen = 0"
    ENDIF
    IF dlen EQ 0 THEN
       RETURN "dlen = 0"
    ENDIF
    IF dlen >= mlen THEN
        RETURN "dlen >= mlen"
    ENDIF 
    i = 0
    j = 1
    k = 0
rem    PRINT "In ParseStr Main$ = ",Main$ FORMAT "%s%s\n"
    S1$=""

    dl$ = Delim$

    IF dlen > 1 THEN
        dl$ = CHR$(255)
        S1$ = CONCAT$(Main$,dl$)
REM' For Testing of memory coruption
REM'    PRINT UCASE$(LEFT$(Delim$,3)) FORMAT "%s\n"
REM'    PRINT "***",Delim$,"****" FORMAT "%s%s%s\n"
REM' ================================================  
        IF EQUAL(UCASE$(LEFT$(Delim$,3)),"ANY") THEN
            FOR i = 4 TO dlen
                    S1$ = Replace(S1$,MID$(Delim$,i,1),dl$)
                NEXT
        ELSE
                S1$ = Replace(S1$,Delim$,dl$)
            ENDIF
    ELSE        
        S1$ = CONCAT$(Main$,Delim$)    
rem        S1$ = Main$
    ENDIF
    dcount = Tally(S1$,dl$)
    rem PRINT "S1$ = ",S1$
rem       dcount = ParseCount(S1$,dl$)
rem    PRINT S1$
    IF Index > dcount THEN
        sRet$ = CONCAT$("Index > dcount  dcount = ",STR$(dcount)," Val of dl$ = ",STR$(ASC(dl$)))
        RETURN sRet$
    ENDIF

    FOR i = 1 TO LEN(S1$)
        IF EQUAL(MID$(S1$,i,1),dl$) THEN
            k = k + 1
            IF k EQ Index THEN
                sRet$ = MID$(S1$,j,(i-j))
                RETURN sRet$
            ENDIF
            j = i + 1
        ENDIF
    NEXT

    RETURN "crap"
ENDFUNCTION