module jesd204_ilas_monitor #(
  parameter DATA_PATH_WIDTH = 4
) (
  input clk,
  input reset,

  input [DATA_PATH_WIDTH*8-1:0] data,
  input [DATA_PATH_WIDTH-1:0] charisk28,

  output reg ilas_config_valid,
  output reg [1:0] ilas_config_addr,
  output reg [DATA_PATH_WIDTH*8-1:0] ilas_config_data,

  output data_ready_n
);

reg [3:0] multi_frame_counter = 'h00;
reg [7:0] frame_counter = 'h00;
reg [7:0] length = 'h00;

localparam STATE_ILAS = 1'b1;
localparam STATE_DATA = 1'b0;

reg state = STATE_ILAS;
reg next_state;
reg prev_was_last = 1'b0;
reg frame_length_error = 1'b0;

assign data_ready_n = next_state;

always @(*) begin
  next_state = state;
  if (reset == 1'b0 && prev_was_last == 1'b1) begin
    if (charisk28[0] != 1'b1 || data[7:5] != 3'h0) begin
      next_state = STATE_DATA;
    end
  end
end

always @(posedge clk) begin
  if (reset == 1'b1) begin
    state <= STATE_ILAS;
  end else begin
    state <= next_state;
  end
end

always @(posedge clk) begin
  if (reset == 1'b1 || (charisk28[3] == 1'b1 && data[31:29] == 3'h3)) begin
    prev_was_last <= 1'b1;
  end else begin
    prev_was_last <= 1'b0;
  end
end

always @(posedge clk) begin
  if (reset == 1'b1) begin
    multi_frame_counter <= 'h00;
  end else if (charisk28[0] == 1'b1 && data[7:5] == 3'h0 && state == STATE_ILAS) begin
    multi_frame_counter <= multi_frame_counter + 1'b1;
  end
end

always @(posedge clk) begin
  if (reset == 1'b1) begin
    length <= 'h00;
  end else if (prev_was_last == 1'b1) begin
    if (length == 'h00) begin
      length <= frame_counter;
    end
  end
end

always @(posedge clk) begin
  frame_length_error <= 1'b0;
  if (prev_was_last == 1'b1) begin
    if (length != 'h00 && length != frame_counter) begin
      frame_length_error <= 1'b1;
    end
  end
end

always @(posedge clk) begin
  if (prev_was_last == 1'b1) begin
    frame_counter <= 'h00;
  end else begin
    frame_counter <= frame_counter + 1'b1;
  end
end

always @(posedge clk) begin
  if (reset == 1'b1) begin
    ilas_config_valid <= 1'b0;
  end else if (state == STATE_ILAS) begin
    if (charisk28[1] == 1'b1 && data[15:13] == 3'h4) begin
      ilas_config_valid <= 1'b1;
    end else if (ilas_config_addr == 'h3) begin
      ilas_config_valid <= 1'b0;
    end
  end
end

always @(posedge clk) begin
  if (ilas_config_valid == 1'b0) begin
    ilas_config_addr <= 1'b0;
  end else if (ilas_config_valid == 1'b1) begin
    ilas_config_addr <= ilas_config_addr + 1'b1;
  end
end

always @(posedge clk) begin
  ilas_config_data <= data;
end

endmodule