`timescale 1ns/1ns

module data_cal(
input clk,
input rst,
input [15:0]d,
input [1:0]sel,

output [4:0]out,
output validout
);
//*************code***********//
reg [15:0] d_reg;
wire [3:0] d0;
wire [3:0] d1;
wire [3:0] d2;
wire [3:0] d3;
assign d0 = d_reg[3:0];
assign d1 = d_reg[7:4];
assign d2 = d_reg[11:8];
assign d3 = d_reg[15:12];

reg [4:0] out_reg;
reg validout_reg;
always @ (posedge clk or negedge rst)
    begin
        if( ~rst ) begin
            out_reg <= 5'b0;
            validout_reg <= 1'b0;
            d_reg <= 16'b0;
        end 
        else begin
            case( sel ) 
                2'b00 : begin
                    d_reg <= d;
                    out_reg <= 5'b0;
                    validout_reg <= 1'b0;    
                end 
                2'b01 : begin
                    d_reg <= d_reg;
                    out_reg <= d_reg[3:0] + d_reg[7:4];// d0 + d1;
                    validout_reg <= 1'b1;    
                end 
                 2'b10 : begin
                     d_reg <= d_reg;
                    out_reg <= d0 + d2;
                    validout_reg <= 1'b1;    
                end 
                 2'b11 : begin
                     d_reg <= d_reg;
                    out_reg <= d0 + d3;
                    validout_reg <= 1'b1;    
                end 
                default : begin
                    out_reg <= 5'b0;
                    validout_reg <= 1'b0;  
                end 
            endcase
        end 
    end

assign out = out_reg;
assign validout = validout_reg;

//*************code***********//
endmodule