program Keyboard_input;
@use "screen/screen"
@use "system/memory"
var  
   	index: byte; 
	command : array[64] of byte;
	p : ^byte;
	
procedure ReadLine();
var
	isNotDone, renderChar : byte=true;
	cur,reset,firstKey, blink, key, prevKey: byte = 0;
	
begin
	isNotDone:=true;
	p:=#Screen::screen0 + Screen::tab40[4];
	

	while (isNotDone) do
	begin
		Screen::WaitForRaster(0);
			
		renderChar:=true;
		key:=getKey();
//		if (key>64 and key<80) then key:=key-64;

		if (key=$FF) then
			firstKey:=0;
			
		prevKey:=key;
		
		if (key<>$FF and reset=0) then
		begin
			if (firstKey=0) then
				reset:=16
			else
				reset:=8;
				
			firstKey:=1;

			if (key=$F7) then // backspace
			begin
				p[cur]:=key_space;
				if (cur<>0) then
					cur:=cur-1;
				p[cur]:=key_space;
			
				renderChar:=false;		
			end;
			if (key=$8E) then // return 
			begin
				renderChar:=false;
				command[cur]:=0;
				cur:=0;
				isNotDone:=false;							
			end;

			if (renderChar) then
			begin
				command[cur]:=key;
				if (key>64 and key<91) then key:=key-64;
				p[cur]:=key;
				inc(cur);
			end;

		end;
		blink+=1;
		if (blink=16) then p[cur]:=key_space+$80;
		if (blink=32) then begin p[cur]:=key_space; blink:=0; end;
		
		if (reset<>0) then reset-=1;

	end;
end;

procedure Message(p2:pointer);
begin
	Screen::PrintString(p2,0,7, #Screen::screen0);
end;


procedure ExecuteCommand();
begin
	Memory::Fill(p,key_space,40);
		Message(#command);
	
	if (strcmp(#command,"HELLO")) then
		Message("HELLO TO YOU");

	if (strcmp(#command,"HOW ARE YOU")) then
		Message("FINE INDEED");

	if (strcmp(#command,"GO AWAY")) then
		Message("NO I WON'T");

	if (strcmp(#command,"WHO ARE YOU")) then
		Message("I AM COMPUTER");

end;


   
begin
	clearscreen(key_space,screen_char_loc);
	p:=#Screen::screen0 + Screen::width;
	Screen::PrintString("HI THERE!",0,1, #Screen::screen0);
	Screen::PrintString("SPEAK YOUR MIND",0,2, #Screen::screen0);
	
	while (true) do
	begin
		ReadLine();
		ExecuteCommand();
	end;
	

end.
