`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2024/12/12 00:12:11
// Design Name: 
// Module Name: sequence_detector_11001
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module sequence_detector_11001(
    input wire clk,
    input wire reset,
    input wire x,
    output reg z
);
parameter S0 = 3'b000, // Initial
          S1 = 3'b001, // 1
          S2 = 3'b010, // 1-1
          S3 = 3'b011, // 1-1-0
          S4 = 3'b100, // 1-1-0-0
          S5 = 3'b101; // 11001
reg [2:0] state_c, state_n;  // Current state & next state
// Part 1
always @(posedge clk) begin
    if (reset)
        state_c <= S0;  // Reset
    else
        state_c <= state_n;  // Update current state
end
// Part 2
always @(*) begin
    // Keep current state by default
    state_n = state_c;
    case(state_c)
        S0: begin
            if (x)
                state_n = S1;  // If 1 go to S1
            else
                state_n = S0;  // If 0 keep S0
        end
        S1: begin
            if (x)
                state_n = S2;  // If 1 go to S2
            else
                state_n = S0;  // If 0 back to S0
        end
        S2: begin
            if (!x)
                state_n = S3;  // If 0 go to S3
            else
                state_n = S2;  // If 1 keep S2
        end
        S3: begin
            if (!x)
                state_n = S4;  // If 0 go to S4
            else
                state_n = S1;  // If 1 back to S1
        end
        S4: begin
            if (x)
                state_n = S5;  // If 1 go to S5 (11001)
            else
                state_n = S0;  // If 0 back to S0
        end
        S5: begin
            state_n = S0;  // Back to initial state
        end
        default: state_n = S0;
    endcase
end
// Part 3
always @(posedge clk) begin
    if (reset)
        z <= 0;  // Reset output 0
    else
        // S5 output 1
        z <= (state_c == S5);
end
endmodule
