; The M13_COPYNEW.ASM file

.586P
.MODEL FLAT, stdcall     ; Flat memory model

EXTERN NEWARRAY@4:NEAR   ; This procedure is defined in M13_NEWARRAY.cpp
EXTERN strlen:NEAR       ; This procedure is part of the C standard library

PUBLIC COPYNEW           ; COPYNEW is externally visible to the linker

_TEXT SEGMENT            ; Code segment begins

; Procedure for copying the source string into newly allocated string
; Input: str1 is the pointer to the source string
; Output: EAX is the pointer to the dynamically allocated target string
COPYNEW PROC  str1: DWORD
        push  esi        ; preserve registers
        push  edi
        
        mov   esi, str1  ; get pointer to the source string

        push  esi  
        call  strlen     ; calculate source string size

        inc   eax        ; Account for terminating null character
        push  eax        ; push required size of the memory block
        call  NEWARRAY@4 ; allocate new block of memory
        mov   edi, eax   ; initialize destination pointer
        push  eax        ; preserve dynamic memory address
L1:
        mov   al, byte ptr [esi] ; copy characters from source...
        mov   byte ptr [edi], al ; ...to destination, including terminating zero
        cmp   al, 0      ; end of string is reached ?
        je    L2         ; Yes, the destination string is ready
        inc   esi        ; No, keep copying...
        inc   edi
        jmp   L1
L2:
        pop   eax        ; return pointer to dynamic memory
        pop   EDI        ; restore preserved registers
        pop   ESI
        ret
COPYNEW ENDP

_TEXT ENDS               ; Code segment begins
END

