/* gcc $(pkg-config glib-2.0 --cflags --libs) \
    -g -o gkeyfilecrlf gkeyfilecrlf.c */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <glib.h>

#define GROUP "main_section"
#define KEY_PREFIX "fill_abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw_"
#define FIRST_KEY 10
#define LAST_KEY 99
#define VALUE 92

static void die(const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fprintf(stderr, "\n");
    exit(2);
}

static void generate(const char *path)
{
    FILE *fp;
    gchar *key;
    gchar *value;
    int i;

    fp = fopen(path, "w");
    if (fp == NULL)
        die("Couldn't open key file");
    fprintf(fp, "[" GROUP "]\r\n");
    fprintf(fp, "fill_specific_length_for_alignment_purposes = 3\r\n");
    for (i = FIRST_KEY; i <= LAST_KEY; i++)
        fprintf(fp, KEY_PREFIX "%d = %d\r\n", i, VALUE);
    fclose(fp);
}

int main(int argc, char **argv)
{
    GKeyFile *kf;
    GError *err = NULL;
    gchar *key;
    int i;
    int val;

    if (argc != 2)
        die("Usage: %s <output-file>", argv[0]);

    /* Generate key file */
    generate(argv[1]);

    /* Load key file */
    kf = g_key_file_new();
    if (!g_key_file_load_from_file(kf, argv[1], G_KEY_FILE_NONE, &err))
        die("Couldn't load key file: %s", err->message);

    /* Retrieve values from key file */
    for (i = FIRST_KEY; i <= LAST_KEY; i++) {
        key = g_strdup_printf(KEY_PREFIX "%d", i);
        val = g_key_file_get_integer(kf, GROUP, key, &err);
        g_free(key);
        if (err != NULL) {
            fprintf(stderr, "%s\n", err->message);
            g_clear_error(&err);
        } else if (val != VALUE) {
            fprintf(stderr, "Bad value %d for key %d\n", val, i);
        }
    }

    return 0;
}
