library ieee;
use ieee.std_logic_1164.all;

use std.textio.all;

package mem_utils is
  type mem_t is array(natural range <>) of std_logic_vector (31 downto 0);

  procedure read_mem (mem : out mem_t; filename : string);
end mem_utils;

package body mem_utils is
  procedure read_mem (mem : out mem_t; filename : string)
  is
    FILE f_in  : text;
    variable l : line;
    variable addr : natural;
    variable off : natural;
    variable byte : std_logic_vector (0 to 7);
  begin
    --  Read mem
    file_open(f_in, filename, read_mode);

    addr := 0;
    off := 0;
    while not endfile(f_in) loop
      readline (f_in, l);

      assert l'length = 8;
      for j in 0 to 7 loop
        if l(l'left + j) = '1' then
          byte(j) := '1';
        elsif l(l'left + j) = '0' then
          byte(j) := '0';
        else
          assert false severity error;
        end if;
      end loop;

      mem (addr)(off + 7 downto off) := byte;
      if off = 24 then
        off := 0;
        addr := addr + 1;
      else
        off := off + 8;
      end if;
    end loop;
    file_close(f_in);
  end read_mem;

end mem_utils;