`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 		Churbanov S.
// 
// Create Date:		15:22:20 12/08/2019 
// Design Name: 
// Module Name:		Win_parameters
// Project Name:	Compact_main
// Target Devices: 
// Tool versions: 
// Description: 	
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module NcoRstGen	
(
	input	Clk_i,
	input	Rst_i,
	input	[31:0]	NcoPhInc_i,
	input	StartMeasEvent_i,
	
	output	NcoRst_o,
	output	StartMeasEvent_o
);
//================================================================================
//  REG/WIRE
//================================================================================
	reg	[15:0]	startMeasEventReg;
	reg	[31:0]	ncoPhIncReg;
	reg	[31:0]	ncoPhIncRegR;
	
	wire	ncoPhIncUpdateFlag	=	(ncoPhIncRegR!=ncoPhIncReg);
	wire	delFlag	=	(startMeasEventReg[15]);
	
	reg	[1:0]	currState;
	
	reg	rst;
//================================================================================
//  PARAMETERS
//================================================================================
	parameter	[1:0]	IDLE	=	2'd0;
	parameter	[1:0]	RST		=	2'd1;
	parameter	[1:0]	DEL		=	2'd2;
//================================================================================
//  ASSIGNMENTS
// ================================================================================	
	assign	NcoRst_o	=	rst;
	assign	StartMeasEvent_o	=	(currState	==	IDLE)?	StartMeasEvent_i:startMeasEventReg[15];
//================================================================================
//  CODING
//================================================================================	

	always	@(posedge	Clk_i)	begin
		if	(!Rst_i)	begin
			ncoPhIncReg		<=	NcoPhInc_i;
			ncoPhIncRegR	<=	ncoPhIncReg;
		end	else	begin
			ncoPhIncReg		<=	0;
			ncoPhIncRegR	<=	0;
		end
	end
	
	always	@(posedge	Clk_i)	begin
		if	(!Rst_i)	begin
			startMeasEventReg	<=	{startMeasEventReg[15:0],StartMeasEvent_i};
		end	else	begin
			startMeasEventReg	<=	0;
		end
	end
	
	always	@(posedge	Clk_i)	begin
		if	(!Rst_i)	begin
			case(currState)
			IDLE	:	begin
							if (ncoPhIncUpdateFlag)	begin
								currState	<= RST;
								rst	<=	1'b1;
							end	else begin
								currState	<= IDLE;
								rst	<=	1'b0;
							end
						end
						
			RST		:	begin
							if	(rst	&	StartMeasEvent_i)	begin
								currState	<= DEL;
								rst	<=	1'b0;
							end	else begin
								currState	<= RST;
								rst	<=	1'b1;
							end
						end
		
			DEL		:	begin
							if	(delFlag)	begin
								currState  <= IDLE;
								rst	<=	1'b0;
							end	else begin
								currState  <= DEL;
								rst	<=	1'b0;
							end
						end
			endcase
		end	else	begin
			currState	<=	2'd0;
		end
	end

endmodule
