-- File Name: template vhdl code for ega drive
-- Author:    Zexin Pan
--
-- 
library ieee;
use  IEEE.STD_LOGIC_1164.all;
use  IEEE.STD_LOGIC_ARITH.all;
use  IEEE.STD_LOGIC_UNSIGNED.all;


entity ega is
	port( 	Clock : in std_logic;
			r,g,b:  in std_logic;
		    H_SYNC_OUT,V_SYNC_OUT : out std_logic;
        	red_out,green_out,blue_out :out std_logic;
			pixel_rw,pixel_col: out std_logic_vector (9 downto 0));
end ega;

architecture behavior of ega is
	
	signal h_count,v_count:std_logic_vector (9 downto 0);
	signal VIDEO_ON_H,VIDEO_ON_V,video_on: STD_LOGIC;
	signal h_sync,v_sync:std_logic;

	begin

	process

	begin
	
	wait until (clock'EVENT) and (clock='1');           
	
	
-- H_count counts horizonal pixels (640 + time for horizonal sync signals+time for blanking)
--
--   <-         640 pixels/row      ->   <-H Sync-> <--blanking-->
--   ------------------------------------__________ ----------
		If (h_count >= "") then   
			h_count <="";
		Else
			h_count <= h_count+1;
		End if;

--Generate Horizontal Sync Signal
		If (h_count <= "") and (h_count >= "") Then   
			H_SYNC <= '1';
		ELSE
			H_SYNC <= '0';
		End if;

--V_count counts rows (350 + time for vertical sync signals+ time for blanking)
--
--  <---- 350 Horizontal pixels------------------> <-V Sync-><-blanking-->
--  -----------------------------------------------__________------------


		If (v_count >= "") and (h_count <= "") then   
			v_count <= "";
		Elsif (h_count = "") Then          
			v_count <= v_count+1;
		End if;
		
-- Generate Vertical Sync Signal
		If (v_count<= "") and (v_count >= "") Then          
   			V_SYNC <= '0';
		ELSE
   			V_SYNC <= '1';
		End if;



-- Generate Video on Screen Signals for Pixel Data			
		If (h_count <= "") Then              
			video_on_H <= '1';
			PIXEL_COL <=h_count;
		ELSE		
			video_on_H <= '0';
		End if;


		if (v_count <="") then             
			video_on_V <='1';
			pixel_rw <=v_count;
		ELSE
			video_on_V <= '0';
		End if;
		
		RED_OUT <=r AND video_on;
		green_out <= g AND video_on;
		blue_out <=b AND video_on;

		H_SYNC_OUT <=H_SYNC;
		V_SYNC_OUT <=V_SYNC;

    	end process;

		video_on <=video_on_H and video_on_V;


end behavior;


