module block_new(clk,reset,ar,ai,br,bi,sink_valid,state,final_state,source_valid);

input clk,reset,sink_valid;
input[17:0] ar,ai,br,bi;

output source_valid;
output[1:0]state,final_state;



parameter s0=2'b00,s1=2'b01,s2=2'b10;
parameter scale=8'b01000000;//2*former scale

reg[7:0]  cnt;
reg[2:0]  Head,head0,head1,head2,head3;
reg[1:0]  current_state, next_state,final_state;


always@(ar or ai or br or bi)begin
	head0=(ar[17])?(~ar[17:15]):ar[17:15];
	head1=(ai[17])?(~ai[17:15]):ai[17:15];	
	head2=(br[17])?(~br[17:15]):br[17:15];
	head3=(bi[17])?(~bi[17:15]):bi[17:15];
	Head={head0[2]|head1[2]|head2[2]|head3[2],head0[1]|head1[1]|head2[1]|head3[1],
	head0[0]|head1[0]|head2[0]|head3[0]};
end

always@(current_state or Head or sink_valid)begin
	case(current_state)
		s0:if(sink_valid==1)
				if(Head==3'b000)
					next_state=s0;
				else if(Head==3'b001)
					next_state=s1;
				else 
					next_state=s2;
			else
				next_state=s0;
		s1:if(sink_valid==1)
				if(Head==3'b000)
					next_state=s1;
				else if(Head==3'b001)
					next_state=s1;
				else 
					next_state=s2;
			else
				next_state=s0;
		s2:if(sink_valid==1)
				if(Head==3'b000)
					next_state=s2;
				else if(Head==3'b001)
					next_state=s2;
				else 
					next_state=s2;
			else
				next_state=s0;
	endcase
end

	
always@(posedge clk or negedge reset)begin
	if(!reset)begin
		current_state<=s0;
		cnt<=8'b0000_0000;
		final_state<=s0;
	end
	else begin
		current_state<=next_state;
		if(sink_valid==1)begin
			if(cnt<scale-1) begin
				cnt<=cnt+8'b0000_0001;
				end
			else begin
				cnt<=8'b0000_0000;
				final_state<=current_state;
			end
		end
		else
				cnt<=8'b0000_0000;
	end
end

assign state=current_state;
assign source_valid=(sink_valid==1'b1||cnt!=8'b0000_0000)?1'b1:1'b0;

endmodule


