procedure ALU_OP				-- perform ALU operation with 2 operands
	(Md : in std_logic_vector(7 downto 0);
	 signal A, X : inout std_logic_vector(7 downto 0);
	 signal N, Z, C : inout std_logic) is 
variable res : std_logic_vector(8 downto 0);	-- result of ALU operation
variable updateNZ : Boolean := TRUE;	-- update NZ flags by default
begin
   case OP is
   	when LDA => res := '0'&Md; A <= res(7 downto 0);	
   	when LDX => res := '0'&Md;  X <= res(7 downto 0);
   	when ADD => res := ('0'&A) + ('0'&Md);
       C <= res(8); A <= res(7 downto 0);
   	when ADC =>  res:=  ('0'&A) + ('0'&Md) + C;
        C <= res(8); A <= res(7 downto 0);
   	when SUB =>  res:= ('0'&A) - ('0'&Md);
       C <= res(8); A <= res(7 downto 0);
   	when SBC =>  res:= ('0'&A) - ('0'&Md) - C;
       C <= res(8); A <= res(7 downto 0);
   	when CMP =>  res:= ('0'&A) - ('0'&Md); C <= res(8);
   	when CPX =>   res:= ('0'&X) - ('0'&Md);  C <= res(8);
   	when ANDa => res :=  '0'&(A and Md) ; A <= res(7 downto 0);
   	when BITa => res := '0'&(A and Md); 
   	when ORA => res := '0'&(A or Md);  A <= res(7 downto 0);
   	when EOR => res := '0'&(A xor Md); A <= res(7 downto 0);
   	when others => updateNZ := FALSE;
   end case;
   if updateNZ then N <= res(7);  
      if  res(7 downto 0) = "00000000" then Z <= '1'; else Z <= '0'; end if;
   end if;
end ALU_OP;

