#include <gtk/gtk.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>


GdkPixbuf * test_pixbuf_loader(char *filename, GError **gerrorptr1, GError **gerrorptr2) {
    GdkPixbuf *pixbuf;
    GdkPixbufLoader *loader;
    FILE *file;
    size_t datalen;
    int done;
    guint8 buffer[65536];

    pixbuf = NULL;
    loader = gdk_pixbuf_loader_new();
    done = 0;

    file = fopen(filename, "rb");
    while (1) {
        datalen = fread(buffer, 1, sizeof(buffer),  file);
        printf("datalen: %i\n", (int)datalen);
        if (datalen == 0) {
            done = 1;
            break;
        }
        if (!gdk_pixbuf_loader_write(loader, buffer, datalen, gerrorptr1)) {
            break;
        }
    }
    fclose(file);

    if (done && gdk_pixbuf_loader_close(loader, gerrorptr2)) {
        pixbuf = gdk_pixbuf_loader_get_pixbuf(loader);
        if (!pixbuf) {
            printf("No pixbuf\n");
            exit(1);
        }
        g_object_ref(pixbuf);
    }
    g_object_unref(loader);

    return pixbuf;
}

int main(int argc, char *argv[]) {
    GError *gerror1, *gerror2;
    GdkPixbuf *originalpb;
    char filename[64];

    gtk_set_locale();
    gtk_init(&argc, &argv);

    strcpy(filename, argv[1]);

    gerror1 = gerror2 = NULL;
    originalpb = test_pixbuf_loader(filename, &gerror1, &gerror2);

    if(gerror1) {
        printf("error message 1: %s\n", gerror1->message);
        exit(1);
    }

    if(gerror2) {
        printf("error message 2: %s\n", gerror2->message);
        exit(1);
    }

    printf("size: %d x %d\n",
            gdk_pixbuf_get_width(originalpb),
            gdk_pixbuf_get_height(originalpb));

    g_object_unref(originalpb);

    return 0;
}
