;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 = wordlength(Text$,5)

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

MCODE Segment Byte
        Assume  CS: MCODE

        Public  wordlength

wordlength Proc Far

ARG     wordnum:WORD, StrHandle: WORD = Retbytes
        jmp over_data
           iwfg  DW   0h
        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

        lodsb                           ; load a character
        cmp     AX,32                   ; 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

        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
        cmp     DX,wordnum              ; is this the desired word?
        jnz     R2                      ; if not get next character
        inc     BX                      ; is the word, count character
        loop ReadChar
        mov     AX,BX                   ; return word count
        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                ;
wordlength EndP