// Depthwise Separable Convolution — Depthwise + Pointwise
module depthwise_separable #(parameter DW=16, CH=32, KH=3, OW=28)(
    input clk, rst_n, input en, input start,
    // Depthwise phase inputs
    input signed [DW-1:0] dw_fm_in, input dw_valid, input [9:0] dw_x, dw_y, input [7:0] dw_ch,
    input signed [DW-1:0] dw_wt [0:CH*KH*KH-1], // Depthwise weights: CH × 3×3
    // Pointwise phase weights
    input signed [DW-1:0] pw_wt [0:CH*CH-1],     // 1×1 conv weights: CH × CH
    // Output
    output reg signed [DW-1:0] pw_out, output reg pw_valid,
    output reg [7:0] out_ch, output reg [9:0] out_px,
    output reg done
);
    // Phase 1: Depthwise conv (per-channel 3×3)
    reg signed [DW*2-1:0] dw_psum;
    reg signed [DW-1:0] dw_result [0:CH-1];
    reg [7:0] ch_cnt, kr_cnt, kc_cnt;
    reg [9:0] px_cnt;
    reg phase; // 0=depthwise, 1=pointwise
    reg [7:0] pw_och, pw_ich;
    reg signed [DW*2-1:0] pw_psum;
    always_ff @(posedge clk or negedge rst_n) begin
        if(!rst_n) begin phase<=0; dw_psum<='0; ch_cnt<=0; kr_cnt<=0; kc_cnt<=0; px_cnt<=0;
            pw_och<=0; pw_ich<=0; pw_psum<='0; pw_out<='0; pw_valid<=0; done<=0; out_ch<=0; out_px<=0; end
        else if(en) case({phase, start})
          2'b00: if(dw_valid) begin // Depthwise
                dw_psum<=dw_psum+dw_fm_in*dw_wt[ch_cnt*KH*KH+kr_cnt*KH+kc_cnt];
                kc_cnt<=kc_cnt+1;
                if(kc_cnt>=KH-1) begin kc_cnt<=0; kr_cnt<=kr_cnt+1;
                  if(kr_cnt>=KH-1) begin kr_cnt<=0;
                    dw_result[ch_cnt]<=dw_psum[DW*2-1:DW]; dw_psum<='0;
                    ch_cnt<=ch_cnt+1;
                    if(ch_cnt>=CH-1) begin ch_cnt<=0; px_cnt<=px_cnt+1;
                        if(px_cnt>=OW*OW-1) phase<=1; // Switch to pointwise
                    end
                  end
                end
            end
          2'b10: begin // Pointwise (1×1 conv)
                pw_psum<=pw_psum+dw_result[pw_ich]*pw_wt[pw_och*CH+pw_ich];
                pw_ich<=pw_ich+1;
                if(pw_ich>=CH-1) begin pw_ich<=0;
                    pw_out<=pw_psum[DW*2-1:DW]; pw_valid<=1;
                    out_ch<=pw_och; out_px<=px_cnt;
                    pw_psum<='0; pw_och<=pw_och+1;
                    if(pw_och>=CH-1) begin pw_och<=0; done<=1; end
                end
            end
        endcase
    end
endmodule