; Random.asm
; Copyright Xerox Corporation 1979

;	Last modified November 8, 1977  5:13 PM

.ent Random

.srel

Random:	.Random

.nrel


; Random()
; Returns a 16-bit random number using the generator
;	x[n] = (x[n-33] + x[n-13]) mod 2↑16

.Random:
	sta 3 1 2
	jsr ran1

	160315
	 34255
	 43770
	104071
	 21360
	135442
	 45545
	106565
	  6714
	133667
	176741
	 12402
	114375
	 36624
	 34427
	105045
	146515
	 63276
	 36434
	 67771
	127054
	 77772
	 26244
	171113
	164223
	114267
	132355
	146005
	 44600
	 41705
	144466
	131235
	 31377

ran1:	lda 0 index		; Get index (counts toward 0)
	add 0 3			; Point to table entry +1
	lda 1 d20		; Is x[n-13] ahead or behind us in table?
	sgt 0 1
	 jmp ran2
	lda 1 -21. 3		; x[n-13] from ahead of us (lower address)
	jmp ran3

ran2:	lda 1 12. 3		; x[n-13] from behind us (higher address)
ran3:	lda 0 -1 3		; Add x[n-33]
	add 1 0
	sta 0 -1 3		; Result is x[n]
	lda 3 1 2
	dsz index		; Advance index
	 jmp 1 3
	lda 1 d33		; Wrap around
	sta 1 index
	jmp 1 3

index:	33.			; Current table index [1..33]
d20:	20.
d33:	33.

	.end