program test;
@use "system/screen"
@use "system/memory"

@export "trse1.flf" "trse.bin" 0

@convert_jdh8 "data/twister_data.bin" "data/twister_data.jdh"
@convert_jdh8 "data/twister_table.bin" "data/twister_table.jdh"


var 
	i,cnt,it : integer;
  	frame,k,y,tmp1,tmp2,tt2: byte;
	time,j,m,x:byte;
  	
	ll,tt : byte; 
	tp,dst,scr,zp:pointer of byte;
	tab:pointer of integer;

	itable32 : array[240] of integer=BuildTable("i*32");
	
//   	data : incbin("data/twister_data.bin");
   	data : incbin("data/twister_data.jdh");
   	table : incbin("data/twister_table.jdh");

	text:string="ABCDEFGHIJKLM";

	tab_div16 : array[256] of byte = BuildTable("i/16");
	 sine32 : array[256] of byte = BuildTable("(Math.sin(i/256.0*Math.PI*2.0)*80+79)/9");
    

	charLookup : array[32] of integer = BuildTable("(2*16*32*i)");
	frameLookup : array[16] of integer = BuildTable("(2*32*i)");


procedure RenderTwister(tx:byte);
begin
	
	tt2:=tt2+1;
	tt:=0-tx; // Text goes up
	tt2:=tx; // Twist goes down
	tp:=#text;
	j:=0;
	
	y:=0;
	scr :=itable32[y];
	scr := scr + #Screen::pos;
	scr:=scr+10;
	for k:=0 to 120 do
	begin
		tmp1:=k+tt2;
		j:=sine32[tmp1];
		frame := tx-j;
		frame := frame &15;
		j:=0;				
//		j:=sine32[(k+tt2)&255]; // Twist turning
//		frame:=(((tx>>1-j))&15); // Current rotation frame
		ll:=(k-tt); // Current shift & text position in y
		
		j:=tab_div16[ll]; // Twister yeah!
	 	m:=k;
	 	m:=tp[j];
		m:=m-1;
		m:=m&7;
//		frame:=7;
//		frame:=time&15;
//		m:=0;
		
//	 	if (frame=0) then frame:=1; // bug
//		asm(";here");
//		frame:=3;
		tab := frameLookup[frame];
		tab := #table+tab;
		it:=charLookup[m];
		tab :=tab +it;
		j:=k+time;
		j:=j&31;
		
		
		zp := tab[j];
		zp:=#data + zp;
		Memory::Copy16(zp,scr,8);
			
		scr:=scr+32;
		Memory::Copy16(zp,scr,8);
		scr:=scr+32;

	end;
	
end;



begin
	Memory::Init();
	scr:=#Screen::pos;	
	while (true) do
	begin	
		RenderTwister(time);
		for i:=0 to 20000 do
		begin
			
		end;
		time+=1;
	end;
	

	
end.
