;       Static Name Aliases
;
        TITLE   strnrev
;       NAME    strnrev.C

;   char *strnrev(dst, src, len)
;
;   copies len characters of src to dst, in REVERSE order.  dst will
;   be terminated by a NUL character.
;
;   Returns a pointer to dst.
;
;   Note: this function is perfectly happy to reverse a string into the
;   same place, strnrev(x, x, L) will work.
;
;   It will not work for partially overlapping source and destination.

        .287
_TEXT   SEGMENT  BYTE PUBLIC 'CODE'
_TEXT   ENDS
_DATA   SEGMENT  WORD PUBLIC 'DATA'
_DATA   ENDS
CONST   SEGMENT  WORD PUBLIC 'CONST'
CONST   ENDS
_BSS    SEGMENT  WORD PUBLIC 'BSS'
_BSS    ENDS
DGROUP  GROUP   CONST,  _BSS,   _DATA
        ASSUME  CS: _TEXT, DS: DGROUP, SS: DGROUP, ES: DGROUP
EXTRN   __chkstk:NEAR
_TEXT      SEGMENT

        PUBLIC  _strnrev
_strnrev        PROC NEAR

;       dsta = 4
;       register si = dsta
;       srca = 6
;       register di = srca
;       len = 8
;       dstz = -2
;       srcz = -6
;       result = -4

        push    bp
        mov     bp,sp
        mov     ax,6
        call    __chkstk
        push    di
        push    si
        mov     si,[bp+4]                ;dsta
        mov     word ptr [bp-4],si       ;result
        mov     di,[bp+6]                ;srca

int 3
        mov     cx,[bp+8]
        mov     al,0
        repnz   scasb
        jcxz    no_adj
        inc     cx
        dec     di
no_adj:

        mov     bx,[bp+8]
        sub     bx,cx
        add     si,bx
        mov     word ptr [bp-2],si   ;dstz
        mov     byte ptr [si],al
        mov     word ptr [bp-6],di   ;srcz

        mov     si,[bp+4]       ;dsta
        mov     di,[bp+6]       ;srca
;       mov     word ptr [bp-4],si      ;result

        jmp     SHORT $L20002
$WC19:

        dec     WORD PTR [bp-6] ;srcz
        mov     bx,[bp-6]       ;srcz
        mov     cl,[bx]
;       cbw
;       mov     [bp-4],ax       ;t

        dec     WORD PTR [bp-2] ;dstz
        mov     bx,[bp-2]       ;dstz
        mov     al,[di]
        inc     di
        mov     [bx],al

;       mov     al,[bp-4]       ;t
        mov     [si],cl
        inc     si

$L20002:
        cmp     [bp-6],di       ;srcz
        ja      $WC19

        mov     ax,[bp-4]
        pop     si
        pop     di
        mov     sp,bp
        pop     bp
        ret

_strnrev        ENDP
_TEXT   ENDS
END
