import config, image
import global jpeglib, jerror

Image *def load_jpeg_luminance(char const *filename):
    struct jpeg_decompress_struct cinfo
    struct jpeg_error_mgr jerr

    FILE * infile

    infile = fopen(filename, "rb")
    if not infile:
        fprintf(stderr, "can't open %s\n", filename)
        return None

    cinfo.err = jpeg_std_error(&jerr)

    jpeg_create_decompress(&cinfo)
    jpeg_stdio_src(&cinfo, infile)
    jpeg_read_header(&cinfo, TRUE)
    jpeg_start_decompress(&cinfo)

    int w = cinfo.output_width
    int h = cinfo.output_height
    int s = cinfo.output_components
    Image *image = image_new_undef_b(w, h)
    image_set_path(image, filename, True)

    printf("%s (%dx%dx%d)\n", filename, w, h, s)

    B *buffer[1]
    B temp[w * s]
    buffer[0] = temp

    while (int)cinfo.output_scanline < h:
        int j = cinfo.output_scanline
        jpeg_read_scanlines(&cinfo, (void *)buffer, 1)
        if s == 1:
            for int i = 0; i < w; i++:
                B c = buffer[0][i]
                image->data.b[j * w + i] = c

        elif s == 3:
            for int i = 0; i < w; i++:
                float r = buffer[0][i * s + 0]
                float g = buffer[0][i * s + 1]
                float b = buffer[0][i * s + 2]
                float y = 0.299 * r + 0.587 * g + 0.114 * b
                if y > 255: y = 255
                image->data.b[j * w + i] = y
        else:
            fprintf(stderr, "Error! Cannot read %s.\n", filename)
            return None

    jpeg_finish_decompress(&cinfo)
    jpeg_destroy_decompress(&cinfo)

    fclose(infile)

    printf("%s (%dx%dx%d)\n", image->name, w, h, s)
    
    return image
