// File: kernel.cpp
// Reference-scalar max pooling.
// LLM target: replace this file with an optimised inner_pooling.
// All per-definition constants live in pooling_def:: (pooling.h).
// Padded region is treated as -inf (matches torch F.max_pool2d), not zero.
#include "pooling.h"
using namespace pooling_def;

#include <cmath>

extern "C" void inner_pooling(const float* input, float* output,
                               int N, int C, int H, int W, int H_out, int W_out)
{
    for (int n = 0; n < N; ++n) {
        for (int c = 0; c < C; ++c) {
            const float* in_c  = input  + ((long)n * C + c) * H * W;
            float*       out_c = output + ((long)n * C + c) * H_out * W_out;
            for (int oh = 0; oh < H_out; ++oh) {
                for (int ow = 0; ow < W_out; ++ow) {
                    float m = -INFINITY;
                    for (int kh = 0; kh < Kh; ++kh) {
                        for (int kw = 0; kw < Kw; ++kw) {
                            int ih = oh * Sh - pad_top + kh;
                            int iw = ow * Sw - pad_left + kw;
                            if (ih >= 0 && ih < H && iw >= 0 && iw < W) {
                                float v = in_c[ih * W + iw];
                                if (v > m) m = v;
                            }
                        }
                    }
                    out_c[oh * W_out + ow] = m;
                }
            }
        }
    }
}