`timescale 1ns / 1ps

module tb_single_port_ram_with_init;

  // Parameters
  parameter DATA_WIDTH = 8;
  parameter ADDR_WIDTH = 9;  // 512 memory locations

  // Signals
  reg clk;
  reg we;
  reg [ADDR_WIDTH-1:0] addr;
  reg [DATA_WIDTH-1:0] data;
  wire [DATA_WIDTH-1:0] q;

  // Instantiate the DUT
  single_port_ram_with_init #(DATA_WIDTH, ADDR_WIDTH) dut (
    .clk(clk),
    .we(we),
    .addr(addr),
    .data(data),
    .q(q)
  );

  // Clock generation
  initial clk = 0;
  always #5 clk = ~clk;

  // Test variables
  integer i;
  reg [DATA_WIDTH-1:0] expected;

  initial begin
    $display("=== RAM 512-Entry Test Start ===");

    // Initialize control signals
    we = 0;
    addr = 0;
    data = 0;
    #20;

    // -------------------------------
    // Write phase: Fill RAM with test values
    for (i = 0; i < 512; i = i + 1) begin
      @(posedge clk);
      addr = i;
      data = (i * 7) % 256;  // generate deterministic data
      we = 1;
    end

    @(posedge clk);
    we = 0;  // turn off write

    // -------------------------------
    // Read & verify phase
    for (i = 0; i < 512; i = i + 1) begin
      @(posedge clk);
      addr = i;

      @(posedge clk);
      #1;
      expected = (i * 7) % 256;
      if (q !== expected)
        $display("ERROR at addr %0d: Got %0h, Expected %0h", i, q, expected);
      else
        $display("PASS at addr %0d: Value = %0h", i, q);
    end

    $display("=== RAM 512-Entry Test Complete ===");
    #10;
    $finish;
  end

endmodule
