/*
    kwintv, Video4Linux based TV application

    Copyright (C) 1998,1999 Moritz Wenk (wenk@mathematik.uni-kl.de)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
    */

#ifdef myDEBUG
#define pDEBUG
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/utsname.h>
#include "parsecl.h"

parsecl::parsecl(int _argc, char** _argv, const struct parse_option* o,
		 const char* help)
{
    argc = _argc;
    argv = _argv;
    opt = o;

    const char* f = find('h');
    if (f)
    {
	printf("\nUsage: %s %s\n\n", argv[0], help);
	int i = 0;
	while (opt[i].oshort)
	{
	    printf("  %c%c  %s%s %s %s\n",
		   (opt[i].oshort != ' ') ? '-' : ' ',
		   (opt[i].oshort != ' ') ? opt[i].oshort : ' ',
		   opt[i].olong ? "--" : "",
		   opt[i].olong ? opt[i].olong : "",
		   opt[i].options ? opt[i].options : "",
		   opt[i].help ? opt[i].help : "");
	    i++;
	}
	printf("\n");
	exit(1);
    }
}

parsecl::~parsecl()
{
}

int parsecl::getInt(int oid, int odefault, int min, int max) const
{
    const char* p = find(oid);
    if (p)
    {
	int i = atoi(p);
	if (i >= min && i <= max)
	    return i;
    }

    return odefault;
}

const char * parsecl::getString(int oid, const char* odefault, const char* options[]) const
{
    const char* p = find(oid);
    if (p)
	return p;

    return odefault;
}

bool parsecl::getSwitch(int oid, bool odefault) const
{
    if (find(oid))
        return true;

    return odefault;
}

const char* parsecl::find(int oid) const
{
    int f = 0;
    while (opt[f].oshort && opt[f].oshort != oid)
	f++;
    if (opt[f].oshort)
    {
	int i = 0;
	while (i < argc)
	{
	    if (argv[i][0] == '-')
	    {
		int x = 2;
		if (argv[i][1] != '-')
		{
		    if (argv[i][1] == opt[f].oshort && argv[i][2] == 0)
			break; // find
		}
		else if (argv[i][2] == 0)
		{
		    i = argc;
		    break; // end of args
		}
		else
		    x++;

		if (strcmp(&argv[i][x], opt[f].olong) == 0)
		    break; // find
	    }
	    i++;
	}

	if (opt[f].options)
	{
	    if (i < argc)
	    {
		const char* p = strchr(argv[i], '=');
		if (p)
		    p++;
		else if (i + 1 < argc)
		    p = argv[i++];
		return p;
	    }
	}
	return argv[i];
    }

    return 0;
}
