// Created with Corsair v{{ corsair_ver }}
//
// Avalon-MM to Local Bus bridge
//

module {{ module_name }} #(
    parameter ADDR_W = {{ config['address_width'] }},
    parameter DATA_W = {{ config['data_width'] }},
    parameter STRB_W = DATA_W / 8
)(
    input clk,
    input rst,
    // Local Bus
    input                     wready,
    output       [ADDR_W-1:0] waddr,
    output       [DATA_W-1:0] wdata,
    output                    wen,
    output       [STRB_W-1:0] wstrb,
    input        [DATA_W-1:0] rdata,
    input                     rvalid,
    output       [ADDR_W-1:0] raddr,
    output                    ren,
{% macro amm_core(regmap_embed=False) %}
    // Avalon-MM
    input  [ADDR_W-1:0]  address,
    input                read,
    output [DATA_W-1:0]  readdata,
    output               readdatavalid,
    input  [STRB_W-1:0]  byteenable,
    input                write,
    input  [DATA_W-1:0]  writedata,
    output               waitrequest
);
{% if regmap_embed %}
wire              wready;
wire [ADDR_W-1:0] waddr;
wire [DATA_W-1:0] wdata;
wire              wen;
wire [STRB_W-1:0] wstrb;
wire [DATA_W-1:0] rdata;
wire              rvalid;
wire [ADDR_W-1:0] raddr;
wire              ren;
{% endif %}

  assign waddr = address,
         raddr = address;

  assign waitrequest   = ~wready;
  assign readdatavalid = rvalid;

  assign wdata    = writedata,
         readdata = rdata;

  assign wen = write;

  assign wstrb = byteenable;
  reg ren_int;
  {% set rst_type = config['register_reset']%}
  {%- if rst_type == 'async_pos' or rst_type == 'sync_pos' %}
      {% set rst_active = 1%}
  {%- elif rst_type == 'async_neg' or rst_type == 'sync_neg' %}
      {% set rst_active = 0%}
  {%- endif %}
  always @(posedge clk
  {%- if rst_type == 'async_pos' %} or posedge rst)
  {%- elif rst_type == 'async_neg' %} or negedge rst)
  {%- else -%} ) {%- endif %} begin
    if (rst == 1'b{{ rst_active }})
      ren_int <= 1'b0;
    else
    begin
      if (read)
        ren_int <= 1'b1;
      else
        if (rvalid)
          ren_int <= 1'b0;
    end
  end

  assign ren = ren_int;
{% endmacro %}
{{ amm_core() }}
endmodule
