;  selfmod.asm   Self modifying program Last byte is the counter value
;                COM file.
;
.model  tiny
.code
org     100h

Start:
        inc     [Counter]               ;Update counter

        mov     ds,ds:[2ch]             ;Get segment of environment
        xor     di,di                   ;Clear pointer
        xor     ax,ax                   ;Clear result to look for
loop1:
        inc     di                      ;Point to next byte
        cmp     [di],ax                 ;Found double zero?
        jnz     loop1                   ; no: search some more

        mov     ax,3d02h                ;Open file for R/W
        lea     dx,[di+4]               ;Point to program name
        int     21h                     ;Open it
        xchg    bx,ax                   ;Handle to BX

        push    cs                      ;Restore DS
        pop     ds

        mov     ah,40h                  ;Write file
        mov     cx,ProgSize             ;Nr of bytes to write
        mov     dx,100h                 ;Start at 100h
        int     21h                     ;Write it

        mov     al,[Counter]            ;Get new counter value in AL
        mov     cl,4                    ;Get shift count in CL
        call    Putch                   ;Display high nibble
        mov     al,ah                   ;Prepare low nibble
Putch:
        ror     ax,cl                   ;Get proper nibble in AL
        cmp     al,10
        sbb     al,69h
        das
        int     29h                     ;Display char in al
        ret                             ;Return to caller (or DOS)

Counter db      0

ProgSize equ    $ - Start

        End     Start
