module jesd204_tx_lane #(
  parameter DATA_PATH_WIDTH = 4
) (
  input clk,

  input [DATA_PATH_WIDTH-1:0] eof,
  input eomf,

  input cgs_enable,

  input [DATA_PATH_WIDTH*8-1:0] ilas_data,
  input [DATA_PATH_WIDTH-1:0] ilas_charisk,

  input [DATA_PATH_WIDTH*8-1:0] tx_data,
  input tx_ready,

  output reg [DATA_PATH_WIDTH*8-1:0] phy_data,
  output reg [DATA_PATH_WIDTH-1:0] phy_charisk,

  input cfg_disable_scrambler
);

wire [DATA_PATH_WIDTH*8-1:0] scrambled_data;
wire [7:0] scrambled_char[0:DATA_PATH_WIDTH-1];
reg [7:0] char_align[0:DATA_PATH_WIDTH-1];

jesd204_scrambler #(
  .WIDTH(DATA_PATH_WIDTH*8),
  .DESCRAMBLE(0)
) i_scrambler (
  .clk(clk),
  .reset(~tx_ready),
  .enable(~cfg_disable_scrambler),
  .data_in(tx_data),
  .data_out(scrambled_data)
);

generate
genvar i;

for (i = 0; i < DATA_PATH_WIDTH; i = i + 1) begin: gen_char
  assign scrambled_char[i] = scrambled_data[i*8+7:i*8];

  always @(*) begin
    if (i == DATA_PATH_WIDTH-1 && eomf == 1'b1) begin
      char_align[i] = 8'h7c; // /A/
    end else begin
      char_align[i] = 8'hfc; // /F/
    end
  end

  always @(posedge clk) begin
    if (cgs_enable == 1'b1) begin
      phy_charisk[i] <= 1'b1;
    end else if (eof[i] == 1'b1 && scrambled_char[i] == char_align[i]) begin
      phy_charisk[i] <= 1'b1;
    end else begin
      phy_charisk[i] <= ilas_charisk[i];
    end
  end
end

endgenerate

always @(posedge clk) begin
  if (cgs_enable == 1'b1) begin
    phy_data <= {DATA_PATH_WIDTH{8'hbc}};
  end else begin
    phy_data <= (tx_ready) ? scrambled_data : ilas_data;
  end
end

endmodule