-------------------------------------------------------------------------
-- Project: FIFO, generic FIFOs written in VHDL
-- Release 1
--
-- Copyright (C) 2007 J. Ahrensfeld
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
--
-- For questions and ideas, please contact the author at jens@jayfield.org
--
-----------------------------------------------------------------------

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.ALL;

LIBRARY WORK;
USE WORK.FIFO_CTRL_PKG.ALL;

entity gray_counter is
	Generic (
		width : natural := 3;
		init_value : natural := 0
	);
	Port
	(
		rst			: in  STD_LOGIC;
		clk			: in  STD_LOGIC;
		ce			: in  STD_LOGIC;
		bcnt		: out unsigned (width-1 downto 0);
		bnxt		: out unsigned (width-1 downto 0);
		gcnt		: out unsigned (width-1 downto 0);
		gnxt		: out unsigned (width-1 downto 0)
	);
end gray_counter;

architecture Behavioral of gray_counter is

	signal cntg : unsigned (width-1 downto 0);
	signal cntb : unsigned (width-1 downto 0);
	signal nxtb : unsigned (width-1 downto 0);
	signal nxtg : unsigned (width-1 downto 0);

begin

	bnxt	<= nxtb;
	gnxt	<= nxtg;
	bcnt	<= cntb;
	gcnt	<= cntg;

	nxtg <= bin2gray(nxtb);
	nxtb <= (cntb + 1) when ce = '1' else cntb;

	process(clk)
	begin
		if rising_edge(clk) then
			if rst = '1' then
				cntb	<= to_unsigned(init_value, width);
				cntg	<= to_unsigned(init_value, width);
			else
				cntg	<= nxtg;
				cntb	<= nxtb;
			end if;
		end if;	
	end process;

end Behavioral;

