import config, image, tiff, histogram

Image *def extract_iris_texture(Image *eye, int px, py, pr, ix, iy, ir, tw, th,
    char const *what):
    Image *texture = image_new_undef_b(tw, th)
    texture->name = strdup(eye->name)

    double angle = 0, da = 2 * pi / tw
    for int i = 0; i < tw; i++:
        double c = cos(angle)
        double s = -sin(angle)
        double sx = px + 0.5 + c * pr
        double sy = py + 0.5 + s * pr
        double ex = ix + 0.5 + c * ir
        double ey = iy + 0.5 + s * ir
        for int j = 0; j < th; j++:
            double x = sx + (ex - sx) * j / th
            double y = sy + (ey - sy) * j / th
            B v = getpixel_bilinear(eye, x, y)
            texture->data.b[i + j * tw] = v
        angle += da

    if strstr(what, "iristexture"):
        char name[MAX_PATH]
        get_image_name(texture, "iristexture", name)
        save_tiff_luminance(name, texture)

    # estimate illumination
    int cw = 16, ch = 16
    Image *lum = image_new_undef_b(tw / cw, th / ch)
    for int i = 0; i < tw; i += cw:
        for int j = 0; j < th; j += ch:
            int l = 0
            for int y = 0; y < ch; y++:
                for int x = 0; x < cw; x++:
                    l += texture->data.b[i + x + (j + y) * tw]
            l /= cw * ch
            lum->data.b[i / cw + (j / ch) * lum->w] = l

    Image *back = scale_image(lum, tw, th, IST_BICUBIC)

    if strstr(what, "textureback"):
        char name[MAX_PATH]
        get_image_name(texture, "textureback", name)
        save_tiff_luminance(name, back)

    for int i = 0; i < tw; i++:
        for int j = 0; j < th; j++:
            B c = texture->data.b[i + j * tw]
            int v = 128 + c - back->data.b[i + j * tw]
            if v < 0: v = 0
            if v > 255: v = 255
            texture->data.b[i + j * tw] = v

    if strstr(what, "texturelit"):
        char name[MAX_PATH]
        get_image_name(texture, "texturelit", name)
        save_tiff_luminance(name, texture)

    # equalization
    equalize(texture)

    # One paper claims to equivalize "each 32 x 32 region" - should investigate
    # what they mean. Using pixel blocks apparently is no good idea.
    #Image *window = image_window(texture, 0, 0, 32, 32)
    #cw = 32
    #ch = 32
    #for int i = 0; i < tw; i += cw:
    #    for int j = 0; j < th; j += ch:
    #        image_move(window, i, j, cw, ch)
    #        equalize(window)

    return texture
