#include <libweb/form.h>
#include <stdlib.h>
#include <stdio.h>

static int print(const char *const key, const char *const value,
    void *const user)
{
    unsigned *const cnt = user;

    printf("key=%s, value=%s, cnt=%u\n", key, value, ++(*cnt));
    return 0;
}

int main(int argc, char *argv[])
{
    int ret = EXIT_FAILURE;
    const char *payload;
    struct form *f = NULL;
    unsigned cnt = 0;
    int n;

    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <payload>\n", *argv);
        goto end;
    }
    else if ((n = form_alloc(payload = argv[1], &f)) < 0)
    {
        fprintf(stderr, "%s: form_alloc failed\n", __func__);
        goto end;
    }
    else if (n)
    {
        fprintf(stderr, "%s: invalid user input: %s\n", __func__, payload);
        goto end;
    }
    else if (form_foreach(f, print, &cnt))
    {
        fprintf(stderr, "%s: form_foreach failed\n", __func__);
        goto end;
    }

    ret = EXIT_SUCCESS;

end:
    form_free(f);
    return ret;
}
