#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <keks/err.h>
#include <keks/items.h>

#include "../lib/mmap.h"

int
main(int argc, char **argv)
{
    assert(argc == 2);
    size_t len = 0;
    unsigned char *buf = NULL;
    if (!Mmap(&buf, &len, argv[1])) {
        exit(EXIT_FAILURE);
    }
    struct KEKSItems items;
    enum KEKSErr err = KEKSItemsInit(&items, 128);
    if (err != KEKSErrNo) {
        return EXIT_FAILURE;
    }
    size_t off = 0;
    err = KEKSItemsParse(&items, &off, buf, len);
    if (err != KEKSErrNo) {
        return EXIT_SUCCESS;
    }
    {
        const size_t tailLen = len - off;
        unsigned char *dst = malloc(len);
        assert(dst != NULL);
        off = 0;
        assert(KEKSItemsEncode(&items, 0, &off, dst, len));
        assert(off == len - tailLen);
        assert(memcmp(dst, buf, len - tailLen) == 0);
    }
    return EXIT_SUCCESS;
}
