`timescale 1ns/1ns

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

output reg [4:0]out,
output reg validout
);
//*************code***********//
reg [15:0] d_latch ;
always@(posedge clk or negedge rst) begin
if(~rst) d_latch <= 0;
else begin
    case(sel) 
    2'b00: d_latch <= d;
    default: d_latch <= d_latch;
    endcase
end
end

wire [4:0] out_1,out_2,out_3;
assign out_1 = d_latch[3:0] + d_latch[7:4];
assign out_2 =  d_latch[3:0] + d_latch[11:8];
assign out_3 = d_latch[3:0] + d_latch[15:12];

always@(*) begin
    if(~rst) begin
        out = 0;
        validout = 0;
    end
    else begin
        case(sel) 
            2'b00 :  begin
                out = 0;
                validout = 0;
            end
            2'b01 :  begin
                out = out_1;
                validout = 1;
            end
            2'b10 :  begin
                out = out_2;
                validout = 1;
            end
            2'b11 :  begin
                out = out_3;
                validout = 1;
            end

        endcase
    end
end

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