;Exam. 2005A.Q5.asm
segment_size equ 0FFFFh
segment_start equ 0FAACh
Max_input_size equ 5
               
.model small
.stack 100h

.data
input_size dw 0
enter_string_msg db 'please enter string', '$'
input_string db Max_input_size, 0
             db Max_input_size dup (0)
num_of_matches db 0
num_of_matches_msg db 'number of matches found', '$'

.code
mov ax, @data
mov ds,ax
mov ax, segment_size
mov ds,ax

mov ah, 3 ;get cursor position and size
int 10h

call GetStringFromUser 
call FindStringInSegment
call PrintNumOfMatches

mov ah, 4ch
int 21h

GetStringFromUser:
    push ax
    push dx
    
    mov dx, offset enter_string_msg     
    mov ah, 9 ;output of a string
    int 21h  

    mov dx, offset input_string
    mov ah, 0Ah ;input of a string
    int 21h  

    pop dx
    pop ax
    ret

FindStringInSegment:
    push bx
    push cx
    push di
    push si
    
    mov num_of_matches, 0
    mov input_size, 1+offset input_string
    
    mov bx, segment_size
    sub bx, input_size
    mov si, 2+offset input_string 
    
    
    findInCurrOffset:
        mov cx, input_size
        mov di, bx
        
        cld ;clear direction flag: DF=0
        
        ;repeat while equal
        ;checking continues as long as cx!=0 and ZF==0
        ;comparing bytes between ES:[DI] and DS:[SI]        
        REPE CMPSB
        jnz NextOffset
        ;if ZF!=0 than cx have not reached zero
        ;and therefore the string are not the same
        
    FoundMatch: ;updating number of matches
        inc num_of_matches
        jmp NextOffset
        
    NextOffset:
        cmp bx, 0
        je Finished
        
        dec bx
        jmp findInCurrOffset
        
    finished:
        pop si
        pop di
        pop cx
        pop bx
    ret
    
PrintNumOfMatches:      
    push ax
    push dx
    
    mov dx, offset num_of_matches_msg
    mov ah, 9 ;output of a string
    int 21h  
    
    mov dl, num_of_matches
    add dl, 48 ;to jump to right ASCII code
    mov ah, 2 ;write character to output
    int 21h  

    pop dx
    pop ax
    ret
end                     