library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;

entity CharDecoder is
    Port ( ASCII : in  STD_LOGIC_VECTOR (7 downto 0);
           Clk : in STD_LOGIC;
           NewData : in  STD_LOGIC;
           RAMRow : out  natural range 0 to 29;
           RAMCol : out  natural range 0 to 79;
           DataOut : out  STD_LOGIC_VECTOR (7 downto 0));
end CharDecoder;

architecture Behavioral of CharDecoder is
	signal Row: integer range 0 to 29;
	signal Col: integer range 0 to 79;
   signal PrevState: STD_LOGIC := '1';
   signal CursorBlink: natural range 0 to 30000000 := 0; 
begin
	process (Clk)
	begin
		if Clk'event and Clk = '1' then
         
         RAMCol <= Col;
			RAMRow <= Row;
         
         CursorBlink <= CursorBlink + 1;
         if CursorBlink <= 15000000 then
            DataOut <= "01011111";
         else
            DataOut <= "00100000";
         end if;
         
            
         if NewData = '1' then
            if PrevState = '0' then
               if to_integer(unsigned(ASCII)) >= 32
               AND to_integer(unsigned(ASCII)) /= 127
               AND to_integer(unsigned(ASCII)) /= 129
               AND to_integer(unsigned(ASCII)) /= 131
               AND to_integer(unsigned(ASCII)) /= 136
               AND to_integer(unsigned(ASCII)) /= 144
               AND to_integer(unsigned(ASCII)) /= 152
               then
                  Col <= Col + 1;
                  if Col >= 79 then
                     Col <= 0;
                     Row <= Row + 1;
                     if Row >= 29 then
                        Row <= 0;
                        Col <= 0;
                     end if;
                  end if;
                  DataOut <= ASCII;
               end if;
               
               if to_integer(unsigned(ASCII)) = 13 then 
                  DataOut <= "00100000";
                  Row <= Row + 1;
                  Col <= 0;
               end if;
			
               if to_integer(unsigned(ASCII)) = 27 then
                  DataOut <= "00100000";
                  Row <= 0;
                  Col <= 0;
               end if;
               
               if to_integer(unsigned(ASCII)) = 8 then
                  DataOut <= "00100000";
                  if Col = 0 then
                     if Row = 0 then
                        Row <= 29;
                     else
                        Row <= Row - 1;
                     end if;
                     Col <= 79;
                  else
                     Col <= Col - 1;
                  end if;
               end if;
            
               PrevState <= '1';
            end if;
         else
            PrevState <= '0';
         end if;
		end if;
	end process;	
end Behavioral;

