// parameterizable sequential crc generator
// This probably could be combinational logic too, though it would be way slow
module crc_gen #(
    parameter CRCBITS=7,
    parameter COMMANDLEN=40,
    parameter POLYNOMIAL='h89
) (
    input clk,
    input reset,
    input start,
    input [COMMANDLEN-1:0] num,
    output logic ready,
    output logic [CRCBITS-1:0] crc
);

logic [$clog2(COMMANDLEN):0] counter;
logic [COMMANDLEN+CRCBITS-1:0] div_reg;

always_ff @(posedge clk) begin
    if (reset) begin
        counter <= 0;
        crc <= 0;
    end
    else if (start) begin
        counter <= COMMANDLEN;
        div_reg <= {num, {CRCBITS{1'b0}}};
        ready <= 0;
    end
    else if (counter != 0) begin
        if (div_reg[counter+CRCBITS-1] == 1) begin
            div_reg <= div_reg ^ (POLYNOMIAL << (counter-1));
        end
        counter <= counter - 1;
    end
    else begin
        ready <= 1;
        crc <= div_reg[CRCBITS-1:0];
    end
end

endmodule
