# Code from Peter Meerwald
import config
import wavelets/cdf_9x7

def pollen_nosubsample_param(V const *indata, int n, instep,
    V *outlow, int lowstep, V *outhigh, int highstep, int scale, V alpha, beta):

    V h[6] # highpass filter
    V g[6] # lowpass filter
    
    h[0] = ((1.0 + cos(alpha) + sin(alpha)) * (1.0 - cos(beta) - sin(beta)) +
        2.0 * sin(beta) * cos(alpha)) / 4.0
    h[1] = ((1.0 - cos(alpha) + sin(alpha)) * (1.0 + cos(beta) - sin(beta)) -
        2.0 * sin(beta) * cos(alpha)) / 4.0
    h[2] = (1.0 + cos(alpha - beta) + sin(alpha - beta)) / 2.0
    h[3] = (1.0 + cos(alpha - beta) - sin(alpha - beta)) / 2.0
    h[4] = 1.0 - h[0] - h[2]
    h[5] = 1.0 - h[1] - h[3]

    # reflect: g = 0 5 4 3 2 1
    # shift: g = 1 0 5 4 3 2
    # alternate: g = 1 -0 5 -4 3 -2

    g[0] = h[1]
    g[1] = -h[0]
    g[2] = h[5]
    g[3] = -h[4]
    g[4] = h[3]
    g[5] = -h[2]

    filter(indata, n, instep, g, 6, outlow, lowstep, 1 << scale)
    filter(indata, n, instep, h, 6, outhigh, highstep, 1 << scale)

V **def pollen(V const *s, int n, char const *key):
    """
    This expects a signal of n samples, and will return (full-length, not
    downsampled) low and high pass results for each subdivision level.

    0 2 4.../log2(n)\ * 2 - 2 are the low pass results
    1 3 5.../log2(n)\ * 2 - 1 the high pass results
    """
    int l = ceil(log2(n));
    V **r = ALLOCATE(l * 2 * sizeof(V *))

    V a = (key[0] - '0') / 9.0 * 2 * pi - pi
    V b = (key[1] - '0') / 9.0 * 2 * pi - pi

    V const *p = s
    for int i = 0; i < l; i++:
        r[i * 2] = ALLOCATE(n * sizeof(V))
        r[i * 2 + 1] = ALLOCATE(n * sizeof(V))
        pollen_nosubsample_param(p, n, 1, r[i * 2], 1, r[i * 2 + 1],
            1, i, a, b)
        # right now, we always use the lowband for further analysis.
        p = r[i * 2]

    return r
