#include "config.h"

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

#include <pipi.h>

static const char * aliases[] =
{
    "-o", "--save",
    "--output", "--save",
    NULL, NULL,
};

static pipi_command_t const *list;

int main(int argc, char *argv[])
{
    pipi_context_t *ctx;

    ctx = pipi_create_context();
    list = pipi_get_command_list();

    while(*++argv)
    {
        pipi_command_t const *cmd;
        char const * const *flag;
        char const * arg;
        int i;

        arg = argv[0];
        for(flag = aliases; flag[0]; flag += 2)
            if(!strcmp(arg, flag[0]))
                arg = flag[1];

        if(!strncmp(arg, "--", 2))
        {
            for(cmd = list; cmd->name; cmd++)
                if(!strcmp(arg + 2, cmd->name))
                    break;

            if(!cmd->name)
            {
                fprintf(stderr, "unknown command %s\n", argv[0]);
                return EXIT_FAILURE;
            }

            for(i = 1; i <= cmd->argc; i++)
                if(argv[i] == NULL)
                {
                    fprintf(stderr, "too few arguments for %s\n", argv[0]);
                    return EXIT_FAILURE;
                }

            switch(cmd->argc)
            {
            case 0:
                if(pipi_command(ctx, cmd->name) != 0)
                {
                    fprintf(stderr, "command %s failed\n", argv[0]);
                    return EXIT_FAILURE;
                }
                break;
            case 1:
                if(pipi_command(ctx, cmd->name, argv[1]) != 0)
                {
                    fprintf(stderr, "command %s failed\n", argv[0]);
                    return EXIT_FAILURE;
                }
                break;
            default:
                /* Can’t handle that argument count */
                return EXIT_FAILURE;
            }

            argv += cmd->argc;
        }
        else
        {
            if(pipi_command(ctx, "load", arg) != 0)
            {
                fprintf(stderr, "could not load `%s'\n", argv[0]);
                return EXIT_FAILURE;
            }
        }
    }

    pipi_destroy_context(ctx);

    return EXIT_SUCCESS;
}

