;Copyright 2000 - Mark McDonald All rights reserved
; DESC:    Returns starting column position of space delimited word
;          wordnum in string.
;          0 is returned if string is null.
;          0 is returned if wordnum is GT number of words.
; EXAMP:   t = xxwordindex(Text$,5,int)

Extrn   Get$Loc: Far
Extrn   Rls$Alloc: Far

MCODE Segment Byte
        Assume  CS: MCODE

        Public  xwordindex

xwordindex Proc Far

ARG     mchar:WORD, wordnum:WORD, StrHandle: WORD = Retbytes
        jmp over_data
           iwfg  DW   0h
over_data:
        push    BP                      ;
        mov     BP,SP                   ;
        push    DS                      ;
                                        ; GET STRING POINTER
        mov     AX, StrHandle           ; put string handle in AX
        push    AX                      ; push it on the on stack
        call    Get$Loc                 ; get location of string
        mov     DS,DX                   ; put returned segment in DS
        mov     SI,AX                   ; put returned offset in SI

        xor     AX,AX                   ; clear AX
        jcxz    Exit                    ; is passed strin null? if so exit
        xor     DX,DX                   ; clear DX
        mov     [iwfg],1                ; init in word flag
        xor     BX,BX                   ; clear BX

ReadChar:
        lodsb                           ; load a character
        inc     BX                      ; increment character counter
        cmp     AX,mchar                ; is character a space?
        jnz     Notsp                   ; if not 0 jump to Notsp
        mov     [iwfg],0                ; is a space, init in word flag
        jmp     R2                      ; get next character

Notsp:
        cmp     [iwfg],2                ; in word flag already set?
        jz      R2                      ; if set get next character
        mov     [iwfg],2                ; set word flag
        inc     DX                      ; add 1 to word count
        cmp     DX,wordnum              ; is this the word desired?
        jnz     R2                      ; if not get next character
        mov     AX,BX                   ; yes move char count to AX
        jmp     Exit2
R2:
        loop ReadChar
Exit:
        xor     AX,AX                   ; return word count
Exit2:
        push    AX                      ; save return val
        push    Word Ptr StrHandle      ; push string handle
        call    Rls$Alloc               ; release string
        pop     AX                      ;
        pop     DS                      ;
        pop     BP                      ;
        retf    Retbytes                ;
xwordindex EndP
MCODE EndS
        End