Implement in Verilog the following circuit: A two-input XNOR (connected to 'in1' and 'in2) has an output connected to the input of a two-input XOR. The second input of the XOR is 'in3.' The output of the XOR is 'out'.

module top_module (
	input in1,
	input in2,
	input in3,
	output logic out
);

	assign out = (~(in1 ^ in2)) ^ in3;
endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input in1,
	input in2,
	input in3,
	output logic out
);

	assign out = (~(in1 ^ in2)) ^ in3;
endmodule

module stimulus_gen (
	input clk,
	output logic in1, in2, in3
);

	initial begin
		repeat(100) @(posedge clk, negedge clk) begin
			{in1, in2, in3} <= $random;
		end

		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_out;
		int errortime_out;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic in1;
	logic in2;
	logic in3;
	logic out_ref;
	logic out_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,in1,in2,in3,out_ref,out_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.in1,
		.in2,
		.in3 );
	reference_module good1 (
		.in1,
		.in2,
		.in3,
		.out(out_ref) );

	top_module top_module1 (
		.in1,
		.in2,
		.in3,
		.out(out_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_out) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "out", stats1.errors_out, stats1.errortime_out);
		else $display("Hint: Output '%s' has no mismatches.", "out");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { out_ref } === ( { out_ref } ^ { out_dut } ^ { out_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (out_ref !== ( out_ref ^ out_dut ^ out_ref ))
		begin if (stats1.errors_out == 0) stats1.errortime_out = $time;
			stats1.errors_out = stats1.errors_out+1'b1; end

	end
endmodule


For the following Karnaugh map, give the circuit implementation using one 4-to-1 multiplexer and as many 2-to-1 multiplexers as required, but using as few as possible. You are not allowed to use any other logic gate and you must use _a_ and _b_ as the multiplexer selector inputs, as shown on the 4-to-1 multiplexer below.

//       ab
// cd   00 01 11 10
//  00 | 0 | 0 | 0 | 1 |
//  01 | 1 | 0 | 0 | 0 |
//  11 | 1 | 0 | 1 | 1 |
//  10 | 1 | 0 | 0 | 1 |

// Consider a block diagram with inputs 'c' and 'd' going into a module called "top_module". This "top_module" has four outputs, mux_in[3:0], that connect to a four input mux. The mux takes as input {a,b} and ab = 00 is connected to mux_in[0], ab=01 is connected to mux_in[1], and so in. You are implementing in Verilog just the portion labelled "top_module", such that the entire circuit (including the 4-to-1 mux) implements the K-map.

module top_module (
	input c,
	input d,
	output [3:0] mux_in
);

	assign mux_in[0] = c | d;
	assign mux_in[1] = 0;
	assign mux_in[2] = ~d;
	assign mux_in[3] = c&d;

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input c,
	input d,
	output [3:0] mux_in
);

	assign mux_in[0] = c | d;
	assign mux_in[1] = 0;
	assign mux_in[2] = ~d;
	assign mux_in[3] = c&d;

endmodule

module stimulus_gen (
	input clk,
	output logic c, d,
	output reg[511:0] wavedrom_title,
	output reg wavedrom_enable
);

// Add two ports to module stimulus_gen:
//    output [511:0] wavedrom_title
//    output reg wavedrom_enable

	task wavedrom_start(input[511:0] title = "");
	endtask

	task wavedrom_stop;
		#1;
	endtask

	initial begin
		{c, d} <= 0;
		@(negedge clk) wavedrom_start();
			@(posedge clk) {c, d} <= 2'h0;
			@(posedge clk) {c, d} <= 2'h1;
			@(posedge clk) {c, d} <= 2'h2;
			@(posedge clk) {c, d} <= 2'h3;
		@(negedge clk) wavedrom_stop();
		repeat(50) @(posedge clk, negedge clk)
			{c,d} <= $random;

		$finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_mux_in;
		int errortime_mux_in;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic c;
	logic d;
	logic [3:0] mux_in_ref;
	logic [3:0] mux_in_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,c,d,mux_in_ref,mux_in_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.c,
		.d );
	reference_module good1 (
		.c,
		.d,
		.mux_in(mux_in_ref) );

	top_module top_module1 (
		.c,
		.d,
		.mux_in(mux_in_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_mux_in) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "mux_in", stats1.errors_mux_in, stats1.errortime_mux_in);
		else $display("Hint: Output '%s' has no mismatches.", "mux_in");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { mux_in_ref } === ( { mux_in_ref } ^ { mux_in_dut } ^ { mux_in_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (mux_in_ref !== ( mux_in_ref ^ mux_in_dut ^ mux_in_ref ))
		begin if (stats1.errors_mux_in == 0) stats1.errortime_mux_in = $time;
			stats1.errors_mux_in = stats1.errors_mux_in+1'b1; end

	end
endmodule


The following diagram is a Mealy machine implementation of the 2's complementer. Implement in Verilog using one-hot encoding. Resets into state A and reset is asynchronous active-high.

// A --x=0 (z=0)--> A
// A --x=1 (z=1)--> B
// B --x=0 (z=1)--> B
// B --x=1 (z=0)--> B

module top_module (
	input clk,
	input areset,
	input x,
	output z
);

	parameter A=0,B=1;
	reg state;
	always @(posedge clk, posedge areset) begin
		if (areset)
			state <= A;
		else begin
			case (state)
				A: state <= x ? B : A;
				B: state <= B;
			endcase
		end
	end

	assign z = (state == A && x==1) | (state == B && x==0);

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input areset,
	input x,
	output z
);

	parameter A=0,B=1;
	reg state;
	always @(posedge clk, posedge areset) begin
		if (areset)
			state <= A;
		else begin
			case (state)
				A: state <= x ? B : A;
				B: state <= B;
			endcase
		end
	end

	assign z = (state == A && x==1) | (state == B && x==0);

endmodule

module stimulus_gen (
	input clk,
	output logic x,
	output logic areset,
	output reg[511:0] wavedrom_title,
	output reg wavedrom_enable,
	input tb_match
);
	reg reset;
	assign areset = reset;

// Add two ports to module stimulus_gen:
//    output [511:0] wavedrom_title
//    output reg wavedrom_enable

	task wavedrom_start(input[511:0] title = "");
	endtask

	task wavedrom_stop;
		#1;
	endtask

	task reset_test(input async=0);
		bit arfail, srfail, datafail;

		@(posedge clk);
		@(posedge clk) reset <= 0;
		repeat(3) @(posedge clk);

		@(negedge clk) begin datafail = !tb_match ; reset <= 1; end
		@(posedge clk) arfail = !tb_match;
		@(posedge clk) begin
			srfail = !tb_match;
			reset <= 0;
		end
		if (srfail)
			$display("Hint: Your reset doesn't seem to be working.");
		else if (arfail && (async || !datafail))
			$display("Hint: Your reset should be %0s, but doesn't appear to be.", async ? "asynchronous" : "synchronous");
		// Don't warn about synchronous reset if the half-cycle before is already wrong. It's more likely
		// a functionality error than the reset being implemented asynchronously.

	endtask

	initial begin
		x <= 0;
		reset <= 1;
		@(posedge clk) reset <= 0; x <= 1;
		@(posedge clk) x <= 0;
		reset_test(1);

		@(negedge clk) wavedrom_start();
			@(posedge clk) {reset,x} <= 2'h2;
			@(posedge clk) {reset,x} <= 2'h0;
			@(posedge clk) {reset,x} <= 2'h0;
			@(posedge clk) {reset,x} <= 2'h1;
			@(posedge clk) {reset,x} <= 2'h0;
			@(posedge clk) {reset,x} <= 2'h1;
			@(posedge clk) {reset,x} <= 2'h1;
			@(posedge clk) {reset,x} <= 2'h0;
			@(posedge clk) {reset,x} <= 2'h0;
		@(negedge clk) wavedrom_stop();
		repeat(400) @(posedge clk, negedge clk)
			{reset,x} <= {($random&31) == 0, ($random&1)==0 };

		$finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_z;
		int errortime_z;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic areset;
	logic x;
	logic z_ref;
	logic z_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,areset,x,z_ref,z_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.areset,
		.x );
	reference_module good1 (
		.clk,
		.areset,
		.x,
		.z(z_ref) );

	top_module top_module1 (
		.clk,
		.areset,
		.x,
		.z(z_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_z) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "z", stats1.errors_z, stats1.errortime_z);
		else $display("Hint: Output '%s' has no mismatches.", "z");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { z_ref } === ( { z_ref } ^ { z_dut } ^ { z_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (z_ref !== ( z_ref ^ z_dut ^ z_ref ))
		begin if (stats1.errors_z == 0) stats1.errortime_z = $time;
			stats1.errors_z = stats1.errors_z+1'b1; end

	end
endmodule


This is a sequential circuit. The circuit consists of combinational logic and one bit of memory (i.e., one flip-flop). The output of the flip-flop has been made observable through the output state.

// Read the simulation waveforms to determine what the circuit does, then implement it.

// time            clk             a               b               state           q
// 0ns             0               1               x               x               x
// 5ns             1               1               x               x               x
// 10ns            0               0               0               x               x
// 15ns            1               0               0               0               0
// 20ns            0               0               0               0               0
// 25ns            1               0               0               0               0
// 30ns            0               0               0               0               0
// 35ns            1               0               0               0               0
// 40ns            0               0               0               0               0
// 45ns            1               0               1               0               1
// 50ns            0               0               1               0               1
// 55ns            1               1               0               0               1
// 60ns            0               1               0               0               1
// 65ns            1               1               1               0               0
// 70ns            0               1               1               0               0
// 75ns            1               0               0               1               1
// 80ns            0               0               0               1               1
// 85ns            1               1               1               0               0
// 90ns            0               1               1               0               0
// 95ns            1               1               1               1               1
// 100ns           0               1               1               1               1
// 105ns           1               1               1               1               1
// 110ns           0               1               1               1               1
// 115ns           1               1               0               1               0
// 120ns           0               1               0               1               0
// 125ns           1               0               1               1               0
// 130ns           0               0               1               1               0
// 135ns           1               0               0               1               1
// 140ns           0               0               0               1               1
// 145ns           1               0               0               0               0
// 150ns           0               0               0               0               0
// 155ns           1               0               0               0               0
// 160ns           0               0               0               0               0
// 165ns           1               0               0               0               0
// 170ns           0               0               0               0               0
// 175ns           1               0               0               0               0
// 180ns           0               0               0               0               0
// 185ns           1               0               0               0               0
// 190ns           0               0               0               0               0

module top_module (
	input clk,
	input a,
	input b,
	output q,
	output state
);

	reg c;
	always @(posedge clk)
		c <= a&b | a&c | b&c;

	assign q = a^b^c;
	assign state = c;

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input a,
	input b,
	output q,
	output state
);

	reg c;
	always @(posedge clk)
		c <= a&b | a&c | b&c;

	assign q = a^b^c;
	assign state = c;

endmodule

module stimulus_gen (
	input clk,
	output logic a,
	output logic b,
	output reg[511:0] wavedrom_title,
	output reg wavedrom_enable
);

// Add two ports to module stimulus_gen:
//    output [511:0] wavedrom_title
//    output reg wavedrom_enable

	task wavedrom_start(input[511:0] title = "");
	endtask

	task wavedrom_stop;
		#1;
	endtask

	initial begin
		a <= 1;
		@(negedge clk) {a,b} <= 0;
		@(negedge clk) wavedrom_start("Unknown circuit");
			repeat(3) @(posedge clk);
			{a,b} <= 1;
			@(posedge clk) {a,b} <= 2;
			@(posedge clk) {a,b} <= 3;
			@(posedge clk) {a,b} <= 0;
			@(posedge clk) {a,b} <= 3;
			@(posedge clk) {a,b} <= 3;
			@(posedge clk) {a,b} <= 3;
			@(posedge clk) {a,b} <= 2;
			@(posedge clk) {a,b} <= 1;
			@(posedge clk) {a,b} <= 0;
			@(posedge clk) {a,b} <= 0;
			@(posedge clk) {a,b} <= 0;
			@(negedge clk);
		wavedrom_stop();

		repeat(200) @(posedge clk, negedge clk)
			a <= &((5)'($urandom));
		$finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_q;
		int errortime_q;
		int errors_state;
		int errortime_state;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic a;
	logic b;
	logic q_ref;
	logic q_dut;
	logic state_ref;
	logic state_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,a,b,q_ref,q_dut,state_ref,state_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.a,
		.b );
	reference_module good1 (
		.clk,
		.a,
		.b,
		.q(q_ref),
		.state(state_ref) );

	top_module top_module1 (
		.clk,
		.a,
		.b,
		.q(q_dut),
		.state(state_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_q) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "q", stats1.errors_q, stats1.errortime_q);
		else $display("Hint: Output '%s' has no mismatches.", "q");
		if (stats1.errors_state) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "state", stats1.errors_state, stats1.errortime_state);
		else $display("Hint: Output '%s' has no mismatches.", "state");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { q_ref, state_ref } === ( { q_ref, state_ref } ^ { q_dut, state_dut } ^ { q_ref, state_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (q_ref !== ( q_ref ^ q_dut ^ q_ref ))
		begin if (stats1.errors_q == 0) stats1.errortime_q = $time;
			stats1.errors_q = stats1.errors_q+1'b1; end
		if (state_ref !== ( state_ref ^ state_dut ^ state_ref ))
		begin if (stats1.errors_state == 0) stats1.errortime_state = $time;
			stats1.errors_state = stats1.errors_state+1'b1; end

	end
endmodule


Consider the function f shown in the Karnaugh map below. Implement this function.
//        x[1]x[2]
// x[3]x[4]   00 01 11 10
//  00 | 1 | 0 | 0 | 1 |
//  01 | 0 | 0 | 0 | 0 |
//  11 | 1 | 1 | 1 | 0 |
//  10 | 1 | 1 | 0 | 1 |

module top_module (
	input [4:1] x,
	output logic f
);

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input [4:1] x,
	output logic f
);

	always_comb begin
		case (x)
			4'h0: f = 1;
			4'h1: f = 1;
			4'h2: f = 0;
			4'h3: f = 0;
			4'h4: f = 1;
			4'h5: f = 1;
			4'h6: f = 1;
			4'h7: f = 0;
			4'h8: f = 0;
			4'h9: f = 0;
			4'ha: f = 0;
			4'hb: f = 0;
			4'hc: f = 1;
			4'hd: f = 0;
			4'he: f = 1;
			4'hf: f = 1;
		endcase
	end

endmodule

module stimulus_gen (
	input clk,
	output logic [4:1] x
);

	initial begin
		repeat(100) @(posedge clk, negedge clk) begin
			x <= $random;
		end

		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_f;
		int errortime_f;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic [4:1] x;
	logic f_ref;
	logic f_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,x,f_ref,f_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.x );
	reference_module good1 (
		.x,
		.f(f_ref) );

	top_module top_module1 (
		.x,
		.f(f_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_f) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "f", stats1.errors_f, stats1.errortime_f);
		else $display("Hint: Output '%s' has no mismatches.", "f");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { f_ref } === ( { f_ref } ^ { f_dut } ^ { f_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (f_ref !== ( f_ref ^ f_dut ^ f_ref ))
		begin if (stats1.errors_f == 0) stats1.errortime_f = $time;
			stats1.errors_f = stats1.errors_f+1'b1; end

	end
endmodule


Synchronous HDLC framing involves decoding a continuous bit stream of data to look for bit patterns that indicate the beginning and end of frames (packets). Seeing exactly 6 consecutive 1s (i.e., 01111110) is a "flag" that indicate frame boundaries. To avoid the data stream from accidentally containing "flags", the sender inserts a zero after every 5 consecutive 1s which the receiver must detect and discard. We also need to signal an error if there are 7 or more consecutive 1s. Create a Moore-type finite state machine to recognize these three sequences:

// (1) 0111110: Signal a bit needs to be discarded (disc).
// (2) 01111110: Flag the beginning/end of a frame (flag).
// (3) 01111111...: Error (7 or more 1s) (err).

// When the FSM is reset, it should be in a state that behaves as though the previous input were 0. The reset signal is active high synchronous. The output signals should be asserted for a complete cycle beginning on the clock cycle after the condition occurs.

module top_module (
	input clk,
	input reset,
	input in,
	output disc,
	output flag,
	output err);

	parameter [3:0] S0=0, S1=1, S2=2, S3=3, S4=4, S5=5, S6=6, SERR=7, SDISC=8, SFLAG=9;
	reg [3:0] state, next;

	assign disc = state == SDISC;
	assign flag = state == SFLAG;
	assign err = state == SERR;

	always @(posedge clk) begin
		case (state)
			S0: state <= in ? S1 : S0;
			S1: state <= in ? S2 : S0;
			S2: state <= in ? S3 : S0;
			S3: state <= in ? S4 : S0;
			S4: state <= in ? S5 : S0;
			S5: state <= in ? S6 : SDISC;
			S6: state <= in ? SERR : SFLAG;
			SERR: state <= in ? SERR : S0;
			SFLAG: state <= in ? S1 : S0;
			SDISC: state <= in ? S1 : S0;
			default: state <= 'x;
		endcase

		if (reset) state <= S0;
	end

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input reset,
	input in,
	output disc,
	output flag,
	output err);

	parameter [3:0] S0=0, S1=1, S2=2, S3=3, S4=4, S5=5, S6=6, SERR=7, SDISC=8, SFLAG=9;
	reg [3:0] state, next;

	assign disc = state == SDISC;
	assign flag = state == SFLAG;
	assign err = state == SERR;

	always @(posedge clk) begin
		case (state)
			S0: state <= in ? S1 : S0;
			S1: state <= in ? S2 : S0;
			S2: state <= in ? S3 : S0;
			S3: state <= in ? S4 : S0;
			S4: state <= in ? S5 : S0;
			S5: state <= in ? S6 : SDISC;
			S6: state <= in ? SERR : SFLAG;
			SERR: state <= in ? SERR : S0;
			SFLAG: state <= in ? S1 : S0;
			SDISC: state <= in ? S1 : S0;
			default: state <= 'x;
		endcase

		if (reset) state <= S0;
	end

endmodule

module stimulus_gen (
	input clk,
	output logic reset, in
);

	initial begin
		reset <= 1;
		in <= 0;
		@(posedge clk);
		repeat(800) @(posedge clk, negedge clk) begin
			reset <= !($random & 31);
			in <= |($random&7);
		end
		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_disc;
		int errortime_disc;
		int errors_flag;
		int errortime_flag;
		int errors_err;
		int errortime_err;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic reset;
	logic in;
	logic disc_ref;
	logic disc_dut;
	logic flag_ref;
	logic flag_dut;
	logic err_ref;
	logic err_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,reset,in,disc_ref,disc_dut,flag_ref,flag_dut,err_ref,err_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.reset,
		.in );
	reference_module good1 (
		.clk,
		.reset,
		.in,
		.disc(disc_ref),
		.flag(flag_ref),
		.err(err_ref) );

	top_module top_module1 (
		.clk,
		.reset,
		.in,
		.disc(disc_dut),
		.flag(flag_dut),
		.err(err_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_disc) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "disc", stats1.errors_disc, stats1.errortime_disc);
		else $display("Hint: Output '%s' has no mismatches.", "disc");
		if (stats1.errors_flag) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "flag", stats1.errors_flag, stats1.errortime_flag);
		else $display("Hint: Output '%s' has no mismatches.", "flag");
		if (stats1.errors_err) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "err", stats1.errors_err, stats1.errortime_err);
		else $display("Hint: Output '%s' has no mismatches.", "err");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { disc_ref, flag_ref, err_ref } === ( { disc_ref, flag_ref, err_ref } ^ { disc_dut, flag_dut, err_dut } ^ { disc_ref, flag_ref, err_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (disc_ref !== ( disc_ref ^ disc_dut ^ disc_ref ))
		begin if (stats1.errors_disc == 0) stats1.errortime_disc = $time;
			stats1.errors_disc = stats1.errors_disc+1'b1; end
		if (flag_ref !== ( flag_ref ^ flag_dut ^ flag_ref ))
		begin if (stats1.errors_flag == 0) stats1.errortime_flag = $time;
			stats1.errors_flag = stats1.errors_flag+1'b1; end
		if (err_ref !== ( err_ref ^ err_dut ^ err_ref ))
		begin if (stats1.errors_err == 0) stats1.errortime_err = $time;
			stats1.errors_err = stats1.errors_err+1'b1; end

	end
endmodule


We want to create a timer with one input that:

// (1) is started when a particular input pattern (1101) is detected,
// (2) shifts in 4 more bits to determine the duration to delay,
// (3) waits for the counters to finish counting, and
// (4) notifies the user and waits for the user to acknowledge the timer.

// The serial data is available on the data input pin. When the pattern 1101 is received, the circuit must then shift in the next 4 bits, most-significant-bit first. These 4 bits determine the duration of the timer delay, referred to as delay[3:0]. After that, the state machine asserts its counting output to indicate it is counting. Once the 1101 and delay[3:0] have been read, the circuit no longer looks at the data input until it resumes searching after everything else is done.

// The state machine must count for exactly (delay[3:0] + 1) * 1000 clock cycles. e.g., delay=0 means count 1000 cycles, and delay=5 means count 6000 cycles. Also output the current remaining time. This should be equal to delay for 1000 cycles, then delay-1 for 1000 cycles, and so on until it is 0 for 1000 cycles.

// When the circuit isn't counting, the count[3:0] output is don't-care (whatever value is convenient for you to implement). At that point, the circuit must assert done to notify the user the timer has timed out, and waits until input ack is 1 before being reset to look for the next occurrence of the start sequence (1101).

// The circuit should reset into a state where it begins searching for the input sequence 1101. The reset signal is active high synchronous.

module top_module(
	input wire clk,
	input wire reset,
	input wire data,
    output wire [3:0] count,
    output reg counting,
    output reg done,
    input wire ack );

	typedef enum logic[3:0] {
		S, S1, S11, S110, B0, B1, B2, B3, Count, Wait
	} States;

	States state, next;

	reg shift_ena;
	reg [9:0] fcount;
	reg [3:0] scount;
	wire done_counting = (scount == 0) && (fcount == 999);

	always_comb begin
		case (state)
			S: next = States'(data ? S1: S);
			S1: next = States'(data ? S11: S);
			S11: next = States'(data ? S11 : S110);
			S110: next = States'(data ? B0 : S);
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = Count;
			Count: next = States'(done_counting ? Wait : Count);
			Wait: next = States'(ack ? S : Wait);
			default: next = States'(4'bx);
		endcase
	end

	always @(posedge clk) begin
		if (reset) state <= S;
		else state <= next;
	end

	always_comb begin
		shift_ena = 0; counting = 0; done = 0;
		if (state == B0 || state == B1 || state == B2 || state == B3)
			shift_ena = 1;
		if (state == Count)
			counting = 1;
		if (state == Wait)
			done = 1;

		if (|state === 1'bx) begin
			{shift_ena, counting, done} = 'x;
		end
	end

	// Shift register
	always @(posedge clk) begin
		if (shift_ena)
			scount <= {scount[2:0], data};
		else if (counting && fcount == 999)
			scount <= scount - 1'b1;
	end

	// Fast counter
	always @(posedge clk)
		if (!counting)
			fcount <= 10'h0;
		else if (fcount == 999)
			fcount <= 10'h0;
		else
			fcount <= fcount + 1'b1;

	assign count = counting ? scount : 'x;

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
`default_nettype none
module reference_module(
	input wire clk,
	input wire reset,
	input wire data,
    output wire [3:0] count,
    output reg counting,
    output reg done,
    input wire ack );

	typedef enum logic[3:0] {
		S, S1, S11, S110, B0, B1, B2, B3, Count, Wait
	} States;

	States state, next;

	reg shift_ena;
	reg [9:0] fcount;
	reg [3:0] scount;
	wire done_counting = (scount == 0) && (fcount == 999);

	always_comb begin
		case (state)
			S: next = States'(data ? S1: S);
			S1: next = States'(data ? S11: S);
			S11: next = States'(data ? S11 : S110);
			S110: next = States'(data ? B0 : S);
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = Count;
			Count: next = States'(done_counting ? Wait : Count);
			Wait: next = States'(ack ? S : Wait);
			default: next = States'(4'bx);
		endcase
	end

	always @(posedge clk) begin
		if (reset) state <= S;
		else state <= next;
	end

	always_comb begin
		shift_ena = 0; counting = 0; done = 0;
		if (state == B0 || state == B1 || state == B2 || state == B3)
			shift_ena = 1;
		if (state == Count)
			counting = 1;
		if (state == Wait)
			done = 1;

		if (|state === 1'bx) begin
			{shift_ena, counting, done} = 'x;
		end
	end

	// Shift register
	always @(posedge clk) begin
		if (shift_ena)
			scount <= {scount[2:0], data};
		else if (counting && fcount == 999)
			scount <= scount - 1'b1;
	end

	// Fast counter
	always @(posedge clk)
		if (!counting)
			fcount <= 10'h0;
		else if (fcount == 999)
			fcount <= 10'h0;
		else
			fcount <= fcount + 1'b1;

	assign count = counting ? scount : 'x;

endmodule

module stimulus_gen (
	input wire clk,
	output reg reset,
	output reg data,
	output reg ack,
	input wire tb_match,
	input wire counting_dut
);
	bit failed = 0;
	int counting_cycles = 0;

	always @(posedge clk, negedge clk)
		if (!tb_match)
			failed <= 1;

	always @(posedge clk)
		if (counting_dut)
			counting_cycles++;

	initial begin

		@(posedge clk);
		failed <= 0;
		reset <= 1;
		data <= 0;
		ack <= 1'bx;
		@(posedge clk)
			data <= 1;
			reset <= 0;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 1;
		@(posedge clk) data <= 1;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 1;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 1;
		@(posedge clk);
			data <= 1'bx;
		repeat(2000) @(posedge clk);
			ack <= 1'b0;
		repeat(3) @(posedge clk);
			ack <= 1'b1;
		@(posedge clk);
			ack <= 1'b0;
			data <= 1'b1;
		if (counting_cycles != 2000)
			$display("Hint: The first test case should count for 2000 cycles. Your circuit counted %0d", counting_cycles);
		counting_cycles <= 0;
		@(posedge clk);
			ack <= 1'bx;
			data <= 1'b1;
		@(posedge clk);
			data <= 1'b0;
		@(posedge clk);
			data <= 1'b1;
		@(posedge clk);	data <= 1'b1;
		@(posedge clk);	data <= 1'b1;
		@(posedge clk);	data <= 1'b1;
		@(posedge clk);	data <= 1'b0;
		repeat(14800) @(posedge clk);
		ack <= 1'b0;
		repeat(400) @(posedge clk);

		if (counting_cycles != 15000)
			$display("Hint: The second test case should count for 15000 cycles. Your circuit counted %0d", counting_cycles);
		counting_cycles <= 0;

		if (failed)
			$display("Hint: Your FSM didn't pass the sample timing diagram posted with the problem statement. Perhaps try debugging that?");

		repeat(1000) @(posedge clk, negedge clk) begin
			reset <= !($random & 8191);
			data <= $random;
			ack <= !($random & 31);
		end
		repeat(100000) @(posedge clk) begin
			reset <= !($random & 8191);
			data <= $random;
			ack <= !($random & 31);
		end

		#1 $finish;
	end

endmodule
module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_count;
		int errortime_count;
		int errors_counting;
		int errortime_counting;
		int errors_done;
		int errortime_done;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic reset;
	logic data;
	logic ack;
	logic [3:0] count_ref;
	logic [3:0] count_dut;
	logic counting_ref;
	logic counting_dut;
	logic done_ref;
	logic done_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,reset,data,ack,count_ref,count_dut,counting_ref,counting_dut,done_ref,done_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.reset,
		.data,
		.ack );
	reference_module good1 (
		.clk,
		.reset,
		.data,
		.ack,
		.count(count_ref),
		.counting(counting_ref),
		.done(done_ref) );

	top_module top_module1 (
		.clk,
		.reset,
		.data,
		.ack,
		.count(count_dut),
		.counting(counting_dut),
		.done(done_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_count) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "count", stats1.errors_count, stats1.errortime_count);
		else $display("Hint: Output '%s' has no mismatches.", "count");
		if (stats1.errors_counting) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "counting", stats1.errors_counting, stats1.errortime_counting);
		else $display("Hint: Output '%s' has no mismatches.", "counting");
		if (stats1.errors_done) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "done", stats1.errors_done, stats1.errortime_done);
		else $display("Hint: Output '%s' has no mismatches.", "done");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { count_ref, counting_ref, done_ref } === ( { count_ref, counting_ref, done_ref } ^ { count_dut, counting_dut, done_dut } ^ { count_ref, counting_ref, done_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (count_ref !== ( count_ref ^ count_dut ^ count_ref ))
		begin if (stats1.errors_count == 0) stats1.errortime_count = $time;
			stats1.errors_count = stats1.errors_count+1'b1; end
		if (counting_ref !== ( counting_ref ^ counting_dut ^ counting_ref ))
		begin if (stats1.errors_counting == 0) stats1.errortime_counting = $time;
			stats1.errors_counting = stats1.errors_counting+1'b1; end
		if (done_ref !== ( done_ref ^ done_dut ^ done_ref ))
		begin if (stats1.errors_done == 0) stats1.errortime_done = $time;
			stats1.errors_done = stats1.errors_done+1'b1; end

	end
endmodule


A large reservior of water serves several users. In order to keep the level of water succificently high, three sensors are placed vertically at 5-inch intervals. When the water level is above the highest sensor s[3], the input flow rate should be zero. When the level is below the lowest sensor s[1], the flow rate should be at maximum (both Nominal flow valve and Supplemental flow valve opened). The flow rate when the level is between the upper and lower sensors is determined by two factors: the water level and the level previous to the last sensor change. Each water level has a nominal flow rate associated with it as show in the table below. If the sensor change indicates that the previous level was lower than the current level, the flow rate should be increased by opening the Supplemental flow valve (controlled by dfr).
// Water Level | Sensors Asserted | Nominal Flow Rate Inputs to be Asserted
// Above s[3] | s[1], s[2], s[3] | None
// Between s[3] and s[2] | s[1], s[2] | fr1
// Between s[2] and s[1]  | s[1] | fr1, fr2
// Below s[1] | None | fr1, fr2, fr3
// Also include an active-high synchronous reset that resets the state machine to a state equivalent to if the water level had been low for a long time (no sensors asserted, and all four outputs asserted).

module top_module (
	input clk,
	input reset,
	input [3:1] s,
	output reg fr3,
	output reg fr2,
	output reg fr1,
	output reg dfr
);
	parameter A2=0, B1=1, B2=2, C1=3, C2=4, D1=5;
	reg [2:0] state, next;

	always @(posedge clk) begin
		if (reset) state <= A2;
		else state <= next;
	end

	always@(*) begin
		case (state)
			A2: next = s[1] ? B1 : A2;
			B1: next = s[2] ? C1 : (s[1] ? B1 : A2);
			B2: next = s[2] ? C1 : (s[1] ? B2 : A2);
			C1: next = s[3] ? D1 : (s[2] ? C1 : B2);
			C2: next = s[3] ? D1 : (s[2] ? C2 : B2);
			D1: next = s[3] ? D1 : C2;
			default: next = 'x;
		endcase
	end
	reg [3:0] fr;
	assign {fr3, fr2, fr1, dfr} = fr;
	always_comb begin
		case (state)
			A2: fr = 4'b1111;
			B1: fr = 4'b0110;
			B2: fr = 4'b0111;
			C1: fr = 4'b0010;
			C2: fr = 4'b0011;
			D1: fr = 4'b0000;
			default: fr = 'x;
		endcase
	end

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input reset,
	input [3:1] s,
	output reg fr3,
	output reg fr2,
	output reg fr1,
	output reg dfr
);
	parameter A2=0, B1=1, B2=2, C1=3, C2=4, D1=5;
	reg [2:0] state, next;

	always @(posedge clk) begin
		if (reset) state <= A2;
		else state <= next;
	end

	always@(*) begin
		case (state)
			A2: next = s[1] ? B1 : A2;
			B1: next = s[2] ? C1 : (s[1] ? B1 : A2);
			B2: next = s[2] ? C1 : (s[1] ? B2 : A2);
			C1: next = s[3] ? D1 : (s[2] ? C1 : B2);
			C2: next = s[3] ? D1 : (s[2] ? C2 : B2);
			D1: next = s[3] ? D1 : C2;
			default: next = 'x;
		endcase
	end
	reg [3:0] fr;
	assign {fr3, fr2, fr1, dfr} = fr;
	always_comb begin
		case (state)
			A2: fr = 4'b1111;
			B1: fr = 4'b0110;
			B2: fr = 4'b0111;
			C1: fr = 4'b0010;
			C2: fr = 4'b0011;
			D1: fr = 4'b0000;
			default: fr = 'x;
		endcase
	end

endmodule

module stimulus_gen (
	input clk,
	output logic reset,
	output logic [3:1] s,
	output reg[511:0] wavedrom_title,
	output reg wavedrom_enable,
	input tb_match
);

// Add two ports to module stimulus_gen:
//    output [511:0] wavedrom_title
//    output reg wavedrom_enable

	task wavedrom_start(input[511:0] title = "");
	endtask

	task wavedrom_stop;
		#1;
	endtask

	task reset_test(input async=0);
		bit arfail, srfail, datafail;

		@(posedge clk);
		@(posedge clk) reset <= 0;
		repeat(3) @(posedge clk);

		@(negedge clk) begin datafail = !tb_match ; reset <= 1; end
		@(posedge clk) arfail = !tb_match;
		@(posedge clk) begin
			srfail = !tb_match;
			reset <= 0;
		end
		if (srfail)
			$display("Hint: Your reset doesn't seem to be working.");
		else if (arfail && (async || !datafail))
			$display("Hint: Your reset should be %0s, but doesn't appear to be.", async ? "asynchronous" : "synchronous");
		// Don't warn about synchronous reset if the half-cycle before is already wrong. It's more likely
		// a functionality error than the reset being implemented asynchronously.

	endtask

	wire [3:0][2:0] val = { 3'h7, 3'h3, 3'h1, 3'h0 };
	integer sval;
	initial begin
		reset <= 1;
		s <= 1;
		reset_test();

		@(posedge clk) s <= 0;
		@(posedge clk) s <= 0;
		@(negedge clk) wavedrom_start("Water rises to highest level, then down to lowest level.");
			@(posedge clk) s <= 0;
			@(posedge clk) s <= 1;
			@(posedge clk) s <= 3;
			@(posedge clk) s <= 7;
			@(posedge clk) s <= 7;
			@(posedge clk) s <= 3;
			@(posedge clk) s <= 3;
			@(posedge clk) s <= 1;
			@(posedge clk) s <= 1;
			@(posedge clk) s <= 0;
			@(posedge clk) s <= 0;
		@(negedge clk) wavedrom_stop();

		sval = 0;
		repeat(1000) begin
			@(posedge clk);
				sval = sval + (sval == 3 ? 0 : $random&1);
				s <= val[sval];
			@(negedge clk);
				sval = sval - (sval == 0 ? 0 : $random&1);
				s <= val[sval];
		end

		$finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_fr3;
		int errortime_fr3;
		int errors_fr2;
		int errortime_fr2;
		int errors_fr1;
		int errortime_fr1;
		int errors_dfr;
		int errortime_dfr;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic reset;
	logic [3:1] s;
	logic fr3_ref;
	logic fr3_dut;
	logic fr2_ref;
	logic fr2_dut;
	logic fr1_ref;
	logic fr1_dut;
	logic dfr_ref;
	logic dfr_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,reset,s,fr3_ref,fr3_dut,fr2_ref,fr2_dut,fr1_ref,fr1_dut,dfr_ref,dfr_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.reset,
		.s );
	reference_module good1 (
		.clk,
		.reset,
		.s,
		.fr3(fr3_ref),
		.fr2(fr2_ref),
		.fr1(fr1_ref),
		.dfr(dfr_ref) );

	top_module top_module1 (
		.clk,
		.reset,
		.s,
		.fr3(fr3_dut),
		.fr2(fr2_dut),
		.fr1(fr1_dut),
		.dfr(dfr_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_fr3) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "fr3", stats1.errors_fr3, stats1.errortime_fr3);
		else $display("Hint: Output '%s' has no mismatches.", "fr3");
		if (stats1.errors_fr2) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "fr2", stats1.errors_fr2, stats1.errortime_fr2);
		else $display("Hint: Output '%s' has no mismatches.", "fr2");
		if (stats1.errors_fr1) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "fr1", stats1.errors_fr1, stats1.errortime_fr1);
		else $display("Hint: Output '%s' has no mismatches.", "fr1");
		if (stats1.errors_dfr) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "dfr", stats1.errors_dfr, stats1.errortime_dfr);
		else $display("Hint: Output '%s' has no mismatches.", "dfr");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { fr3_ref, fr2_ref, fr1_ref, dfr_ref } === ( { fr3_ref, fr2_ref, fr1_ref, dfr_ref } ^ { fr3_dut, fr2_dut, fr1_dut, dfr_dut } ^ { fr3_ref, fr2_ref, fr1_ref, dfr_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (fr3_ref !== ( fr3_ref ^ fr3_dut ^ fr3_ref ))
		begin if (stats1.errors_fr3 == 0) stats1.errortime_fr3 = $time;
			stats1.errors_fr3 = stats1.errors_fr3+1'b1; end
		if (fr2_ref !== ( fr2_ref ^ fr2_dut ^ fr2_ref ))
		begin if (stats1.errors_fr2 == 0) stats1.errortime_fr2 = $time;
			stats1.errors_fr2 = stats1.errors_fr2+1'b1; end
		if (fr1_ref !== ( fr1_ref ^ fr1_dut ^ fr1_ref ))
		begin if (stats1.errors_fr1 == 0) stats1.errortime_fr1 = $time;
			stats1.errors_fr1 = stats1.errors_fr1+1'b1; end
		if (dfr_ref !== ( dfr_ref ^ dfr_dut ^ dfr_ref ))
		begin if (stats1.errors_dfr == 0) stats1.errortime_dfr = $time;
			stats1.errors_dfr = stats1.errors_dfr+1'b1; end

	end
endmodule


In many (older) serial communications protocols, each data byte is sent along with a start bit and a stop bit, to help the receiver delimit bytes from the stream of bits. One common scheme is to use one start bit (0), 8 data bits, and 1 stop bit (1). The line is also at logic 1 when nothing is being transmitted (idle). Design a finite state machine that will identify when bytes have been correctly received when given a stream of bits. It needs to identify the start bit, wait for all 8 data bits, then verify that the stop bit was correct. If the stop bit does not appear when expected, the FSM must wait until it finds a stop bit before attempting to receive the next byte. Include a active-high synchronous reset. Note that the serial protocol sends the least significant bit first.

module top_module (
	input clk,
	input in,
	input reset,
	output done
);
	parameter B0=0, B1=1, B2=2, B3=3, B4=4, B5=5, B6=6, B7=7, START=8, STOP=9, DONE=10, ERR=11;
	reg [3:0] state;
	reg [3:0] next;

    always_comb begin
		case (state)
			START: next = in ? START : B0;	// start bit is 0
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = B4;
			B4: next = B5;
			B5: next = B6;
			B6: next = B7;
			B7: next = STOP;
			STOP: next = in ? DONE : ERR;  // stop bit is 1. Idle state is 1.
			DONE: next = in ? START : B0;
			ERR: next = in ? START : ERR;
		endcase
    end

    always @(posedge clk) begin
		if (reset) state <= START;
        else state <= next;
	end

	assign done = (state==DONE);

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input in,
	input reset,
	output done
);
	parameter B0=0, B1=1, B2=2, B3=3, B4=4, B5=5, B6=6, B7=7, START=8, STOP=9, DONE=10, ERR=11;
	reg [3:0] state;
	reg [3:0] next;

    always_comb begin
		case (state)
			START: next = in ? START : B0;	// start bit is 0
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = B4;
			B4: next = B5;
			B5: next = B6;
			B6: next = B7;
			B7: next = STOP;
			STOP: next = in ? DONE : ERR;  // stop bit is 1. Idle state is 1.
			DONE: next = in ? START : B0;
			ERR: next = in ? START : ERR;
		endcase
    end

    always @(posedge clk) begin
		if (reset) state <= START;
        else state <= next;
	end

	assign done = (state==DONE);

endmodule

module stimulus_gen (
	input clk,
	output logic in,
	output logic reset
);

	initial begin
		reset <= 1;
		in <= 1;
		@(posedge clk);
		reset <= 0;
		in <= 0;
		repeat(9) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(9) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(10) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(10) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(9) @(posedge clk);
		in <= 1;
		@(posedge clk);

		repeat(800) @(posedge clk, negedge clk) begin
			in <= $random;
			reset <= !($random & 31);
		end

		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_done;
		int errortime_done;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic in;
	logic reset;
	logic done_ref;
	logic done_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,in,reset,done_ref,done_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.in,
		.reset );
	reference_module good1 (
		.clk,
		.in,
		.reset,
		.done(done_ref) );

	top_module top_module1 (
		.clk,
		.in,
		.reset,
		.done(done_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_done) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "done", stats1.errors_done, stats1.errortime_done);
		else $display("Hint: Output '%s' has no mismatches.", "done");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { done_ref } === ( { done_ref } ^ { done_dut } ^ { done_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (done_ref !== ( done_ref ^ done_dut ^ done_ref ))
		begin if (stats1.errors_done == 0) stats1.errortime_done = $time;
			stats1.errors_done = stats1.errors_done+1'b1; end

	end
endmodule


In many (older) serial communications protocols, each data byte is sent along with a start bit and a stop bit, to help the receiver delimit bytes from the stream of bits. One common scheme is to use one start bit (0), 8 data bits, and 1 stop bit (1). The line is also at logic 1 when nothing is being transmitted (idle). Design a finite state machine that will identify when bytes have been correctly received when given a stream of bits. It needs to identify the start bit, wait for all 8 data bits, then verify that the stop bit was correct. The module will also output the correctly-received data byte. out_byte needs to be valid when done is 1, and is don't-care otherwise.If the stop bit does not appear when expected, the FSM must wait until it finds a stop bit before attempting to receive the next byte. Include a active-high synchronous reset. Note that the serial protocol sends the least significant bit first. It should assert done each time it finds a stop bit.

module top_module (
	input clk,
	input in,
	input reset,
	output [7:0] out_byte,
	output done
);
	parameter B0=0, B1=1, B2=2, B3=3, B4=4, B5=5, B6=6, B7=7, START=8, STOP=9, DONE=10, ERR=11;
	reg [3:0] state;
	reg [3:0] next;

    reg [9:0] byte_r;

    always_comb begin
		case (state)
			START: next = in ? START : B0;	// start bit is 0
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = B4;
			B4: next = B5;
			B5: next = B6;
			B6: next = B7;
			B7: next = STOP;
			STOP: next = in ? DONE : ERR;  // stop bit is 1. Idle state is 1.
			DONE: next = in ? START : B0;
			ERR: next = in ? START : ERR;
		endcase
    end

    always @(posedge clk) begin
		if (reset) state <= START;
        else state <= next;
	end

	always @(posedge clk) begin
		byte_r <= {in, byte_r[9:1]};
	end

	assign done = (state==DONE);
	assign out_byte = done ? byte_r[8:1] : 8'hx;

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input in,
	input reset,
	output [7:0] out_byte,
	output done
);
	parameter B0=0, B1=1, B2=2, B3=3, B4=4, B5=5, B6=6, B7=7, START=8, STOP=9, DONE=10, ERR=11;
	reg [3:0] state;
	reg [3:0] next;

    reg [9:0] byte_r;

    always_comb begin
		case (state)
			START: next = in ? START : B0;	// start bit is 0
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = B4;
			B4: next = B5;
			B5: next = B6;
			B6: next = B7;
			B7: next = STOP;
			STOP: next = in ? DONE : ERR;  // stop bit is 1. Idle state is 1.
			DONE: next = in ? START : B0;
			ERR: next = in ? START : ERR;
		endcase
    end

    always @(posedge clk) begin
		if (reset) state <= START;
        else state <= next;
	end

	always @(posedge clk) begin
		byte_r <= {in, byte_r[9:1]};
	end

	assign done = (state==DONE);
	assign out_byte = done ? byte_r[8:1] : 8'hx;

endmodule

module stimulus_gen (
	input clk,
	output logic in,
	output logic reset
);

	initial begin
		reset <= 1;
		in <= 1;
		@(posedge clk);
		reset <= 0;
		in <= 0;
		repeat(9) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(9) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(10) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(10) @(posedge clk);
		in <= 1;
		@(posedge clk);
		in <= 0;
		repeat(9) @(posedge clk);
		in <= 1;
		@(posedge clk);

		repeat(800) @(posedge clk, negedge clk) begin
			in <= $random;
			reset <= !($random & 31);
		end

		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_out_byte;
		int errortime_out_byte;
		int errors_done;
		int errortime_done;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic in;
	logic reset;
	logic [7:0] out_byte_ref;
	logic [7:0] out_byte_dut;
	logic done_ref;
	logic done_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,in,reset,out_byte_ref,out_byte_dut,done_ref,done_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.in,
		.reset );
	reference_module good1 (
		.clk,
		.in,
		.reset,
		.out_byte(out_byte_ref),
		.done(done_ref) );

	top_module top_module1 (
		.clk,
		.in,
		.reset,
		.out_byte(out_byte_dut),
		.done(done_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_out_byte) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "out_byte", stats1.errors_out_byte, stats1.errortime_out_byte);
		else $display("Hint: Output '%s' has no mismatches.", "out_byte");
		if (stats1.errors_done) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "done", stats1.errors_done, stats1.errortime_done);
		else $display("Hint: Output '%s' has no mismatches.", "done");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { out_byte_ref, done_ref } === ( { out_byte_ref, done_ref } ^ { out_byte_dut, done_dut } ^ { out_byte_ref, done_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (out_byte_ref !== ( out_byte_ref ^ out_byte_dut ^ out_byte_ref ))
		begin if (stats1.errors_out_byte == 0) stats1.errortime_out_byte = $time;
			stats1.errors_out_byte = stats1.errors_out_byte+1'b1; end
		if (done_ref !== ( done_ref ^ done_dut ^ done_ref ))
		begin if (stats1.errors_done == 0) stats1.errortime_done = $time;
			stats1.errors_done = stats1.errors_done+1'b1; end

	end
endmodule


Build a gshare branch predictor with 7-bit pc and 7-bit global history, hashed (using xor) into a 7-bit index. This index accesses a 128-entry table of two-bit saturating counters. The branch predictor should contain a 7-bit global branch history register. The branch predictor has two sets of interfaces: One for doing predictions and one for doing training. The prediction interface is used in the processor's Fetch stage to ask the branch predictor for branch direction predictions for the instructions being fetched. Once these branches proceed down the pipeline and are executed, the true outcomes of the branches become known. The branch predictor is then trained using the actual branch direction outcomes.
// When a branch prediction is requested (predict_valid = 1) for a given pc, the branch predictor produces the predicted branch direction and state of the branch history register used to make the prediction. The branch history register is then updated (at the next positive clock edge) for the predicted branch.
// When training for a branch is requested (train_valid = 1), the branch predictor is told the pc and branch history register value for the branch that is being trained, as well as the actual branch outcome and whether the branch was a misprediction (needing a pipeline flush). Update the pattern history table (PHT) to train the branch predictor to predict this branch more accurately next time. In addition, if the branch being trained is mispredicted, also recover the branch history register to the state immediately after the mispredicting branch completes execution.
// If training for a misprediction and a prediction (for a different, younger instruction) occurs in the same cycle, both operations will want to modify the branch history register. When this happens, training takes precedence, because the branch being predicted will be discarded anyway. If training and prediction of the same PHT entry happen at the same time, the prediction sees the PHT state before training because training only modifies the PHT at the next positive clock edge. The following timing diagram shows the timing when training and predicting PHT entry 0 at the same time. The training request at cycle 4 changes the PHT entry state in cycle 5, but the prediction request in cycle 4 outputs the PHT state at cycle 4, without considering the effect of the training request in cycle 4. Reset is asynchronous active-high.

module top_module(
	input clk,
	input areset,

	input predict_valid,
	input [6:0] predict_pc,
	output predict_taken,
	output [6:0] predict_history,

	input train_valid,
	input train_taken,
	input train_mispredicted,
	input [6:0] train_history,
	input [6:0] train_pc
);
	parameter n = 7;
	logic [1:0] pht [2**n-1:0];

	parameter [1:0] SNT = 0, LNT = 1, LT = 2, ST = 3;

	logic [n-1:0] predict_history_r;
	wire [n-1:0] predict_index = predict_history_r ^ predict_pc;
	wire [n-1:0] train_index = train_history ^ train_pc;

	always@(posedge clk, posedge areset)
		if (areset) begin
			for (integer i=0; i<2**n; i=i+1)
				pht[i] = LNT;
			predict_history_r = 0;
        end	else begin
			if (predict_valid)
				predict_history_r <= {predict_history_r, predict_taken};
			if(train_valid) begin
				if(pht[train_index] < 3 && train_taken)
					pht[train_index] <= pht[train_index] + 1;
				else if(pht[train_index] > 0 && !train_taken)
					pht[train_index] <= pht[train_index] - 1;
				if (train_mispredicted)
					predict_history_r <= {train_history, train_taken};
			end
		end

	assign predict_taken = predict_valid ? pht[predict_index][1] : 1'bx;
	assign predict_history = predict_valid ? predict_history_r : {n{1'bx}};
endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module(
	input clk,
	input areset,

	input predict_valid,
	input [6:0] predict_pc,
	output predict_taken,
	output [6:0] predict_history,

	input train_valid,
	input train_taken,
	input train_mispredicted,
	input [6:0] train_history,
	input [6:0] train_pc
);
	parameter n = 7;
	logic [1:0] pht [2**n-1:0];

	parameter [1:0] SNT = 0, LNT = 1, LT = 2, ST = 3;

	logic [n-1:0] predict_history_r;
	wire [n-1:0] predict_index = predict_history_r ^ predict_pc;
	wire [n-1:0] train_index = train_history ^ train_pc;

	always@(posedge clk, posedge areset)
		if (areset) begin
			for (integer i=0; i<2**n; i=i+1)
				pht[i] = LNT;
			predict_history_r = 0;
        end	else begin
			if (predict_valid)
				predict_history_r <= {predict_history_r, predict_taken};
			if(train_valid) begin
				if(pht[train_index] < 3 && train_taken)
					pht[train_index] <= pht[train_index] + 1;
				else if(pht[train_index] > 0 && !train_taken)
					pht[train_index] <= pht[train_index] - 1;
				if (train_mispredicted)
					predict_history_r <= {train_history, train_taken};
			end
		end

	assign predict_taken = predict_valid ? pht[predict_index][1] : 1'bx;
	assign predict_history = predict_valid ? predict_history_r : {n{1'bx}};
endmodule

module stimulus_gen
#(parameter N=7)
(
	input clk,
	output logic areset,

	output logic predict_valid,
	output [N-1:0] predict_pc,

	output logic train_valid,
	output train_taken,
	output train_mispredicted,
	output [N-1:0] train_history,
	output [N-1:0] train_pc,

	input tb_match,
	output reg[511:0] wavedrom_title,
	output reg wavedrom_enable,
	output int wavedrom_hide_after_time
);

// Add two ports to module stimulus_gen:
//    output [511:0] wavedrom_title
//    output reg wavedrom_enable

	task wavedrom_start(input[511:0] title = "");
	endtask

	task wavedrom_stop;
		#1;
	endtask

	reg reset;
	task reset_test(input async=0);
		bit arfail, srfail, datafail;

		@(posedge clk);
		@(posedge clk) reset <= 0;
		repeat(3) @(posedge clk);

		@(negedge clk) begin datafail = !tb_match ; reset <= 1; end
		@(posedge clk) arfail = !tb_match;
		@(posedge clk) begin
			srfail = !tb_match;
			reset <= 0;
		end
		if (srfail)
			$display("Hint: Your reset doesn't seem to be working.");
		else if (arfail && (async || !datafail))
			$display("Hint: Your reset should be %0s, but doesn't appear to be.", async ? "asynchronous" : "synchronous");
		// Don't warn about synchronous reset if the half-cycle before is already wrong. It's more likely
		// a functionality error than the reset being implemented asynchronously.

	endtask

	assign areset = reset;

	logic [N-1:0] predict_pc_r;
	logic train_taken_r;
	logic train_mispredicted_r;
	logic [N-1:0] train_history_r;
	logic [N-1:0] train_pc_r;

	assign predict_pc = predict_valid ? predict_pc_r : {N{1'bx}};
	assign train_taken = train_valid ? train_taken_r : 1'bx;
	assign train_mispredicted = train_valid ? train_mispredicted_r : 1'bx;
	assign train_history = train_valid ? train_history_r : {N{1'bx}};
	assign train_pc = train_valid ? train_pc_r : {N{1'bx}};

	initial begin
		@(posedge clk) reset <= 1;
		@(posedge clk) reset <= 0;
		predict_valid <= 1;
		train_mispredicted_r <= 1;
		train_history_r <= 7'h7f;
		train_pc_r <= 7'h4;
		train_taken_r <= 1;
		train_valid <= 1;
		predict_valid <= 1;
		predict_pc_r <= 4;

		wavedrom_start("Asynchronous reset");
			reset_test(1); // Test for asynchronous reset
		wavedrom_stop();
		@(posedge clk) reset <= 1;
		predict_valid <= 0;

		wavedrom_start("Training entries (pc = 0xa, history = 0 and 2)");
		predict_pc_r <= 7'ha;
		predict_valid <= 1;

		train_history_r <= 7'h0;
		train_pc_r <= 7'ha;
		train_taken_r <= 1;
		train_valid <= 0;
		train_mispredicted_r <= 0;

		@(negedge clk) reset <= 0;
		@(posedge clk) train_valid <= 1;
		@(posedge clk) train_history_r <= 7'h2;
		@(posedge clk) train_valid <= 0;

		repeat(4) @(posedge clk);
		train_history_r <= 7'h0;
		train_taken_r <= 0;
		train_valid <= 1;
		@(posedge clk) train_valid <= 0;

		repeat(8) @(posedge clk);
		wavedrom_stop();

		@(posedge clk);

		wavedrom_start("History register recovery on misprediction");
		reset <= 1;
		predict_pc_r <= 7'ha;
		predict_valid <= 1;

		train_history_r <= 7'h0;
		train_pc_r <= 7'ha;
		train_taken_r <= 1;
		train_valid <= 0;
		train_mispredicted_r <= 1;

		@(negedge clk) reset <= 0;
		@(posedge clk);
		@(posedge clk) train_valid <= 1;
		@(posedge clk) train_valid <= 0;
		@(posedge clk) train_valid <= 1;
		train_history_r <= 7'h10;
		train_taken_r <= 0;
		@(posedge clk) train_valid <= 0;

		repeat(4) @(posedge clk);
		train_history_r <= 7'h0;
		train_taken_r <= 0;
		train_valid <= 1;
		@(posedge clk) train_valid <= 0;
		@(posedge clk) train_valid <= 1;
		train_history_r <= 7'h20;
		@(posedge clk) train_valid <= 0;

		repeat(3) @(posedge clk);
		wavedrom_stop();

		repeat(1000) @(posedge clk,negedge clk) begin
			{predict_valid, predict_pc_r, train_pc_r, train_taken_r, train_valid} <= {$urandom};
			train_history_r <= $urandom;
			train_mispredicted_r <= !($urandom_range(0,31));
		end

		#1 $finish;
	end

endmodule
module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_predict_taken;
		int errortime_predict_taken;
		int errors_predict_history;
		int errortime_predict_history;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic areset;
	logic predict_valid;
	logic [6:0] predict_pc;
	logic train_valid;
	logic train_taken;
	logic train_mispredicted;
	logic [6:0] train_history;
	logic [6:0] train_pc;
	logic predict_taken_ref;
	logic predict_taken_dut;
	logic [6:0] predict_history_ref;
	logic [6:0] predict_history_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,areset,predict_valid,predict_pc,train_valid,train_taken,train_mispredicted,train_history,train_pc,predict_taken_ref,predict_taken_dut,predict_history_ref,predict_history_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.areset,
		.predict_valid,
		.predict_pc,
		.train_valid,
		.train_taken,
		.train_mispredicted,
		.train_history,
		.train_pc );
	reference_module good1 (
		.clk,
		.areset,
		.predict_valid,
		.predict_pc,
		.train_valid,
		.train_taken,
		.train_mispredicted,
		.train_history,
		.train_pc,
		.predict_taken(predict_taken_ref),
		.predict_history(predict_history_ref) );

	top_module top_module1 (
		.clk,
		.areset,
		.predict_valid,
		.predict_pc,
		.train_valid,
		.train_taken,
		.train_mispredicted,
		.train_history,
		.train_pc,
		.predict_taken(predict_taken_dut),
		.predict_history(predict_history_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_predict_taken) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "predict_taken", stats1.errors_predict_taken, stats1.errortime_predict_taken);
		else $display("Hint: Output '%s' has no mismatches.", "predict_taken");
		if (stats1.errors_predict_history) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "predict_history", stats1.errors_predict_history, stats1.errortime_predict_history);
		else $display("Hint: Output '%s' has no mismatches.", "predict_history");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { predict_taken_ref, predict_history_ref } === ( { predict_taken_ref, predict_history_ref } ^ { predict_taken_dut, predict_history_dut } ^ { predict_taken_ref, predict_history_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (predict_taken_ref !== ( predict_taken_ref ^ predict_taken_dut ^ predict_taken_ref ))
		begin if (stats1.errors_predict_taken == 0) stats1.errortime_predict_taken = $time;
			stats1.errors_predict_taken = stats1.errors_predict_taken+1'b1; end
		if (predict_history_ref !== ( predict_history_ref ^ predict_history_dut ^ predict_history_ref ))
		begin if (stats1.errors_predict_history == 0) stats1.errortime_predict_history = $time;
			stats1.errors_predict_history = stats1.errors_predict_history+1'b1; end

	end
endmodule


The game Lemmings involves critters with fairly simple brains. So simple that we are going to model it using a finite state machine. In the Lemmings' 2D world, Lemmings can be in one of two states: walking left (walk_left is 1) or walking right (walk_right is 1). It will switch directions if it hits an obstacle. In particular, if a Lemming is bumped on the left (by receiving a 1 on bump_left), it will walk right. If it's bumped on the right (by receiving a 1 on bump_right), it will walk left. If it's bumped on both sides at the same time, it will still switch directions.
// In addition to walking left and right and changing direction when bumped, when ground=0, the Lemming will fall and say ""aaah!"". When the ground reappears (ground=1), the Lemming will resume walking in the same direction as before the fall. Being bumped while falling does not affect the walking direction, and being bumped in the same cycle as ground disappears (but not yet falling), or when the ground reappears while still falling, also does not affect the walking direction.
// In addition to walking and falling, Lemmings can sometimes be told to do useful things, like dig (it starts digging when dig=1). A Lemming can dig if it is currently walking on ground (ground=1 and not falling), and will continue digging until it reaches the other side (ground=0). At that point, since there is no ground, it will fall (aaah!), then continue walking in its original direction once it hits ground again. As with falling, being bumped while digging has no effect, and being told to dig when falling or when there is no ground is ignored. (In other words, a walking Lemming can fall, dig, or switch directions. If more than one of these conditions are satisfied, fall has higher precedence than dig, which has higher precedence than switching directions.)
// Although Lemmings can walk, fall, and dig, Lemmings aren't invulnerable. If a Lemming falls for too long then hits the ground, it can splatter. In particular, if a Lemming falls for more than 20 clock cycles then hits the ground, it will splatter and cease walking, falling, or digging (all 4 outputs become 0), forever (Or until the FSM gets reset). There is no upper limit on how far a Lemming can fall before hitting the ground. Lemmings only splatter when hitting the ground; they do not splatter in mid-air.
// Implement a Moore state machine that models this behaviour. areset is positive edge triggered asynchronous reseting the Lemming machine to walk left.

module top_module (
	input clk,
	input areset,
	input bump_left,
	input bump_right,
	input ground,
	input dig,
	output walk_left,
	output walk_right,
	output aaah,
	output digging
);
	parameter WL=0, WR=1, FALLL=2, FALLR=3, DIGL=4, DIGR=5, DEAD=6;
	reg [2:0] state;
	reg [2:0] next;

    reg [4:0] fall_counter;

    always_comb begin
		case (state)
			WL: if (!ground) next = FALLL;
				else if (dig) next = DIGL;
				else if (bump_left) next = WR;
				else next = WL;
			WR:
				if (!ground) next = FALLR;
				else if (dig) next = DIGR;
				else if (bump_right) next = WL;
				else next = WR;
			FALLL: next = ground ? (fall_counter >= 20 ? DEAD : WL) : FALLL;
			FALLR: next = ground ? (fall_counter >= 20 ? DEAD : WR) : FALLR;
			DIGL: next = ground ? DIGL : FALLL;
			DIGR: next = ground ? DIGR : FALLR;
			DEAD: next = DEAD;
		endcase
    end

    always @(posedge clk, posedge areset) begin
		if (areset) state <= WL;
        else state <= next;
	end

	always @(posedge clk) begin
		if (state == FALLL || state == FALLR) begin
			if (fall_counter < 20)
				fall_counter <= fall_counter + 1'b1;
		end
		else
			fall_counter <= 0;
	end

	assign walk_left = (state==WL);
	assign walk_right = (state==WR);
	assign aaah = (state == FALLL) || (state == FALLR);
	assign digging = (state == DIGL) || (state == DIGR);

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module (
	input clk,
	input areset,
	input bump_left,
	input bump_right,
	input ground,
	input dig,
	output walk_left,
	output walk_right,
	output aaah,
	output digging
);
	parameter WL=0, WR=1, FALLL=2, FALLR=3, DIGL=4, DIGR=5, DEAD=6;
	reg [2:0] state;
	reg [2:0] next;

    reg [4:0] fall_counter;

    always_comb begin
		case (state)
			WL: if (!ground) next = FALLL;
				else if (dig) next = DIGL;
				else if (bump_left) next = WR;
				else next = WL;
			WR:
				if (!ground) next = FALLR;
				else if (dig) next = DIGR;
				else if (bump_right) next = WL;
				else next = WR;
			FALLL: next = ground ? (fall_counter >= 20 ? DEAD : WL) : FALLL;
			FALLR: next = ground ? (fall_counter >= 20 ? DEAD : WR) : FALLR;
			DIGL: next = ground ? DIGL : FALLL;
			DIGR: next = ground ? DIGR : FALLR;
			DEAD: next = DEAD;
		endcase
    end

    always @(posedge clk, posedge areset) begin
		if (areset) state <= WL;
        else state <= next;
	end

	always @(posedge clk) begin
		if (state == FALLL || state == FALLR) begin
			if (fall_counter < 20)
				fall_counter <= fall_counter + 1'b1;
		end
		else
			fall_counter <= 0;
	end

	assign walk_left = (state==WL);
	assign walk_right = (state==WR);
	assign aaah = (state == FALLL) || (state == FALLR);
	assign digging = (state == DIGL) || (state == DIGR);

endmodule

module stimulus_gen (
	input clk,
	output logic areset,
	output logic bump_left,
	output logic bump_right,
	output logic dig,
	output logic ground,
	output reg[511:0] wavedrom_title,
	output reg wavedrom_enable,
	input tb_match
);

	reg reset;
	assign areset = reset;

	task reset_test(input async=0);
		bit arfail, srfail, datafail;

		@(posedge clk);
		@(posedge clk) reset <= 0;
		repeat(3) @(posedge clk);

		@(negedge clk) begin datafail = !tb_match ; reset <= 1; end
		@(posedge clk) arfail = !tb_match;
		@(posedge clk) begin
			srfail = !tb_match;
			reset <= 0;
		end
		if (srfail)
			$display("Hint: Your reset doesn't seem to be working.");
		else if (arfail && (async || !datafail))
			$display("Hint: Your reset should be %0s, but doesn't appear to be.", async ? "asynchronous" : "synchronous");
		// Don't warn about synchronous reset if the half-cycle before is already wrong. It's more likely
		// a functionality error than the reset being implemented asynchronously.

	endtask

// Add two ports to module stimulus_gen:
//    output [511:0] wavedrom_title
//    output reg wavedrom_enable

	task wavedrom_start(input[511:0] title = "");
	endtask

	task wavedrom_stop;
		#1;
	endtask

	initial begin
		reset <= 1'b1;
		@(posedge clk);
		reset <= 0;
		{bump_left, bump_right, ground, dig} <= 2;
		repeat(2) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 3;
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 10;
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 0;
		repeat(3) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 3;
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;
		repeat(4) @(posedge clk);

		{bump_left, bump_right, ground, dig} <= 0;		// Fall
		repeat(20) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;		// Survive
		repeat(1) @(posedge clk);

		{bump_left, bump_right, ground, dig} <= 0;		// Fall
		repeat(21) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;		// Splat after falling left
		repeat(20) @(posedge clk) begin
			{dig, bump_right, bump_left} <= $random & $random;	// See if it's handled correctly.
			ground <= |($random & 7);
		end

		reset <= 1;
		{bump_left, bump_right, ground, dig} <= 2;		// Normal
		@(posedge clk)
		reset <= 0;		// Resurrect.
		bump_left <= 1;
		repeat(5) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 0;		// Fall
		repeat(21) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;		// Splat after falling right
		repeat(20) @(posedge clk) begin
			{dig, bump_right, bump_left} <= $random & $random;	// See if it's handled correctly.
			ground <= |($random & 7);
		end

		reset <= 1;
		@(posedge clk)
		reset <= 0;		// Resurrect.
		{bump_left, bump_right, ground, dig} <= 2;		// Normal
		wavedrom_start("Splat?");
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 0;		// Fall
		repeat(24) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;		// Splat? (24-cycles)
		repeat(2) @(posedge clk);
		wavedrom_stop();

		reset <= 1;
		@(posedge clk)
		reset <= 0;		// Resurrect.
		{bump_left, bump_right, ground, dig} <= 2;		// Normal
		@(posedge clk);
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 0;		// Fall
		repeat(35) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;		// Splat? (Test for 5-bit non-saturating counter)
		repeat(2) @(posedge clk);
		repeat(20) @(posedge clk) begin
			{dig, bump_right, bump_left} <= $random & $random;	// See if it's handled correctly.
			ground <= |($random & 7);
		end

		reset <= 1;
		{bump_left, bump_right, ground, dig} <= 2;		// Normal
		@(posedge clk);
		reset <= 0;		// Resurrect.
		@(posedge clk);
		{bump_left, bump_right, ground, dig} <= 0;		// Fall
		repeat(67) @(posedge clk);
		{bump_left, bump_right, ground, dig} <= 2;		// Splat? (Test for 6-bit non-saturating counter)
		repeat(20) @(posedge clk) begin
			{dig, bump_right, bump_left} <= $random & $random;	// See if it's handled correctly.
			ground <= |($random & 7);
		end

		reset <= 1;
		{bump_left, bump_right, ground, dig} <= 2;		// Normal
		@(posedge clk)
		reset <= 0;		// Resurrect.

		repeat(400) @(posedge clk, negedge clk) begin
			{dig, bump_right, bump_left} <= $random & $random;
			ground <= |($random & 7);
			reset <= !($random & 31);
		end

		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_walk_left;
		int errortime_walk_left;
		int errors_walk_right;
		int errortime_walk_right;
		int errors_aaah;
		int errortime_aaah;
		int errors_digging;
		int errortime_digging;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic areset;
	logic bump_left;
	logic bump_right;
	logic ground;
	logic dig;
	logic walk_left_ref;
	logic walk_left_dut;
	logic walk_right_ref;
	logic walk_right_dut;
	logic aaah_ref;
	logic aaah_dut;
	logic digging_ref;
	logic digging_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,areset,bump_left,bump_right,ground,dig,walk_left_ref,walk_left_dut,walk_right_ref,walk_right_dut,aaah_ref,aaah_dut,digging_ref,digging_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.areset,
		.bump_left,
		.bump_right,
		.ground,
		.dig );
	reference_module good1 (
		.clk,
		.areset,
		.bump_left,
		.bump_right,
		.ground,
		.dig,
		.walk_left(walk_left_ref),
		.walk_right(walk_right_ref),
		.aaah(aaah_ref),
		.digging(digging_ref) );

	top_module top_module1 (
		.clk,
		.areset,
		.bump_left,
		.bump_right,
		.ground,
		.dig,
		.walk_left(walk_left_dut),
		.walk_right(walk_right_dut),
		.aaah(aaah_dut),
		.digging(digging_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_walk_left) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "walk_left", stats1.errors_walk_left, stats1.errortime_walk_left);
		else $display("Hint: Output '%s' has no mismatches.", "walk_left");
		if (stats1.errors_walk_right) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "walk_right", stats1.errors_walk_right, stats1.errortime_walk_right);
		else $display("Hint: Output '%s' has no mismatches.", "walk_right");
		if (stats1.errors_aaah) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "aaah", stats1.errors_aaah, stats1.errortime_aaah);
		else $display("Hint: Output '%s' has no mismatches.", "aaah");
		if (stats1.errors_digging) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "digging", stats1.errors_digging, stats1.errortime_digging);
		else $display("Hint: Output '%s' has no mismatches.", "digging");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { walk_left_ref, walk_right_ref, aaah_ref, digging_ref } === ( { walk_left_ref, walk_right_ref, aaah_ref, digging_ref } ^ { walk_left_dut, walk_right_dut, aaah_dut, digging_dut } ^ { walk_left_ref, walk_right_ref, aaah_ref, digging_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (walk_left_ref !== ( walk_left_ref ^ walk_left_dut ^ walk_left_ref ))
		begin if (stats1.errors_walk_left == 0) stats1.errortime_walk_left = $time;
			stats1.errors_walk_left = stats1.errors_walk_left+1'b1; end
		if (walk_right_ref !== ( walk_right_ref ^ walk_right_dut ^ walk_right_ref ))
		begin if (stats1.errors_walk_right == 0) stats1.errortime_walk_right = $time;
			stats1.errors_walk_right = stats1.errors_walk_right+1'b1; end
		if (aaah_ref !== ( aaah_ref ^ aaah_dut ^ aaah_ref ))
		begin if (stats1.errors_aaah == 0) stats1.errortime_aaah = $time;
			stats1.errors_aaah = stats1.errors_aaah+1'b1; end
		if (digging_ref !== ( digging_ref ^ digging_dut ^ digging_ref ))
		begin if (stats1.errors_digging == 0) stats1.errortime_digging = $time;
			stats1.errors_digging = stats1.errors_digging+1'b1; end

	end
endmodule


We want to create a timer that:
// (1) is started when a particular pattern (1101) is detected,
// (2) shifts in 4 more bits to determine the duration to delay,
// (3) waits for the counters to finish counting, and
// (4) notifies the user and waits for the user to acknowledge the timer.
// In this problem, implement just the finite-state machine that controls the timer. The data path (counters and some comparators) are not included here.
// The serial data is available on the data input pin. When the pattern 1101 is received, the state machine must then assert output shift_ena for exactly 4 clock cycles. After that, the state machine asserts its counting output to indicate it is waiting for the counters, and waits until input done_counting is high.At that point, the state machine must assert done to notify the user the timer has timed out, and waits until input ack is 1 before being reset to look for the next occurrence of the start sequence (1101). The state machine should have a active high synchronous reset, setting the state to where it begins searching for the input sequence 1101.

module top_module(
	input clk,
	input reset,
	input data,
    output reg shift_ena,
    output reg counting,
    input done_counting,
    output reg done,
    input ack );

	typedef enum logic[3:0] {
		S, S1, S11, S110, B0, B1, B2, B3, Count, Wait
	} States;

	States state, next;

	always_comb begin
		case (state)
			S: next = States'(data ? S1: S);
			S1: next = States'(data ? S11: S);
			S11: next = States'(data ? S11 : S110);
			S110: next = States'(data ? B0 : S);
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = Count;
			Count: next = States'(done_counting ? Wait : Count);
			Wait: next = States'(ack ? S : Wait);
			default: next = States'(4'bx);
		endcase
	end

	always @(posedge clk) begin
		if (reset) state <= S;
		else state <= next;
	end

	always_comb begin
		shift_ena = 0; counting = 0; done = 0;
		if (state == B0 || state == B1 || state == B2 || state == B3)
			shift_ena = 1;
		if (state == Count)
			counting = 1;
		if (state == Wait)
			done = 1;

		if (|state === 1'bx) begin
			{shift_ena, counting, done} = 'x;
		end

	end

endmodule

`timescale 1 ps/1 ps
`define OK 12
`define INCORRECT 13
module reference_module(
	input clk,
	input reset,
	input data,
    output reg shift_ena,
    output reg counting,
    input done_counting,
    output reg done,
    input ack );

	typedef enum logic[3:0] {
		S, S1, S11, S110, B0, B1, B2, B3, Count, Wait
	} States;

	States state, next;

	always_comb begin
		case (state)
			S: next = States'(data ? S1: S);
			S1: next = States'(data ? S11: S);
			S11: next = States'(data ? S11 : S110);
			S110: next = States'(data ? B0 : S);
			B0: next = B1;
			B1: next = B2;
			B2: next = B3;
			B3: next = Count;
			Count: next = States'(done_counting ? Wait : Count);
			Wait: next = States'(ack ? S : Wait);
			default: next = States'(4'bx);
		endcase
	end

	always @(posedge clk) begin
		if (reset) state <= S;
		else state <= next;
	end

	always_comb begin
		shift_ena = 0; counting = 0; done = 0;
		if (state == B0 || state == B1 || state == B2 || state == B3)
			shift_ena = 1;
		if (state == Count)
			counting = 1;
		if (state == Wait)
			done = 1;

		if (|state === 1'bx) begin
			{shift_ena, counting, done} = 'x;
		end

	end

endmodule

module stimulus_gen (
	input clk,
	output reg reset,
	output reg data, done_counting, ack,
	input tb_match
);
	bit failed = 0;

	always @(posedge clk, negedge clk)
		if (!tb_match)
			failed <= 1;

	initial begin

		@(posedge clk);
		failed <= 0;
		reset <= 1;
		data <= 0;
		done_counting <= 1'bx;
		ack <= 1'bx;
		@(posedge clk)
			data <= 1;
			reset <= 0;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 1;
		@(posedge clk) data <= 1;
		@(posedge clk) data <= 0;
		@(posedge clk) data <= 1;
		@(posedge clk);
			data <= 1'bx;
		repeat(4) @(posedge clk);
			done_counting <= 1'b0;
		repeat(4) @(posedge clk);
			done_counting <= 1'b1;
		@(posedge clk);
			done_counting <= 1'bx;
			ack <= 1'b0;
		repeat(3) @(posedge clk);
			ack <= 1'b1;
		@(posedge clk);
			ack <= 1'b0;
			data <= 1'b1;
		@(posedge clk);
			ack <= 1'bx;
			data <= 1'b1;
		@(posedge clk);
			data <= 1'b0;
		@(posedge clk);
			data <= 1'b1;
		@(posedge clk);
			data <= 1'bx;
		repeat(4) @(posedge clk);
			done_counting <= 1'b0;
		repeat(4) @(posedge clk);
			done_counting <= 1'b1;
		@(posedge clk);

		if (failed)
			$display("Hint: Your FSM didn't pass the sample timing diagram posted with the problem statement. Perhaps try debugging that?");

		repeat(5000) @(posedge clk, negedge clk) begin
			reset <= !($random & 255);
			data <= $random;
			done_counting <= !($random & 31);
			ack <= !($random & 31);
		end

		#1 $finish;
	end

endmodule

module tb();

	typedef struct packed {
		int errors;
		int errortime;
		int errors_shift_ena;
		int errortime_shift_ena;
		int errors_counting;
		int errortime_counting;
		int errors_done;
		int errortime_done;

		int clocks;
	} stats;

	stats stats1;

	wire[511:0] wavedrom_title;
	wire wavedrom_enable;
	int wavedrom_hide_after_time;

	reg clk=0;
	initial forever
		#5 clk = ~clk;

	logic reset;
	logic data;
	logic done_counting;
	logic ack;
	logic shift_ena_ref;
	logic shift_ena_dut;
	logic counting_ref;
	logic counting_dut;
	logic done_ref;
	logic done_dut;

	initial begin
		$dumpfile("wave.vcd");
		$dumpvars(1, stim1.clk, tb_mismatch ,clk,reset,data,done_counting,ack,shift_ena_ref,shift_ena_dut,counting_ref,counting_dut,done_ref,done_dut );
	end

	wire tb_match;		// Verification
	wire tb_mismatch = ~tb_match;

	stimulus_gen stim1 (
		.clk,
		.* ,
		.reset,
		.data,
		.done_counting,
		.ack );
	reference_module good1 (
		.clk,
		.reset,
		.data,
		.done_counting,
		.ack,
		.shift_ena(shift_ena_ref),
		.counting(counting_ref),
		.done(done_ref) );

	top_module top_module1 (
		.clk,
		.reset,
		.data,
		.done_counting,
		.ack,
		.shift_ena(shift_ena_dut),
		.counting(counting_dut),
		.done(done_dut) );

	bit strobe = 0;
	task wait_for_end_of_timestep;
		repeat(5) begin
			strobe <= !strobe;  // Try to delay until the very end of the time step.
			@(strobe);
		end
	endtask

	final begin
		if (stats1.errors_shift_ena) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "shift_ena", stats1.errors_shift_ena, stats1.errortime_shift_ena);
		else $display("Hint: Output '%s' has no mismatches.", "shift_ena");
		if (stats1.errors_counting) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "counting", stats1.errors_counting, stats1.errortime_counting);
		else $display("Hint: Output '%s' has no mismatches.", "counting");
		if (stats1.errors_done) $display("Hint: Output '%s' has %0d mismatches. First mismatch occurred at time %0d.", "done", stats1.errors_done, stats1.errortime_done);
		else $display("Hint: Output '%s' has no mismatches.", "done");

		$display("Hint: Total mismatched samples is %1d out of %1d samples\n", stats1.errors, stats1.clocks);
		$display("Simulation finished at %0d ps", $time);
		$display("Mismatches: %1d in %1d samples", stats1.errors, stats1.clocks);
	end

	// Verification: XORs on the right makes any X in good_vector match anything, but X in dut_vector will only match X.
	assign tb_match = ( { shift_ena_ref, counting_ref, done_ref } === ( { shift_ena_ref, counting_ref, done_ref } ^ { shift_ena_dut, counting_dut, done_dut } ^ { shift_ena_ref, counting_ref, done_ref } ) );
	// Use explicit sensitivity list here. @(*) causes NetProc::nex_input() to be called when trying to compute
	// the sensitivity list of the @(strobe) process, which isn't implemented.
	always @(posedge clk, negedge clk) begin

		stats1.clocks++;
		if (!tb_match) begin
			if (stats1.errors == 0) stats1.errortime = $time;
			stats1.errors++;
		end
		if (shift_ena_ref !== ( shift_ena_ref ^ shift_ena_dut ^ shift_ena_ref ))
		begin if (stats1.errors_shift_ena == 0) stats1.errortime_shift_ena = $time;
			stats1.errors_shift_ena = stats1.errors_shift_ena+1'b1; end
		if (counting_ref !== ( counting_ref ^ counting_dut ^ counting_ref ))
		begin if (stats1.errors_counting == 0) stats1.errortime_counting = $time;
			stats1.errors_counting = stats1.errors_counting+1'b1; end
		if (done_ref !== ( done_ref ^ done_dut ^ done_ref ))
		begin if (stats1.errors_done == 0) stats1.errortime_done = $time;
			stats1.errors_done = stats1.errors_done+1'b1; end

	end
endmodule