import config, math

static def transform_row_to_column(V *v, int w, b, V *out):
    """
    We use a trick to deal with horizontal/vertical alternating: We always read
    input horizontal, but output vertical. That way each other transform pass
    has the data transposed. Of course this won't work with a proper
    implementation working on a single buffer.
    """
    int w2 = b * (w / 2)
    int i2 = 0
    for int i = 0; i < w; i += 2:
        out[i2] = (v[i] + v[i + 1]) / 2
        out[w2 + i2] = (v[i + 1] - v[i]) / 2
        i2 += b

V *def haar_wavelet(V *image, int w, h):
    V *result = ALLOCATE(w * h * sizeof *image)
    V *temp = ALLOCATE(w * h * sizeof *image)
    V *previous = image
    for int k= 0; k < 4; k++:
        int s = 1 << k
        # horizontal (to vertical)
        for int j = 0; j < h / s; j++:
            transform_row_to_column(previous + j * w, w / s, h, temp + j)
        # vertical (back to horizontal)
        for int i = 0; i < w / s; i++:
            transform_row_to_column(temp + i * h, h / s, w, result + i)
        previous = result
    FREE(temp)
    return result
            