def get_or_pop_arg(argname,args,kwargs,argspec):
    """Finds the value of argname by looking in args and kwargs. Is argname
       is present in argspec then the value is simply returned. If argname
       is not present, the value is removed from arg or kwargs as appropriate.

       Note: If argname is not present in either argspec or kwargs then it is
             assumed to be the last element of args and is popped off (and added
             to kwargs if the argspec says a **keywords argument is present)."""
    regargs, varargs, varkwargs, defaults = argspec

    if argname in kwargs:
        if varkwargs is None and argname not in regargs:
            return kwargs.pop(argname)
        else:
            return kwargs[argname]
    elif argname not in regargs:
        if varkwargs is None:
            return args.pop()
        else:
            value = args.pop()
            kwargs[argname] = value
            return value
    else:
        return args[regargs.index(argname)]