--	Package File Template
--
--	Purpose: This package defines supplemental types, subtypes, 
--		 constants, and functions 


library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.std_logic_unsigned.all;

package udp_functions_pkg is

	function to_bcd ( bin : std_logic_vector(11 downto 0) ) return std_logic_vector;

end udp_functions_pkg;


package body udp_functions_pkg is

-- from http://vhdlguru.blogspot.it/2010/04/8-bit-binary-to-bcd-converter-double.html

function to_bcd ( bin : std_logic_vector(11 downto 0) ) return std_logic_vector is
	variable i		: integer := 0;
	variable bcd	: std_logic_vector(13 downto 0) := (others => '0');
	variable bint	: std_logic_vector(11 downto 0) := bin;

	begin
		for i in 0 to 11 loop												-- repeating 12 times.
			bcd(13 downto 1) := bcd(12 downto 0);						-- shifting the bits.
			bcd(0) := bint(11);
			bint(11 downto 1) := bint(10 downto 0);
			bint(0) :='0';
			
			
			if(i < 11 and bcd(3 downto 0) > "0100") then				-- add 3 if BCD digit is greater than 4.
				bcd(3 downto 0) := bcd(3 downto 0) + "0011";
			end if;
			
			if(i < 11 and bcd(7 downto 4) > "0100") then				-- add 3 if BCD digit is greater than 4.
				bcd(7 downto 4) := bcd(7 downto 4) + "0011";
			end if;
			
			if(i < 11 and bcd(11 downto 8) > "0100") then			-- add 3 if BCD digit is greater than 4.
				bcd(11 downto 8) := bcd(11 downto 8) + "0011";
			end if;
			
		end loop;
		
		return bcd;
		
	end to_bcd;

 
end udp_functions_pkg;
