;Copyright 2000 - Mark McDonald All rights reserved
; DESC:    Returns length of wordn in string
;          wordnum in string.
;          0 is returned if string is null.
;          0 is returned if wordnum is GT number of words.
; EXAMP:   t = xwordlength(Text$,5,char)

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

MCODE Segment Byte
        Assume  CS: MCODE

        Public  xwordlength

xwordlength 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
        xor     BX,BX                   ; clear BX
        jcxz    Exit                    ; is passed string null?
        cmp     AX,wordnum              ; is passed word number 0?
        jz      Exit
        xor     DX,DX                   ; clear DX
        mov     [iwfg],1                ; init in word flag

ReadChar:
        lodsb                           ; load a character
        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

        cmp     BX,0                    ; not a space, must be in word
        jnz     Exit                    ; if so then we are done counting
        jmp     R2                      ; else get next character

Notsp:
        cmp     [iwfg],2                ; in word flag already set?
        jz      R1                      ; if so pass to char counter
        mov     [iwfg],2                ; else set in word flag
        inc     DX                      ; add 1 to word count
R1:
        cmp     DX,wordnum              ; is this the desired word?
        jnz     R2                      ; if not get next character
        inc     BX                      ; is the word, count character
R2:
        loop ReadChar
Exit:
        mov     AX,BX                   ; 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                ;
xwordlength EndP
MCODE EndS
        End