'Introspect the key fields in the hierarchical table'

def __keys(self):

    tablename = self.tablename
    if (not tablename):
        return
    s3db = current.s3db
    table = s3db[tablename]
    config = s3db.get_config(tablename, 'hierarchy')
    if (not config):
        return
    if isinstance(config, tuple):
        (parent, self.__ckey) = config[:2]
    else:
        (parent, self.__ckey) = (config, None)
    pkey = None
    fkey = None
    if (parent is None):
        pkey = table._id
        for field in table:
            ftype = str(field.type)
            if (ftype[:9] == 'reference'):
                key = ftype[10:].split('.')
                if ((key[0] == tablename) and ((len(key) == 1) or (key[1] == pkey.name))):
                    parent = field.name
                    fkey = field
                    break
    else:
        resource = s3db.resource(tablename)
        rfield = resource.resolve_selector(parent)
        if (rfield.tname == resource.tablename):
            fkey = rfield.field
            self.__link = None
            self.__lkey = None
            self.__left = None
        else:
            links = resource.links
            alias = parent.split(('.%s' % rfield.fname))[0]
            link = links.get(alias)
            if (not link):
                alias = rfield.tname.split('_', 1)[1]
                link = links.get(alias)
            if link:
                fkey = rfield.field
                self.__link = rfield.tname
                self.__lkey = link.fkey
                self.__left = rfield.left.get(rfield.tname)
    if (not fkey):
        raise AttributeError
    if (pkey is None):
        ftype = str(fkey.type)
        if (ftype[:9] != 'reference'):
            raise SyntaxError(('Invalid    parent    field:    %s    is    not    a    foreign    key' % fkey))
        key = ftype[10:].split('.')
        if (key[0] == tablename):
            pkey = table._id
        else:
            ktable = s3db[key[0]]
            skey = ktable._id.name
            if ((skey != 'id') and ('instance_type' in ktable)):
                try:
                    pkey = table[skey]
                except AttributeError:
                    raise SyntaxError(('%s    is    not    an    instance    type    of    %s' % (tablename, ktable._tablename)))
    self.__pkey = pkey
    self.__fkey = fkey
    return
