`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    17:07:13 06/04/2021 
// Design Name: 
// Module Name:    mean_filter 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module mean_filter(
	input 				clk,
	input 				rst_n,
	input 				de,
	
	input 		[7:0]	data_in,

	output		[7:0]	data_out,
	
	input             filter_in_hs,
	input             filter_in_vs,
	input             filter_in_de,
	
	output reg        filter_out_hs,
	output reg        filter_out_vs,
	output reg        filter_out_de	
);
	
	wire 	[7:0] matrix_p11, matrix_p12, matrix_p13;
	wire 	[7:0]	matrix_p21, matrix_p22, matrix_p23;
	wire 	[7:0]	matrix_p31, matrix_p32, matrix_p33;

	shift_ram shift_ram_u1(
		.clk		(clk),						
		.rst_n		(rst_n),		
		.de		(de),	
			
		.data_in		(data_in),
				
		.matrix_p11		(matrix_p11),						
		.matrix_p12		(matrix_p12),						
		.matrix_p13		(matrix_p13),
		.matrix_p21		(matrix_p21),						
		.matrix_p22		(matrix_p22),						
		.matrix_p23		(matrix_p23),						
		.matrix_p31		(matrix_p31),						
		.matrix_p32		(matrix_p32),						
		.matrix_p33		(matrix_p33),
		
		.shift_in_hs		(filter_in_hs),
		.shift_in_vs		(filter_in_vs),
		.shift_in_de		(filter_in_de),
			
		.shift_out_hs		(shift_out_hs),
		.shift_out_vs		(shift_out_vs),
		.shift_out_de		(shift_out_de)	
);


	reg [10:0] mean_value1;
	reg [10:0] mean_value2;
	reg [10:0] mean_value3;
	
	always@(posedge clk or posedge rst_n)begin
		if(rst_n) begin
				mean_value1 <= 0;
				mean_value2 <= 0;
				mean_value3 <= 0;
		end
		else begin
				mean_value1 <= matrix_p11 + matrix_p12 + matrix_p13;
				mean_value2 <= matrix_p21 + 11'd0	   + matrix_p23;
				mean_value3 <= matrix_p31 + matrix_p32 + matrix_p33;
		end
	end


	reg [10:0] mean_value4;
	
	always@(posedge clk or posedge rst_n)begin
		if(rst_n)
			mean_value4 <= 0;
		else
			mean_value4 <= mean_value1 + mean_value2 + mean_value3;
	end	
	
	assign 	data_out = mean_value4[10:3];		

	reg  i_h_sync_delay_1;
	reg  i_v_sync_delay_1;
	reg  i_data_en_delay_1;
	
	always@(posedge clk or posedge rst_n)begin
		if(rst_n)
			begin
				i_h_sync_delay_1  <= 1'b0;
				i_v_sync_delay_1  <= 1'b0;
				i_data_en_delay_1 <= 1'b0;
				
				filter_out_hs <= 1'b0;
				filter_out_vs <= 1'b0;
				filter_out_de <= 1'b0;
			end
		else
			begin
				i_h_sync_delay_1  <= shift_out_hs;
				i_v_sync_delay_1  <= shift_out_vs;
				i_data_en_delay_1 <= shift_out_de;
				
				filter_out_hs <= i_h_sync_delay_1;
				filter_out_vs <= i_v_sync_delay_1;
				filter_out_de <= i_data_en_delay_1;     	
			end
	end

endmodule
