;==========================================================
; File:    Average.asm
; Author:  Bary W Pollack
; Date:    Oct. 23, 2009
; Course:  GSP130
; Purpose: Determine the average of a table of integers.
;          Show how to index an array of integers.
;==========================================================


include 'emu8086.inc'

       org  100h ; set location counter to 100h

       jmp  CodeStart

DataStart:

values   dw  3, 1, 4, 2, 5, 0    ; values end with zero
valMsg   db  13, 10, "The values are: ", 0
space    db  " ", 0
avgMsg   db  13, 10, "The (integer) average is ", 0
finMsg   db  13, 10, 13, 10, "Fini", 13, 10, 0
sum      dw  0
count    dw  0 
average  dw  ?


CodeStart:
       mov  si, offset valMsg    ; display initial message
       call print_string

       mov  di, offset values    ; load index register
Lup:
       mov  ax, [di]             ; get next integer
       cmp  ax, 0                ; if zero, we're done
       je   Calculate
       add  sum, ax              ; add it to the sum
       add  count, 1             ; increment count
       call print_num            ; display the number

       mov  si, offset space     ; display space
       call print_string 
       
       add  di, 2                ; increment to next word
       jmp  Lup                  ; go back for more

Calculate:
       mov  dx, 0                ; load dx:ax with sum
       mov  ax, sum              ; load bx with count
       mov  bx, count            ; divide sum / count
       div  bx                   ; quotient is in bx
       mov  average, ax          ; save result in average

Finish:
       mov  si, offset avgMsg    ; display "The average is"
       call print_string
       
       mov  ax, average          ; display the average
       call print_num

       mov  si, offset finMsg    ; display "Fini"
       call print_string
       ret                       ; return to caller

DEFINE_GET_STRING
DEFINE_PRINT_STRING
DEFINE_PRINT_NUM 
DEFINE_PRINT_NUM_UNS
