import string, getopt

import CommandLineUtil

def FancyGetopt(cmd,option_table, args):
    short_opts = []
    long_opts = []
    short2long = {}
    takes_arg = {}

    # the resulting options
    options = {}

    for option in option_table:
        (short, long) = option.getForGetOpt(short2long, takes_arg)
        short_opts.append(short)
        long_opts.extend(long)

    short_opts = string.join(short_opts)
    try:
        (opts, args) = getopt.getopt(args, short_opts, long_opts)
    except getopt.error, msg:
        raise CommandLineUtil.ArgumentError(cmd, str(msg))

    for (opt, val) in opts:
        if len(opt) == 2 and opt[0] == '-':
            # it's a short option
            opt = short2long[opt[1]]
        elif len(opt) > 2 and opt[0:2] == '--':
            opt = opt[2:]

        if not takes_arg[opt]:
            # boolean option
            val = 1

        if options.has_key(opt):
            if type(options[opt]) != type([]):
                options[opt] = [options[opt]]
            options[opt].append(val)
        else:
            options[opt] = val
    return (options, args)


