/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

#include <errno.h>

#include "data.h"

#define DBFNM "data.dat"

int main()
{
    int dbfd;
    struct data *data_ptr;
    /* setup memory and file */
    dbfd = open(DBFNM, O_RDWR);
    if(dbfd == -1)
    {
        dbfd = open(DBFNM, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
        data_ptr = malloc(sizeof(struct data));
        memset(data_ptr, 0, sizeof(struct data));
        write(dbfd, data_ptr, sizeof(struct data));
        free(data_ptr);
        close(dbfd);
        dbfd = open(DBFNM, O_RDWR);
    }
    data_ptr =  mmap(NULL, sizeof(struct data), PROT_READ | PROT_WRITE, MAP_SHARED, dbfd, 0);
    /* work */
    data_add_item(data_ptr, 1, "A A", 123);
    data_add_item(data_ptr, 2, "B B", 456);
    data_add_item(data_ptr, 3, "C C", 789);
    data_dump(data_ptr, stdout);
    /* ensure data are persisted */
    msync(data_ptr, sizeof(struct data), MS_SYNC);
    /* teardown memory and file */
    munmap(data_ptr, sizeof(struct data));
    close(dbfd);
    /* */
    return 0;
}
