	icl "includes.m65"

ROWCRS	equ $54		;Row of cursor, 1 byte
;COLCRS	equ $55		;Column of cursor, 2 bytes

; Aliases
cursor_y	equ ROWCRS
cursor_x	equ COLCRS

color	equ $2fb	;Color for graphics operations
drawpoint 		equ $f1d8
openmode		equ $ef9c
rom_colors		equ $EE53 ; 0B,0D,0F *2 = 16,1A,1E
;rom_colors		equ $E230 ; 03,07,0E
;rom_colors		equ $e241 ; 03,07,0F

SEEDS_COUNT equ 64
PIXELS_PER_LEN equ 32 

;; we load the code to zero page after system variables

	org $71
length:		; this does not have to be defined
	org $72
pixel:  
	org $73
init:
	jmp start		; 3 bytes
	org $76			; $76-$79
xor_const: 
	.byte $B7, $1D, $C1, $04	
	org $7A
part:
	.byte SEEDS_COUNT-1	; first part is 63
	org $7B
direction:	
	.byte 0		; this gets zeroed by setting graphics mode

	org $7C
; 4 unused system variables $7C-$7F as seed
crc_seed: 
	INS "data.bin",0,4

	org $80
word_seeds:	
	INS "data.bin",4,(SEEDS_COUNT*2) ; inserts 128 bytes into $80-$FF

; on stack page but we are not going to use too much stack
	org $100
	
start
;#### start ####
	lda #$07		; 2 bytes
	jsr openmode	; 3 bytes, Changes $7B (SWPFLG) on zero page to zero so we can't load data there
	; A=00 X=07 Y=01
	
; Setting colors

;	lda #$05
;	sta color0
;	lda #$0A
;	sta color1
;	lda #$0F
;	sta color2	
; or
;	lda #$3
;	sta color0
;	asl @
;	sta color1
;	asl @
;	sta color2
	
next_part:

init_part:
	lda part		; part 0-63, from the end
	sta length		
	sta color	

	asl @			; a = part * 2
	tax				; x = part * 2
	
	; (word) crc_seed = word_seed;
	lda word_seeds,x	
	sta crc_seed
	
	sta cursor_x		; cursor_x = crc_seed
	
	inx
	lda word_seeds,x	
	sta crc_seed+1		
	
	sta cursor_y		; cursor_y = (crc_seed >> 8)

init_part_end

next_length:
	lda #PIXELS_PER_LEN-1
	sta pixel		

next_pixel:
	; r = GetRandom();
inlined_rnd: 
	ASL crc_seed
	ROL crc_seed+1
	ROL crc_seed+2
	ROL crc_seed+3
	BCC nofeedback	
	ldx #3
xor_seed_loop:
	LDA rom_colors,x	; set colors - use rom memory
	ASL @
	STA color0,x
	
	LDA crc_seed,x		; xor crc_seed with constant
	EOR xor_const,x
	STA crc_seed,x
	dex
	bpl	xor_seed_loop
	sta direction	; a=direction=crc_seed[0]
nofeedback:

move_cursor:
	ldx #$C8 ; opcode: iny	
	lda direction ; a=direction
	and #$82	; and 10000001, can set negative flag 
	bpl skip1	; jump if positive - negative flag (&80) is clear: if A&80 then decrease
	ldx #$88 	; opcode: dey - when negative flag is set
skip1
	stx smc
	
	and #2		; random value 0 or 1 for cursor_y/cursor_x
	lsr
	tax
	ldy cursor_y,x  ; x=0,1
smc:
	iny 		; self modifying code - iny/dey
	tya
	and #$7F	; limit value to 0-127
	sta cursor_y,x
		
	jsr drawpoint

;;;;;;;; loop
	
	dec pixel
	bpl next_pixel
	
	dec length
	bpl next_length
	
	dec part	;
	bpl next_part	
end:
	bmi *	; infinite loop, smaller than jmp *
	
;	run start ; not needed

