#include<lua.h>
#include<stdio.h>
#include<stdlib.h>
#include<png.h>
#include<string.h>
#if !defined(_MSC_VER)
#include<unistd.h>
#endif

static void *l_alloc (void *ud, void *ptr, size_t osize,
        size_t nsize) {
    (void)ud;
    (void)osize;
    if (nsize == 0) {
        free(ptr);
        return NULL;
    } else {
        return realloc(ptr, nsize);
    }
}

void open_image(const char *fname) {
    png_image image;

    memset(&image, 0, (sizeof image));
    image.version = PNG_IMAGE_VERSION;

    if(png_image_begin_read_from_file(&image, fname) != 0) {
        png_bytep buffer;

        image.format = PNG_FORMAT_RGBA;
        buffer = malloc(PNG_IMAGE_SIZE(image));

        if(png_image_finish_read(&image, NULL, buffer, 0, NULL) != 0) {
            printf("Image %s read failed: %s\n", fname, image.message);
        }
//        png_free_image(&image);
        free(buffer);
    } else {
        printf("Image %s open failed: %s", fname, image.message);
    }
}

int printer(lua_State *l) {
    if(!lua_isstring(l, 1)) {
        fprintf(stderr, "Incorrect call.\n");
        return 0;
    }
    open_image(lua_tostring(l, 1));
    return 0;
}


int main(int argc, char **argv) {
    lua_State *l = lua_newstate(l_alloc, NULL);
    if(!l) {
        printf("Lua state allocation failed.\n");
        return 1;
    }
    lua_register(l, "printer", printer);
    lua_getglobal(l, "printer");
    lua_pushliteral(l, "foobar.png");
    lua_call(l, 1, 0);
    lua_close(l);
    return 0;
}
