program Tutorial14_fire;

var
	c,val,time,i : byte;
	x,y : byte;
	// Use custom charset
	charset: IncBin("charsets/tutorial3.bin","$5fff");
	color : array [8] of byte = (9, 2,2,8,8, 10,10, 7,7,1, 1,1,1); 
	
	shiftx: byte;

	rands : array[256] of byte;

	zeropage1: pointer;

/*
 	This tutorial shows a typical preferred coding method using the TRSE language: 
	- First prototype in TRSE
	- Identify slow bottlenecks
	- Rewrite inner loops to assembler

*/

procedure Fire();
begin

	shiftx:=shiftx+31;
	moveto(0, 9, $44);
	zeropage1:=$D968;

	for y:=9 to 13 do begin // 160*4
	//	 Original code
	/*	for x:=0 to 160 onpage do begin
			val:=screenmemory[x+39]+screenmemory[x+40]+screenmemory[x+41] + screenmemory[x+80];
			screenmemory[x]:=val/4 + 64;
		end;*/

			// Optimized
			for x:=0 to 160 onpage do 
			asm("
				lda x
				adc #38
				tay
				lda (screenmemory),y
				iny
				adc (screenmemory),y
				iny
				adc (screenmemory),y
				pha
				tya
				adc #39
				tay
				pla
				adc (screenmemory),y
				
				lsr
				lsr

				tax
				pha
				ldy x
				lda color,x
				sta (zeropage1),y
				pla
				

				bne cont
				lda #1
cont:
				adc #63
				;ldy x
				sta (screenmemory),y		
			");			

		inczp(screenmemory, 160);
		inczp(zeropage1,160);
	end;

	for i:=0 to 40 do begin
		screenmemory[i]:=rands[i+shiftx];
		screenmemory[i+40]:=rands[i-shiftx];
	end;

end;



procedure InitRandom();
begin
	for i:=0 to 0 do begin
		rand(0,255,val);
		rands[i]:=val/16+64;
	end;

end;


begin
	InitRandom();
	HideborderY(0);
	// Set color background
	SCREEN_BG_COL:=BLACK;
	SCREEN_FG_COL:=BLACK;
	// Set charmap location at $2000
	setbank(VIC_BANK1);
	SetCharsetLocation($2000);
	// Clear screen and color memory
	ClearScreen($20, ^$4400);
	ClearScreen(WHITE, SCREEN_COL_LOC);
//	fill(^$2000+^512,1, 0);
	// Main loop
	while 1=1 do begin
		inc(time);
		waitForRaster(0);
		Fire();
	end;
end.
