; School of Computer Engineering
; K.N. Toosi University of Technology

%include "asm_io.inc"

segment .bss
a:      resd       1    ; reserve a dword (4 bytes) 

segment .text
global asm_main

asm_main:
        enter 0,0
        pusha
        ;; ==========================

        push a      ; push the address of a
        push 10

        call store_sum

        add esp, 8


        mov eax, [a]
        call print_int
        call print_nl

        ;; ==========================
        popa
        leave
        ret

store_sum:
        push ebp
        mov ebp, esp
        sub esp, 8              ; local variables

        mov dword [ebp-8], 0            ; sum = 0
        mov dword [ebp-4], 1            ; i = 1
forloop:
        ; if (i > n) goto endloop
        mov eax, [ebp-4]        ; eax = i
        cmp eax, [ebp+8]        
        jg  endloop

        ;; sum = sum + i
        add [ebp-8], eax        ; NOTE: eax == i

        inc dword [ebp-4]       ; i++

        jmp forloop

endloop:        
        mov ecx, [ebp+12]
        mov eax, [ebp-8]

        mov [ecx], eax

        mov esp, ebp    ; release local vars
        pop ebp
        ret