'Clean up data for sending across the AMP wire. Also apply INLINEFUNCS.
Args:
session (Session): The relevant session instance.
kwargs (dict) Each keyword represents a
send-instruction, with the keyword itself being the name
of the instruction (like "text"). Suitable values for each
keyword are:
- arg                ->  [[arg], {}]
- [args]             ->  [[args], {}]
- {kwargs}           ->  [[], {kwargs}]
- [args, {kwargs}]   ->  [[arg], {kwargs}]
- [[args], {kwargs}] ->  [[args], {kwargs}]
Returns:
kwargs (dict): A cleaned dictionary of cmdname:[[args],{kwargs}] pairs,
where the keys, args and kwargs have all been converted to
send-safe entities (strings or numbers), and inlinefuncs have been
applied.'

def clean_senddata(self, session, kwargs):

    options = (kwargs.pop('options', None) or {})
    raw = options.get('raw', False)
    strip_inlinefunc = options.get('strip_inlinefunc', False)
    def _validate(data):
        'Helper    function    to    convert    data    to    AMP-safe    (picketable)    values'
        if isinstance(data, dict):
            newdict = {}
            for (key, part) in data.items():
                newdict[key] = _validate(part)
            return newdict
        elif hasattr(data, '__iter__'):
            return [_validate(part) for part in data]
        elif isinstance(data, basestring):
            try:
                data = (data and to_str(to_unicode(data), encoding=session.protocol_flags['ENCODING']))
            except LookupError:
                session.protocol_flags['ENCODING'] = 'utf-8'
                data = to_str(to_unicode(data), encoding=session.protocol_flags['ENCODING'])
            if (_INLINEFUNC_ENABLED and (not raw) and isinstance(self, ServerSessionHandler)):
                data = parse_inlinefunc(data, strip=strip_inlinefunc, session=session)
            return data
        elif (hasattr(data, 'id') and hasattr(data, 'db_date_created') and hasattr(data, '__dbclass__')):
            return _validate(unicode(data))
        else:
            return data
    rkwargs = {}
    for (key, data) in kwargs.iteritems():
        key = _validate(key)
        if (not data):
            if (key == 'text'):
                continue
            rkwargs[key] = [[], {}]
        elif isinstance(data, dict):
            rkwargs[key] = [[], _validate(data)]
        elif hasattr(data, '__iter__'):
            if isinstance(data[(-1)], dict):
                if (len(data) == 2):
                    if hasattr(data[0], '__iter__'):
                        rkwargs[key] = [_validate(data[0]), _validate(data[1])]
                    else:
                        rkwargs[key] = [[_validate(data[0])], _validate(data[1])]
                else:
                    rkwargs[key] = [_validate(data[:(-1)]), _validate(data[(-1)])]
            else:
                rkwargs[key] = [_validate(data), {}]
        else:
            rkwargs[key] = [[_validate(data)], {}]
        rkwargs[key][1]['options'] = options
    return rkwargs
