;
;   SIEVE of ERISTOTHANIES
;


        .entry  sieve, ^m<r2,r3,r4,r5,r6,iv>

;
;   First, let's get the base address and size of the array.  Also,
;   declare a condition handler (not ready to use yet, but for future
;   testing.
;

        movl    @#array_size, r5
        moval   @#array, r6
        movab   @#errors, (fp)

;
;   Initialize the array
;

        movl    r5, r0

init:       movab   (r6)[r0], r4    ;   Get address of cell (debug)
        clrb    (r4)        ;   and zap it.
        sobgtr  r0, init

;
;   Choose the first prime number
;

        movl    #2, r1

;
;   Mark out the nth elements of the array
;

        movl    r1, r2      ;   prime is index

mark:       movb    #1, (r6)[r2]    ;   write the marker byte
        addl2   r1, r2      ;   stride by prime
        cmpl    r2, r5      ;   are we done?

        bleq    mark        ;   nope, go some more

;
;   Find the next free element
;

        movl    r1, r3      ;   make copy of last prime

find:   incl    r1          ;   step to next cell
        cmpl    r1, r5      ;   are we at end of array?
        bgtr    done        ;   yes, all done

        tstb    (r6)[r1]    ;   see if cell empty
        bneq    find        ;   no, look some more

        movl    r1, r2      ;   yes, cell empty, so mark
        brb mark            ;   this as new prime

done:   movl    r3, r0      ;   we return last prime
                            ;   as function result
        ret

;
;   Condition handler (currently does nothing)
;
        .entry errors, ^m<>
        movl #1, r0         ;   just signal success
        ret

;
;   Data storage here...
;

array_size: .long   100
array:      .blkb   100


        .end sieve

