Bug #239006 - In FakeVartree._aux_get_wrapper(), fall back to vdb metadata
authorZac Medico <zmedico@gentoo.org>
Mon, 6 Oct 2008 17:18:18 +0000 (17:18 -0000)
committerZac Medico <zmedico@gentoo.org>
Mon, 6 Oct 2008 17:18:18 +0000 (17:18 -0000)
if the live ebuild's EAPI is unsupported. (trunk r11600)

svn path=/main/branches/2.1.4/; revision=11640

bin/emerge

index 040fb71843d7b60a83ab465b040e785373915c15..f71536f344789805ff2fa65e8b0faf2951be203c 100755 (executable)
@@ -20,7 +20,6 @@ try:
 except KeyboardInterrupt:
        sys.exit(1)
 
-import gc
 import os, stat
 
 os.environ["PORTAGE_LEGACY_GLOBALS"] = "false"
@@ -189,7 +188,6 @@ options=[
 "--ask",          "--alphabetical",
 "--buildpkg",     "--buildpkgonly",
 "--changelog",    "--columns",
-"--complete-graph",
 "--debug",        "--deep",
 "--digest",
 "--emptytree",
@@ -304,6 +302,12 @@ def getgccversion(chost):
        "!!! other terminals also.\n"
        )
 
+       mystatus, myoutput = commands.getstatusoutput("eselect compiler show")
+       if mystatus == os.EX_OK and len(myoutput.split("/")) == 2:
+               part1, part2 = myoutput.split("/")
+               if part1.startswith(chost + "-"):
+                       return myoutput.replace(chost + "-", gcc_ver_prefix, 1)
+
        mystatus, myoutput = commands.getstatusoutput("gcc-config -c")
        if mystatus == os.EX_OK and myoutput.startswith(chost + "-"):
                return myoutput.replace(chost + "-", gcc_ver_prefix, 1)
@@ -360,7 +364,6 @@ def create_depgraph_params(myopts, myaction):
        # recurse:   go into the dependencies
        # deep:      go into the dependencies of already merged packages
        # empty:     pretend nothing is merged
-       # complete:  completely account for all known dependencies
        myparams = set(["recurse"])
        if "--update" in myopts or \
                "--newuse" in myopts or \
@@ -375,8 +378,6 @@ def create_depgraph_params(myopts, myaction):
                myparams.discard("recurse")
        if "--deep" in myopts:
                myparams.add("deep")
-       if "--complete-graph" in myopts:
-               myparams.add("complete")
        return myparams
 
 # search functionality
@@ -391,18 +392,16 @@ class search:
        #
        # public interface
        #
-       def __init__(self, root_config, spinner, searchdesc,
+       def __init__(self, settings, trees, spinner, searchdesc,
                verbose, usepkg, usepkgonly):
                """Searches the available and installed packages for the supplied search key.
                The list of available and installed packages is created at object instantiation.
                This makes successive searches faster."""
-               self.settings = root_config.settings
-               self.vartree = root_config.trees["vartree"]
+               self.settings = settings
+               self.vartree = trees["vartree"]
                self.spinner = spinner
                self.verbose = verbose
                self.searchdesc = searchdesc
-               self.root_config = root_config
-               self.setconfig = root_config.setconfig
 
                def fake_portdb():
                        pass
@@ -413,9 +412,9 @@ class search:
 
                self._dbs = []
 
-               portdb = root_config.trees["porttree"].dbapi
-               bindb = root_config.trees["bintree"].dbapi
-               vardb = root_config.trees["vartree"].dbapi
+               portdb = trees["porttree"].dbapi
+               bindb = trees["bintree"].dbapi
+               vardb = trees["vartree"].dbapi
 
                if not usepkgonly and portdb._have_root_eclass_dir:
                        self._dbs.append(portdb)
@@ -467,14 +466,8 @@ class search:
        def _visible(self, db, cpv, metadata):
                installed = db is self.vartree.dbapi
                built = installed or db is not self._portdb
-               pkg_type = "ebuild"
-               if installed:
-                       pkg_type = "installed"
-               elif built:
-                       pkg_type = "binary"
-               return visible(self.settings,
-                       Package(type_name=pkg_type, root_config=self.root_config,
-                       cpv=cpv, built=built, installed=installed, metadata=metadata))
+               return visible(self.settings, cpv, metadata,
+                       built=built, installed=installed)
 
        def _xmatch(self, level, atom):
                """
@@ -502,8 +495,8 @@ class search:
                                else:
                                        db_keys = list(db._aux_cache_keys)
                                        for cpv in db.match(atom):
-                                               metadata = izip(db_keys,
-                                                       db.aux_get(cpv, db_keys))
+                                               metadata = dict(izip(db_keys,
+                                                       db.aux_get(cpv, db_keys)))
                                                if not self._visible(db, cpv, metadata):
                                                        continue
                                                matches.add(cpv)
@@ -525,8 +518,8 @@ class search:
                                        for cpv in reversed(db.match(atom)):
                                                if portage.cpv_getkey(cpv) != cp:
                                                        continue
-                                               metadata = izip(db_keys,
-                                                       db.aux_get(cpv, db_keys))
+                                               metadata = dict(izip(db_keys,
+                                                       db.aux_get(cpv, db_keys)))
                                                if not self._visible(db, cpv, metadata):
                                                        continue
                                                if not result or cpv == portage.best([cpv, result]):
@@ -615,7 +608,7 @@ class search:
                                                        self.portdb.xmatch("match-all",match))
                                else:
                                        full_package = match
-                                       match        = portage.cpv_getkey(match)
+                                       match        = portage.pkgsplit(match)[0]
 
                                if full_package:
                                        try:
@@ -738,7 +731,7 @@ def getlist(settings, mode):
 
        return mynewlines
 
-def world_clean_package(vardb, cpv):
+def clean_world(vardb, cpv):
        """Remove a package from the world file when unmerged."""
        world_set = WorldSet(vardb.settings)
        world_set.lock()
@@ -767,118 +760,68 @@ def world_clean_package(vardb, cpv):
        world_set.save()
        world_set.unlock()
 
-SETPREFIX = "@"
-
-class SetConfig(object):
-       def __init__(self, settings, trees):
-               self.sets = {}
-               self.sets["world"] = WorldSet(settings)
-               self.sets["world"].load()
-               self.sets["system"] = SystemSet(settings)
-
-       def getSets(self):
-               return self.sets
-
-       def getSetAtoms(self, name):
-               return set(self.sets[name])
-
-class InternalPackageSet(object):
-       def __init__(self, initial_atoms=None):
+class AtomSet(object):
+       def __init__(self, atoms=None):
                self._atoms = {}
-               self._nonatoms = set()
-               if initial_atoms:
-                       self.update(initial_atoms)
+               if atoms:
+                       self.update(atoms)
        def clear(self):
                self._atoms.clear()
-               self._nonatoms.clear()
        def add(self, atom):
-               if not isinstance(atom, portage_dep.Atom):
-                       if isinstance(atom, basestring):
-                               atom = atom.strip()
-                       if not atom:
-                               return
-                       try:
-                               atom = portage_dep.Atom(atom)
-                       except portage_exception.InvalidAtom:
-                               self._nonatoms.add(atom)
-                               return
-
-               cp_list = self._atoms.get(atom.cp)
+               cp = portage.dep_getkey(atom)
+               cp_list = self._atoms.get(cp)
                if cp_list is None:
                        cp_list = []
-                       self._atoms[atom.cp] = cp_list
+                       self._atoms[cp] = cp_list
                if atom not in cp_list:
                        cp_list.append(atom)
        def update(self, atoms):
                for atom in atoms:
                        self.add(atom)
        def __contains__(self, atom):
-               if atom in self._nonatoms:
-                       return True
                cp = portage.dep_getkey(atom)
                if cp in self._atoms and atom in self._atoms[cp]:
                        return True
                return False
-
-       def findAtomForPackage(self, pkg):
+       def findAtomForPackage(self, cpv, metadata):
                """Return the best match for a given package from the arguments, or
                None if there are no matches.  This matches virtual arguments against
                the PROVIDE metadata.  This can raise an InvalidDependString exception
                if an error occurs while parsing PROVIDE."""
-
-               # Atoms matched via PROVIDE must be temporarily transformed since
-               # match_from_list() only works correctly when atom.cp == pkg.cp.
-               rev_transform = {}
-               for atom in self.iterAtomsForPackage(pkg):
-                       if atom.cp == pkg.cp:
-                               rev_transform[atom] = atom
-                       else:
-                               rev_transform[portage_dep.Atom(atom.replace(atom.cp, pkg.cp, 1))] = atom
-               best_match = portage.best_match_to_list(pkg, rev_transform.iterkeys())
-               if best_match:
-                       return rev_transform[best_match]
-               return None
-
-       def iterAtomsForPackage(self, pkg):
-               """
-               Find all matching atoms for a given package. This matches virtual
-               arguments against the PROVIDE metadata.  This will raise an
-               InvalidDependString exception if PROVIDE is invalid.
-               """
-               cpv_slot_list = [pkg]
-               cp = portage.cpv_getkey(pkg.cpv)
+               cpv_slot = "%s:%s" % (cpv, metadata["SLOT"])
+               cp = portage.dep_getkey(cpv)
                atoms = self._atoms.get(cp)
                if atoms:
-                       for atom in atoms:
-                               if portage.match_from_list(atom, cpv_slot_list):
-                                       yield atom
-               if not pkg.metadata["PROVIDE"]:
-                       return
+                       best_match = portage.best_match_to_list(cpv_slot, atoms)
+                       if best_match:
+                               return best_match
+               if not metadata["PROVIDE"]:
+                       return None
                provides = portage.flatten(portage_dep.use_reduce(
-                       portage_dep.paren_reduce(pkg.metadata["PROVIDE"]),
-                       uselist=pkg.metadata["USE"].split()))
+                       portage_dep.paren_reduce(metadata["PROVIDE"]),
+                       uselist=metadata["USE"].split()))
                for provide in provides:
                        provided_cp = portage.dep_getkey(provide)
                        atoms = self._atoms.get(provided_cp)
                        if atoms:
-                               for atom in atoms:
-                                       if portage.match_from_list(atom.replace(provided_cp, cp),
-                                               cpv_slot_list):
-                                               yield atom
-
+                               transformed_atoms = [atom.replace(provided_cp, cp) for atom in atoms]
+                               best_match = portage.best_match_to_list(cpv_slot, transformed_atoms)
+                               if best_match:
+                                       return atoms[transformed_atoms.index(best_match)]
+               return None
        def __iter__(self):
                for atoms in self._atoms.itervalues():
                        for atom in atoms:
                                yield atom
 
-class SystemSet(InternalPackageSet):
+class SystemSet(AtomSet):
        def __init__(self, settings, **kwargs):
-               InternalPackageSet.__init__(self, **kwargs)
+               AtomSet.__init__(self, **kwargs)
                self.update(getlist(settings, "system"))
 
-class WorldSet(InternalPackageSet):
+class WorldSet(AtomSet):
        def __init__(self, settings, **kwargs):
-               InternalPackageSet.__init__(self, **kwargs)
+               AtomSet.__init__(self, **kwargs)
                self.world_file = os.path.join(settings["ROOT"], portage.WORLD_FILE)
                self._lock = None
        def _ensure_dirs(self):
@@ -901,25 +844,25 @@ class WorldSet(InternalPackageSet):
 class RootConfig(object):
        """This is used internally by depgraph to track information about a
        particular $ROOT."""
-       def __init__(self, settings, trees, setconfig):
+       def __init__(self, trees):
                self.trees = trees
-               self.settings = settings
+               self.settings = trees["vartree"].settings
                self.root = self.settings["ROOT"]
-               self.setconfig = setconfig
-               self.sets = self.setconfig.getSets()
-               self.visible_pkgs = PackageVirtualDbapi(self.settings)
+               self.sets = {}
+               world_set = WorldSet(self.settings)
+               world_set.load()
+               self.sets["world"] = world_set
+               system_set = SystemSet(self.settings)
+               self.sets["system"] = system_set
 
-def create_world_atom(pkg, args_set, root_config):
+def create_world_atom(pkg_key, metadata, args_set, root_config):
        """Create a new atom for the world file if one does not exist.  If the
        argument atom is precise enough to identify a specific slot then a slot
        atom will be returned. Atoms that are in the system set may also be stored
        in world since system atoms can only match one slot while world atoms can
        be greedy with respect to slots.  Unslotted system packages will not be
        stored in world."""
-
-       arg_atom = args_set.findAtomForPackage(pkg)
-       if not arg_atom:
-               return None
+       arg_atom = args_set.findAtomForPackage(pkg_key, metadata)
        cp = portage.dep_getkey(arg_atom)
        new_world_atom = cp
        sets = root_config.sets
@@ -938,7 +881,7 @@ def create_world_atom(pkg, args_set, root_config):
        if slotted and arg_atom != cp:
                # If the user gave a specific atom, store it as a
                # slot atom in the world file.
-               slot_atom = pkg.slot_atom
+               slot_atom = "%s:%s" % (cp, metadata["SLOT"])
 
                # For USE=multislot, there are a couple of cases to
                # handle here:
@@ -973,13 +916,13 @@ def create_world_atom(pkg, args_set, root_config):
                        if len(matched_slots) == 1:
                                new_world_atom = slot_atom
 
-       if new_world_atom == sets["world"].findAtomForPackage(pkg):
+       if new_world_atom == sets["world"].findAtomForPackage(pkg_key, metadata):
                # Both atoms would be identical, so there's nothing to add.
                return None
        if not slotted:
                # Unlike world atoms, system atoms are not greedy for slots, so they
                # can't be safely excluded from world if they are slotted.
-               system_atom = sets["system"].findAtomForPackage(pkg)
+               system_atom = sets["system"].findAtomForPackage(pkg_key, metadata)
                if system_atom:
                        if not portage.dep_getkey(system_atom).startswith("virtual/"):
                                return None
@@ -999,49 +942,7 @@ def filter_iuse_defaults(iuse):
                else:
                        yield flag
 
-class SlotObject(object):
-       __slots__ = ("__weakref__",)
-
-       def __init__(self, **kwargs):
-               classes = [self.__class__]
-               while classes:
-                       c = classes.pop()
-                       if c is SlotObject:
-                               continue
-                       classes.extend(c.__bases__)
-                       slots = getattr(c, "__slots__", None)
-                       if not slots:
-                               continue
-                       for myattr in slots:
-                               myvalue = kwargs.get(myattr, None)
-                               setattr(self, myattr, myvalue)
-
-class AbstractDepPriority(SlotObject):
-       __slots__ = ("buildtime", "runtime", "runtime_post")
-
-       def __lt__(self, other):
-               return self.__int__() < other
-
-       def __le__(self, other):
-               return self.__int__() <= other
-
-       def __eq__(self, other):
-               return self.__int__() == other
-
-       def __ne__(self, other):
-               return self.__int__() != other
-
-       def __gt__(self, other):
-               return self.__int__() > other
-
-       def __ge__(self, other):
-               return self.__int__() >= other
-
-       def copy(self):
-               import copy
-               return copy.copy(self)
-
-class DepPriority(AbstractDepPriority):
+class DepPriority(object):
        """
                This class generates an integer priority level based of various
                attributes of the dependency relationship.  Attributes can be assigned
@@ -1052,16 +953,13 @@ class DepPriority(AbstractDepPriority):
                "buildtime", "runtime", and "system".  Various combinations of
                attributes lead to the following priority levels:
 
-               Combination of properties           Priority  Category
+               Combination of properties    Priority level
 
-               not satisfied and buildtime            0       HARD
-               not satisfied and runtime             -1       MEDIUM
-               not satisfied and runtime_post        -2       MEDIUM_SOFT
-               satisfied and buildtime and rebuild   -3       SOFT
-               satisfied and buildtime               -4       SOFT
-               satisfied and runtime                 -5       SOFT
-               satisfied and runtime_post            -6       SOFT
-               (none of the above)                   -6       SOFT
+               not satisfied and buildtime     0
+               not satisfied and runtime      -1
+               satisfied and buildtime        -2
+               satisfied and runtime          -3
+               (none of the above)            -4
 
                Several integer constants are defined for categorization of priority
                levels:
@@ -1071,12 +969,17 @@ class DepPriority(AbstractDepPriority):
                SOFT     The upper boundary for soft dependencies.
                MIN      The lower boundary for soft dependencies.
        """
-       __slots__ = ("satisfied", "rebuild")
+       __slots__ = ("__weakref__", "satisfied", "buildtime", "runtime", "runtime_post", "rebuild")
        MEDIUM = -1
        MEDIUM_SOFT = -2
        SOFT   = -3
        MIN    = -6
-
+       def __init__(self, **kwargs):
+               for myattr in self.__slots__:
+                       if myattr == "__weakref__":
+                               continue
+                       myvalue = kwargs.get(myattr, False)
+                       setattr(self, myattr, myvalue)
        def __int__(self):
                if not self.satisfied:
                        if self.buildtime:
@@ -1094,7 +997,21 @@ class DepPriority(AbstractDepPriority):
                if self.runtime_post:
                        return -6
                return -6
-
+       def __lt__(self, other):
+               return self.__int__() < other
+       def __le__(self, other):
+               return self.__int__() <= other
+       def __eq__(self, other):
+               return self.__int__() == other
+       def __ne__(self, other):
+               return self.__int__() != other
+       def __gt__(self, other):
+               return self.__int__() > other
+       def __ge__(self, other):
+               return self.__int__() >= other
+       def copy(self):
+               import copy
+               return copy.copy(self)
        def __str__(self):
                myvalue = self.__int__()
                if myvalue > self.MEDIUM:
@@ -1105,43 +1022,6 @@ class DepPriority(AbstractDepPriority):
                        return "medium-soft"
                return "soft"
 
-class BlockerDepPriority(DepPriority):
-       __slots__ = ()
-       def __int__(self):
-               return 0
-
-BlockerDepPriority.instance = BlockerDepPriority()
-
-class UnmergeDepPriority(AbstractDepPriority):
-       __slots__ = ()
-       """
-       Combination of properties           Priority  Category
-
-       runtime                                0       HARD
-       runtime_post                          -1       HARD
-       buildtime                             -2       SOFT
-       (none of the above)                   -2       SOFT
-       """
-
-       MAX    =  0
-       SOFT   = -2
-       MIN    = -2
-
-       def __int__(self):
-               if self.runtime:
-                       return 0
-               if self.runtime_post:
-                       return -1
-               if self.buildtime:
-                       return -2
-               return -2
-
-       def __str__(self):
-               myvalue = self.__int__()
-               if myvalue > self.SOFT:
-                       return "hard"
-               return "soft"
-
 class FakeVartree(portage.vartree):
        """This is implements an in-memory copy of a vartree instance that provides
        all the interfaces required for use by the depgraph.  The vardb is locked
@@ -1152,19 +1032,14 @@ class FakeVartree(portage.vartree):
        user doesn't necessarily need write access to the vardb in cases where
        global updates are necessary (updates are performed when necessary if there
        is not a matching ebuild in the tree)."""
-       def __init__(self, root_config, pkg_cache=None, acquire_lock=1):
-               if pkg_cache is None:
-                       pkg_cache = {}
-               real_vartree = root_config.trees["vartree"]
-               portdb = root_config.trees["porttree"].dbapi
+       def __init__(self, real_vartree, portdb, db_keys):
                self.root = real_vartree.root
                self.settings = real_vartree.settings
-               mykeys = list(Package.metadata_keys)
+               mykeys = db_keys[:]
                for required_key in ("COUNTER", "SLOT"):
                        if required_key not in mykeys:
                                mykeys.append(required_key)
-               self._pkg_cache = pkg_cache
-               self.dbapi = PackageVirtualDbapi(real_vartree.settings)
+               self.dbapi = portage.fakedbapi(settings=real_vartree.settings)
                vdb_path = os.path.join(self.root, portage.VDB_PATH)
                try:
                        # At least the parent needs to exist for the lock file.
@@ -1173,17 +1048,12 @@ class FakeVartree(portage.vartree):
                        pass
                vdb_lock = None
                try:
-                       if acquire_lock and os.access(vdb_path, os.W_OK):
+                       if os.access(vdb_path, os.W_OK):
                                vdb_lock = portage_locks.lockdir(vdb_path)
                        real_dbapi = real_vartree.dbapi
                        slot_counters = {}
                        for cpv in real_dbapi.cpv_all():
-                               cache_key = ("installed", self.root, cpv, "nomerge")
-                               pkg = self._pkg_cache.get(cache_key)
-                               if pkg is not None:
-                                       metadata = pkg.metadata
-                               else:
-                                       metadata = dict(izip(mykeys, real_dbapi.aux_get(cpv, mykeys)))
+                               metadata = dict(izip(mykeys, real_dbapi.aux_get(cpv, mykeys)))
                                myslot = metadata["SLOT"]
                                mycp = portage.dep_getkey(cpv)
                                myslot_atom = "%s:%s" % (mycp, myslot)
@@ -1197,12 +1067,7 @@ class FakeVartree(portage.vartree):
                                        if other_counter > mycounter:
                                                continue
                                slot_counters[myslot_atom] = mycounter
-                               if pkg is None:
-                                       pkg = Package(built=True, cpv=cpv,
-                                               installed=True, metadata=metadata,
-                                               root_config=root_config, type_name="installed")
-                               self._pkg_cache[pkg] = pkg
-                               self.dbapi.cpv_inject(pkg)
+                               self.dbapi.cpv_inject(cpv, metadata=metadata)
                        real_dbapi.flush_cache()
                finally:
                        if vdb_lock:
@@ -1217,27 +1082,11 @@ class FakeVartree(portage.vartree):
                # being delayed in case cache generation is triggered.
                self._aux_get = self.dbapi.aux_get
                self.dbapi.aux_get = self._aux_get_wrapper
-               self._match = self.dbapi.match
-               self.dbapi.match = self._match_wrapper
                self._aux_get_history = set()
-               self._portdb_keys = ["DEPEND", "RDEPEND", "PDEPEND"]
+               self._portdb_keys = ["EAPI", "DEPEND", "RDEPEND", "PDEPEND"]
                self._portdb = portdb
                self._global_updates = None
 
-       def _match_wrapper(self, cpv, use_cache=1):
-               """
-               Make sure the metadata in Package instances gets updated for any
-               cpv that is returned from a match() call, since the metadata can
-               be accessed directly from the Package instance instead of via
-               aux_get().
-               """
-               matches = self._match(cpv, use_cache=use_cache)
-               for cpv in matches:
-                       if cpv in self._aux_get_history:
-                               continue
-                       self._aux_get_wrapper(cpv, [])
-               return matches
-
        def _aux_get_wrapper(self, pkg, wants):
                if pkg in self._aux_get_history:
                        return self._aux_get(pkg, wants)
@@ -1246,6 +1095,8 @@ class FakeVartree(portage.vartree):
                        # Use the live ebuild metadata if possible.
                        live_metadata = dict(izip(self._portdb_keys,
                                self._portdb.aux_get(pkg, self._portdb_keys)))
+                       if not portage.eapi_is_supported(live_metadata["EAPI"]):
+                               raise KeyError(pkg)
                        self.dbapi.aux_update(pkg, live_metadata)
                except (KeyError, portage_exception.PortageException):
                        if self._global_updates is None:
@@ -1276,7 +1127,7 @@ def perform_global_updates(mycpv, mydb, mycommands):
        if updates:
                mydb.aux_update(mycpv, updates)
 
-def visible(pkgsettings, pkg):
+def visible(pkgsettings, cpv, metadata, built=False, installed=False):
        """
        Check if a package is visible. This can raise an InvalidDependString
        exception if LICENSE is invalid.
@@ -1284,19 +1135,18 @@ def visible(pkgsettings, pkg):
        @rtype: Boolean
        @returns: True if the package is visible, False otherwise.
        """
-       if not pkg.metadata["SLOT"]:
+       if not metadata["SLOT"]:
                return False
-       if pkg.built and not pkg.installed and "CHOST" in pkg.metadata:
-               if not pkgsettings._accept_chost(pkg):
-                       return False
-       if not portage.eapi_is_supported(pkg.metadata["EAPI"]):
+       if built and not installed and \
+               metadata["CHOST"] != pkgsettings["CHOST"]:
+               return False
+       if not portage.eapi_is_supported(metadata["EAPI"]):
                return False
-       if not pkg.installed and \
-               pkgsettings._getMissingKeywords(pkg.cpv, pkg.metadata):
+       if not installed and pkgsettings._getMissingKeywords(cpv, metadata):
                return False
-       if pkgsettings._getMaskAtom(pkg.cpv, pkg.metadata):
+       if pkgsettings._getMaskAtom(cpv, metadata):
                return False
-       if pkgsettings._getProfileMaskAtom(pkg.cpv, pkg.metadata):
+       if pkgsettings._getProfileMaskAtom(cpv, metadata):
                return False
        return True
 
@@ -1306,10 +1156,10 @@ def get_masking_status(pkg, pkgsettings, root_config):
                pkg, settings=pkgsettings,
                portdb=root_config.trees["porttree"].dbapi)
 
-       if pkg.built and not pkg.installed and "CHOST" in pkg.metadata:
-               if not pkgsettings._accept_chost(pkg):
-                       mreasons.append("CHOST: %s" % \
-                               pkg.metadata["CHOST"])
+       if pkg.built and not pkg.installed and \
+               pkg.metadata["CHOST"] != root_config.settings["CHOST"]:
+               mreasons.append("CHOST: %s" % \
+                       pkg.metadata["CHOST"])
 
        if not pkg.metadata["SLOT"]:
                mreasons.append("invalid: SLOT is undefined")
@@ -1326,11 +1176,11 @@ def get_mask_info(root_config, cpv, pkgsettings,
                metadata = None
        if metadata and not built:
                pkgsettings.setcpv(cpv, mydb=metadata)
-               metadata["USE"] = pkgsettings["PORTAGE_USE"]
+               metadata["USE"] = pkgsettings.get("USE", "")
        if metadata is None:
                mreasons = ["corruption"]
        else:
-               pkg = Package(type_name=pkg_type, root_config=root_config,
+               pkg = Package(type_name=pkg_type, root=root_config.root,
                        cpv=cpv, built=built, installed=installed, metadata=metadata)
                mreasons = get_masking_status(pkg, pkgsettings, root_config)
        return metadata, mreasons
@@ -1367,237 +1217,43 @@ def show_masked_packages(masked_packages):
                        shown_comments.add(comment)
        return have_eapi_mask
 
-class Task(SlotObject):
-       __slots__ = ("_hash_key", "_hash_value")
+class Package(object):
+       __slots__ = ("__weakref__", "built", "cpv", "depth",
+               "installed", "metadata", "root", "onlydeps", "type_name",
+               "cpv_slot", "slot_atom", "_digraph_node")
+       def __init__(self, **kwargs):
+               for myattr in self.__slots__:
+                       if myattr == "__weakref__":
+                               continue
+                       myvalue = kwargs.get(myattr, None)
+                       setattr(self, myattr, myvalue)
 
-       def _get_hash_key(self):
-               hash_key = getattr(self, "_hash_key", None)
-               if hash_key is None:
-                       raise NotImplementedError(self)
-               return hash_key
+               self.slot_atom = "%s:%s" % \
+                       (portage.cpv_getkey(self.cpv), self.metadata["SLOT"])
 
-       def __eq__(self, other):
-               return self._get_hash_key() == other
+               self.cpv_slot = "%s:%s" % (self.cpv, self.metadata["SLOT"])
 
-       def __ne__(self, other):
-               return self._get_hash_key() != other
+               status = "merge"
+               if self.onlydeps or self.installed:
+                       status = "nomerge"
+               self._digraph_node = (self.type_name, self.root, self.cpv, status)
 
+       def __eq__(self, other):
+               return self._digraph_node == other
+       def __ne__(self, other):
+               return self._digraph_node != other
        def __hash__(self):
-               hash_value = getattr(self, "_hash_value", None)
-               if hash_value is None:
-                       self._hash_value = hash(self._get_hash_key())
-               return self._hash_value
-
+               return hash(self._digraph_node)
        def __len__(self):
-               return len(self._get_hash_key())
-
+               return len(self._digraph_node)
        def __getitem__(self, key):
-               return self._get_hash_key()[key]
-
+               return self._digraph_node[key]
        def __iter__(self):
-               return iter(self._get_hash_key())
-
+               return iter(self._digraph_node)
        def __contains__(self, key):
-               return key in self._get_hash_key()
-
-       def __str__(self):
-               return str(self._get_hash_key())
-
-class Blocker(Task):
-       __slots__ = ("root", "atom", "cp", "satisfied")
-
-       def __init__(self, **kwargs):
-               Task.__init__(self, **kwargs)
-               self.cp = portage.dep_getkey(self.atom)
-
-       def _get_hash_key(self):
-               hash_key = getattr(self, "_hash_key", None)
-               if hash_key is None:
-                       self._hash_key = \
-                               ("blocks", self.root, self.atom)
-               return self._hash_key
-
-class Package(Task):
-       __slots__ = ("built", "cpv", "depth",
-               "installed", "metadata", "onlydeps", "operation",
-               "root_config", "type_name",
-               "category", "counter", "cp", "cpv_split",
-               "inherited", "iuse", "mtime",
-               "pf", "pv_split", "root", "slot", "slot_atom", "use")
-
-       metadata_keys = [
-               "CHOST", "COUNTER", "DEPEND", "EAPI", "IUSE", "KEYWORDS",
-               "LICENSE", "PDEPEND", "PROVIDE", "RDEPEND",
-               "repository", "RESTRICT", "SLOT", "USE", "_mtime_"]
-
-       def __init__(self, **kwargs):
-               Task.__init__(self, **kwargs)
-               self.root = self.root_config.root
-               self.metadata = self._metadata_wrapper(self, self.metadata)
-               self.cp = portage.cpv_getkey(self.cpv)
-               self.slot_atom = portage_dep.Atom("%s:%s" % (self.cp, self.slot))
-               self.category, self.pf = portage.catsplit(self.cpv)
-               self.cpv_split = portage.catpkgsplit(self.cpv)
-               self.pv_split = self.cpv_split[1:]
-
-       class _use(object):
-
-               __slots__ = ("__weakref__", "enabled")
-
-               def __init__(self, use):
-                       self.enabled = frozenset(use)
-
-       class _iuse(object):
-
-               __slots__ = ("__weakref__", "all", "enabled", "disabled", "iuse_implicit", "tokens")
-
-               def __init__(self, tokens):
-                       self.tokens = tuple(tokens)
-                       enabled = []
-                       disabled = []
-                       other = []
-                       for x in tokens:
-                               prefix = x[:1]
-                               if prefix == "+":
-                                       enabled.append(x[1:])
-                               elif prefix == "-":
-                                       disabled.append(x[1:])
-                               else:
-                                       other.append(x)
-                       self.enabled = frozenset(enabled)
-                       self.disabled = frozenset(disabled)
-                       self.all = frozenset(chain(enabled, disabled, other))
-
-       class _metadata_wrapper(dict):
-               """
-               Detect metadata updates and synchronize Package attributes.
-               """
-               _wrapped_keys = frozenset(
-                       ["COUNTER", "INHERITED", "IUSE", "SLOT", "USE", "_mtime_"])
-
-               def __init__(self, pkg, metadata):
-                       dict.__init__(self)
-                       self._pkg = pkg
-                       i = getattr(metadata, "iteritems", None)
-                       if i is None:
-                               i = metadata
-                       else:
-                               i = i()
-                       for k, v in i:
-                               self[k] = v
-
-               def __setitem__(self, k, v):
-                       dict.__setitem__(self, k, v)
-                       if k in self._wrapped_keys:
-                               getattr(self, "_set_" + k.lower())(k, v)
-
-               def _set_inherited(self, k, v):
-                       if isinstance(v, basestring):
-                               v = frozenset(v.split())
-                       self._pkg.inherited = v
-
-               def _set_iuse(self, k, v):
-                       self._pkg.iuse = self._pkg._iuse(v.split())
-
-               def _set_slot(self, k, v):
-                       self._pkg.slot = v
-
-               def _set_use(self, k, v):
-                       self._pkg.use = self._pkg._use(v.split())
-
-               def _set_counter(self, k, v):
-                       if isinstance(v, basestring):
-                               try:
-                                       v = int(v.strip())
-                               except ValueError:
-                                       v = 0
-                       self._pkg.counter = v
-
-               def _set__mtime_(self, k, v):
-                       if isinstance(v, basestring):
-                               try:
-                                       v = float(v.strip())
-                               except ValueError:
-                                       v = 0
-                       self._pkg.mtime = v
-
-       def _get_hash_key(self):
-               hash_key = getattr(self, "_hash_key", None)
-               if hash_key is None:
-                       if self.operation is None:
-                               self.operation = "merge"
-                               if self.onlydeps or self.installed:
-                                       self.operation = "nomerge"
-                       self._hash_key = \
-                               (self.type_name, self.root, self.cpv, self.operation)
-               return self._hash_key
-
-       def __lt__(self, other):
-               if other.cp != self.cp:
-                       return False
-               if portage.pkgcmp(self.pv_split, other.pv_split) < 0:
-                       return True
-               return False
-
-       def __le__(self, other):
-               if other.cp != self.cp:
-                       return False
-               if portage.pkgcmp(self.pv_split, other.pv_split) <= 0:
-                       return True
-               return False
-
-       def __gt__(self, other):
-               if other.cp != self.cp:
-                       return False
-               if portage.pkgcmp(self.pv_split, other.pv_split) > 0:
-                       return True
-               return False
-
-       def __ge__(self, other):
-               if other.cp != self.cp:
-                       return False
-               if portage.pkgcmp(self.pv_split, other.pv_split) >= 0:
-                       return True
-               return False
-
-class DependencyArg(object):
-       def __init__(self, arg=None, root_config=None):
-               self.arg = arg
-               self.root_config = root_config
-
+               return key in self._digraph_node
        def __str__(self):
-               return self.arg
-
-class AtomArg(DependencyArg):
-       def __init__(self, atom=None, **kwargs):
-               DependencyArg.__init__(self, **kwargs)
-               self.atom = atom
-               if not isinstance(self.atom, portage_dep.Atom):
-                       self.atom = portage_dep.Atom(self.atom)
-               self.set = (self.atom, )
-
-class PackageArg(DependencyArg):
-       def __init__(self, package=None, **kwargs):
-               DependencyArg.__init__(self, **kwargs)
-               self.package = package
-               self.atom = portage_dep.Atom("=" + package.cpv)
-               self.set = (self.atom, )
-
-class SetArg(DependencyArg):
-       def __init__(self, set=None, **kwargs):
-               DependencyArg.__init__(self, **kwargs)
-               self.set = set
-               self.name = self.arg[len(SETPREFIX):]
-
-class Dependency(SlotObject):
-       __slots__ = ("atom", "blocker", "depth",
-               "parent", "onlydeps", "priority", "root")
-       def __init__(self, **kwargs):
-               SlotObject.__init__(self, **kwargs)
-               if self.priority is None:
-                       self.priority = DepPriority()
-               if self.depth is None:
-                       self.depth = 0
+               return str(self._digraph_node)
 
 class BlockerCache(DictMixin):
        """This caches blockers of installed packages so that dep_check does not
@@ -1607,27 +1263,20 @@ class BlockerCache(DictMixin):
                1) the set of installed packages (including COUNTER) has changed
                2) the old-style virtuals have changed
        """
-
-       # Number of uncached packages to trigger cache update, since
-       # it's wasteful to update it for every vdb change.
-       _cache_threshold = 5
-
        class BlockerData(object):
-
-               __slots__ = ("__weakref__", "atoms", "counter")
-
                def __init__(self, counter, atoms):
                        self.counter = counter
                        self.atoms = atoms
 
        def __init__(self, myroot, vardb):
                self._vardb = vardb
+               self._installed_pkgs = set(vardb.cpv_all())
                self._virtuals = vardb.settings.getvirtuals()
                self._cache_filename = os.path.join(myroot,
                        portage.CACHE_PATH.lstrip(os.path.sep), "vdb_blockers.pickle")
                self._cache_version = "1"
                self._cache_data = None
-               self._modified = set()
+               self._modified = False
                self._load()
 
        def _load(self):
@@ -1638,65 +1287,24 @@ class BlockerCache(DictMixin):
                        self._cache_data = mypickle.load()
                        f.close()
                        del f
-               except (IOError, OSError, EOFError, cPickle.UnpicklingError), e:
-                       if isinstance(e, cPickle.UnpicklingError):
-                               writemsg("!!! Error loading '%s': %s\n" % \
-                                       (self._cache_filename, str(e)), noiselevel=-1)
-                       del e
+               except (IOError, OSError, EOFError, cPickle.UnpicklingError):
+                       pass
                cache_valid = self._cache_data and \
                        isinstance(self._cache_data, dict) and \
                        self._cache_data.get("version") == self._cache_version and \
-                       isinstance(self._cache_data.get("blockers"), dict)
+                       self._cache_data.get("virtuals") == self._virtuals and \
+                       set(self._cache_data.get("blockers", [])) == self._installed_pkgs
                if cache_valid:
-                       # Validate all the atoms and counters so that
-                       # corruption is detected as soon as possible.
-                       invalid_items = set()
-                       for k, v in self._cache_data["blockers"].iteritems():
-                               if not isinstance(k, basestring):
-                                       invalid_items.add(k)
-                                       continue
-                               try:
-                                       if portage.catpkgsplit(k) is None:
-                                               invalid_items.add(k)
-                                               continue
-                               except portage_exception.InvalidData:
-                                       invalid_items.add(k)
-                                       continue
-                               if not isinstance(v, tuple) or \
-                                       len(v) != 2:
-                                       invalid_items.add(k)
-                                       continue
-                               counter, atoms = v
-                               if not isinstance(counter, (int, long)):
-                                       invalid_items.add(k)
-                                       continue
-                               if not isinstance(atoms, (list, tuple)):
-                                       invalid_items.add(k)
-                                       continue
-                               invalid_atom = False
-                               for atom in atoms:
-                                       if not isinstance(atom, basestring):
-                                               invalid_atom = True
-                                               break
-                                       if atom[:1] != "!" or \
-                                               not portage.isvalidatom(
-                                               atom, allow_blockers=True):
-                                               invalid_atom = True
-                                               break
-                               if invalid_atom:
-                                       invalid_items.add(k)
-                                       continue
-
-                       for k in invalid_items:
-                               del self._cache_data["blockers"][k]
-                       if not self._cache_data["blockers"]:
-                               cache_valid = False
-
+                       for pkg in self._installed_pkgs:
+                               if long(self._vardb.aux_get(pkg, ["COUNTER"])[0]) != \
+                                       self[pkg].counter:
+                                       cache_valid = False
+                                       break
                if not cache_valid:
                        self._cache_data = {"version":self._cache_version}
                        self._cache_data["blockers"] = {}
                        self._cache_data["virtuals"] = self._virtuals
-               self._modified.clear()
+               self._modified = False
 
        def flush(self):
                """If the current user has permission and the internal blocker cache
@@ -1714,7 +1322,7 @@ class BlockerCache(DictMixin):
                        "virtuals" : vardb.settings.getvirtuals()
                }
                """
-               if len(self._modified) >= self._cache_threshold and \
+               if self._modified and \
                        secpass >= 2:
                        try:
                                f = portage_util.atomic_ofstream(self._cache_filename)
@@ -1724,7 +1332,7 @@ class BlockerCache(DictMixin):
                                        self._cache_filename, gid=portage.portage_gid, mode=0644)
                        except (IOError, OSError), e:
                                pass
-                       self._modified.clear()
+                       self._modified = False
 
        def __setitem__(self, cpv, blocker_data):
                """
@@ -1737,14 +1345,8 @@ class BlockerCache(DictMixin):
                @type blocker_data: BlockerData
                """
                self._cache_data["blockers"][cpv] = \
-                       (blocker_data.counter, tuple(str(x) for x in blocker_data.atoms))
-               self._modified.add(cpv)
-
-       def __iter__(self):
-               return iter(self._cache_data["blockers"])
-
-       def __delitem__(self, cpv):
-               del self._cache_data["blockers"][cpv]
+                       (blocker_data.counter, blocker_data.atoms)
+               self._modified = True
 
        def __getitem__(self, cpv):
                """
@@ -1756,107 +1358,9 @@ class BlockerCache(DictMixin):
        def keys(self):
                """This needs to be implemented so that self.__repr__() doesn't raise
                an AttributeError."""
-               return list(self)
-
-class BlockerDB(object):
-
-       def __init__(self, root_config):
-               self._root_config = root_config
-               self._vartree = root_config.trees["vartree"]
-               self._portdb = root_config.trees["porttree"].dbapi
-               self._blocker_cache = \
-                       BlockerCache(self._vartree.root, self._vartree.dbapi)
-               self._dep_check_trees = { self._vartree.root : {
-                       "porttree"    :  self._vartree,
-                       "vartree"     :  self._vartree,
-               }}
-
-       def findInstalledBlockers(self, new_pkg, acquire_lock=0):
-               blocker_cache = self._blocker_cache
-               dep_keys = ["DEPEND", "RDEPEND", "PDEPEND"]
-               dep_check_trees = self._dep_check_trees
-               settings = self._vartree.settings
-               stale_cache = set(blocker_cache)
-               fake_vartree = \
-                       FakeVartree(self._root_config, acquire_lock=acquire_lock)
-               vardb = fake_vartree.dbapi
-               installed_pkgs = list(vardb)
-
-               for inst_pkg in installed_pkgs:
-                       stale_cache.discard(inst_pkg.cpv)
-                       cached_blockers = blocker_cache.get(inst_pkg.cpv)
-                       if cached_blockers is not None and \
-                               cached_blockers.counter != long(inst_pkg.metadata["COUNTER"]):
-                               cached_blockers = None
-                       if cached_blockers is not None:
-                               blocker_atoms = cached_blockers.atoms
-                       else:
-                               # Use aux_get() to trigger FakeVartree global
-                               # updates on *DEPEND when appropriate.
-                               depstr = " ".join(vardb.aux_get(inst_pkg.cpv, dep_keys))
-                               try:
-                                       portage_dep._dep_check_strict = False
-                                       success, atoms = portage.dep_check(depstr,
-                                               vardb, settings, myuse=inst_pkg.use.enabled,
-                                               trees=dep_check_trees, myroot=inst_pkg.root)
-                               finally:
-                                       portage_dep._dep_check_strict = True
-                               if not success:
-                                       pkg_location = os.path.join(inst_pkg.root,
-                                               portage.VDB_PATH, inst_pkg.category, inst_pkg.pf)
-                                       portage.writemsg("!!! %s/*DEPEND: %s\n" % \
-                                               (pkg_location, atoms), noiselevel=-1)
-                                       continue
-
-                               blocker_atoms = [atom for atom in atoms \
-                                       if atom.startswith("!")]
-                               blocker_atoms.sort()
-                               counter = long(inst_pkg.metadata["COUNTER"])
-                               blocker_cache[inst_pkg.cpv] = \
-                                       blocker_cache.BlockerData(counter, blocker_atoms)
-               for cpv in stale_cache:
-                       del blocker_cache[cpv]
-               blocker_cache.flush()
-
-               blocker_parents = digraph()
-               blocker_atoms = []
-               for pkg in installed_pkgs:
-                       for blocker_atom in self._blocker_cache[pkg.cpv].atoms:
-                               blocker_atom = blocker_atom[1:]
-                               blocker_atoms.append(blocker_atom)
-                               blocker_parents.add(blocker_atom, pkg)
-
-               blocker_atoms = InternalPackageSet(initial_atoms=blocker_atoms)
-               blocking_pkgs = set()
-               for atom in blocker_atoms.iterAtomsForPackage(new_pkg):
-                       blocking_pkgs.update(blocker_parents.parent_nodes(atom))
-
-               # Check for blockers in the other direction.
-               depstr = " ".join(new_pkg.metadata[k] for k in dep_keys)
-               try:
-                       portage_dep._dep_check_strict = False
-                       success, atoms = portage.dep_check(depstr,
-                               vardb, settings, myuse=new_pkg.use.enabled,
-                               trees=dep_check_trees, myroot=new_pkg.root)
-               finally:
-                       portage_dep._dep_check_strict = True
-               if not success:
-                       # We should never get this far with invalid deps.
-                       show_invalid_depstring_notice(new_pkg, depstr, atoms)
-                       assert False
-
-               blocker_atoms = [atom[1:] for atom in atoms \
-                       if atom.startswith("!")]
-               if blocker_atoms:
-                       blocker_atoms = InternalPackageSet(initial_atoms=blocker_atoms)
-                       for inst_pkg in installed_pkgs:
-                               try:
-                                       blocker_atoms.iterAtomsForPackage(inst_pkg).next()
-                               except (portage_exception.InvalidDependString, StopIteration):
-                                       continue
-                               blocking_pkgs.add(inst_pkg)
-
-               return blocking_pkgs
+               if self._cache_data and "blockers" in self._cache_data:
+                       return self._cache_data["blockers"].keys()
+               return []
 
 def show_invalid_depstring_notice(parent_node, depstring, error_msg):
 
@@ -1893,145 +1397,19 @@ def show_invalid_depstring_notice(parent_node, depstring, error_msg):
                f.add_flowing_data(x)
        f.end_paragraph(1)
 
-class PackageVirtualDbapi(portage.dbapi):
-       """
-       A dbapi-like interface class that represents the state of the installed
-       package database as new packages are installed, replacing any packages
-       that previously existed in the same slot. The main difference between
-       this class and fakedbapi is that this one uses Package instances
-       internally (passed in via cpv_inject() and cpv_remove() calls).
-       """
-       def __init__(self, settings):
-               portage.dbapi.__init__(self)
-               self.settings = settings
-               self._match_cache = {}
-               self._cp_map = {}
-               self._cpv_map = {}
-
-       def clear(self):
-               """
-               Remove all packages.
-               """
-               if self._cpv_map:
-                       self._clear_cache()
-                       self._cp_map.clear()
-                       self._cpv_map.clear()
-
-       def copy(self):
-               obj = PackageVirtualDbapi(self.settings)
-               obj._match_cache = self._match_cache.copy()
-               obj._cp_map = self._cp_map.copy()
-               for k, v in obj._cp_map.iteritems():
-                       obj._cp_map[k] = v[:]
-               obj._cpv_map = self._cpv_map.copy()
-               return obj
-
-       def __iter__(self):
-               return self._cpv_map.itervalues()
-
-       def __contains__(self, item):
-               existing = self._cpv_map.get(item.cpv)
-               if existing is not None and \
-                       existing == item:
-                       return True
-               return False
-
-       def match_pkgs(self, atom):
-               return [self._cpv_map[cpv] for cpv in self.match(atom)]
-
-       def _clear_cache(self):
-               if self._categories is not None:
-                       self._categories = None
-               if self._match_cache:
-                       self._match_cache = {}
-
-       def match(self, origdep, use_cache=1):
-               result = self._match_cache.get(origdep)
-               if result is not None:
-                       return result[:]
-               result = portage.dbapi.match(self, origdep, use_cache=use_cache)
-               self._match_cache[origdep] = result
-               return result[:]
-
-       def cpv_exists(self, cpv):
-               return cpv in self._cpv_map
-
-       def cp_list(self, mycp, use_cache=1):
-               cachelist = self._match_cache.get(mycp)
-               # cp_list() doesn't expand old-style virtuals
-               if cachelist and cachelist[0].startswith(mycp):
-                       return cachelist[:]
-               cpv_list = self._cp_map.get(mycp)
-               if cpv_list is None:
-                       cpv_list = []
-               else:
-                       cpv_list = [pkg.cpv for pkg in cpv_list]
-               self._cpv_sort_ascending(cpv_list)
-               if not (not cpv_list and mycp.startswith("virtual/")):
-                       self._match_cache[mycp] = cpv_list
-               return cpv_list[:]
-
-       def cp_all(self):
-               return list(self._cp_map)
-
-       def cpv_all(self):
-               return list(self._cpv_map)
-
-       def cpv_inject(self, pkg):
-               cp_list = self._cp_map.get(pkg.cp)
-               if cp_list is None:
-                       cp_list = []
-                       self._cp_map[pkg.cp] = cp_list
-               e_pkg = self._cpv_map.get(pkg.cpv)
-               if e_pkg is not None:
-                       if e_pkg == pkg:
-                               return
-                       self.cpv_remove(e_pkg)
-               for e_pkg in cp_list:
-                       if e_pkg.slot_atom == pkg.slot_atom:
-                               if e_pkg == pkg:
-                                       return
-                               self.cpv_remove(e_pkg)
-                               break
-               cp_list.append(pkg)
-               self._cpv_map[pkg.cpv] = pkg
-               self._clear_cache()
-
-       def cpv_remove(self, pkg):
-               old_pkg = self._cpv_map.get(pkg.cpv)
-               if old_pkg != pkg:
-                       raise KeyError(pkg)
-               self._cp_map[pkg.cp].remove(pkg)
-               del self._cpv_map[pkg.cpv]
-               self._clear_cache()
-
-       def aux_get(self, cpv, wants):
-               metadata = self._cpv_map[cpv].metadata
-               return [metadata.get(x, "") for x in wants]
-
-       def aux_update(self, cpv, values):
-               self._cpv_map[cpv].metadata.update(values)
-               self._clear_cache()
-
-class depgraph(object):
+class depgraph:
 
        pkg_tree_map = {
                "ebuild":"porttree",
                "binary":"bintree",
                "installed":"vartree"}
 
-       _mydbapi_keys = Package.metadata_keys
-
-       _dep_keys = ["DEPEND", "RDEPEND", "PDEPEND"]
-
-       # If dep calculation time exceeds this value then automatically
-       # enable "complete" mode since any performance difference is
-       # not as likely to be noticed by the user after this much time
-       # has passed.
-       _complete_threshold = 20
+       _mydbapi_keys = [
+               "CHOST", "DEPEND", "EAPI", "IUSE", "KEYWORDS",
+               "LICENSE", "PDEPEND", "PROVIDE", "RDEPEND",
+               "repository", "RESTRICT", "SLOT", "USE"]
 
        def __init__(self, settings, trees, myopts, myparams, spinner):
-               self._creation_time = time.time()
                self.settings = settings
                self.target_root = settings["ROOT"]
                self.myopts = myopts
@@ -2041,99 +1419,43 @@ class depgraph(object):
                        self.edebug = 1
                self.spinner = spinner
                self.pkgsettings = {}
-               # Maps slot atom to package for each Package added to the graph.
-               self._slot_pkg_map = {}
+               # Maps cpv to digraph node for all nodes added to the graph.
+               self.pkg_node_map = {}
+               # Maps slot atom to digraph node for all nodes added to the graph.
+               self._slot_node_map = {}
                # Maps nodes to the reasons they were selected for reinstallation.
                self._reinstall_nodes = {}
                self.mydbapi = {}
                self.trees = {}
-               self._trees_orig = trees
                self.roots = {}
-               # Contains a filtered view of preferred packages that are selected
-               # from available repositories.
-               self._filtered_trees = {}
-               # Contains installed packages and new packages that have been added
-               # to the graph.
-               self._graph_trees = {}
-               # All Package instances
-               self._pkg_cache = self._package_cache(self)
                for myroot in trees:
                        self.trees[myroot] = {}
-                       # Create a RootConfig instance that references
-                       # the FakeVartree instead of the real one.
-                       self.roots[myroot] = RootConfig(
-                               trees[myroot]["vartree"].settings,
-                               self.trees[myroot],
-                               trees[myroot]["root_config"].setconfig)
                        for tree in ("porttree", "bintree"):
                                self.trees[myroot][tree] = trees[myroot][tree]
                        self.trees[myroot]["vartree"] = \
-                               FakeVartree(trees[myroot]["root_config"],
-                                       pkg_cache=self._pkg_cache)
+                               FakeVartree(trees[myroot]["vartree"],
+                                       trees[myroot]["porttree"].dbapi,
+                                       self._mydbapi_keys)
                        self.pkgsettings[myroot] = portage.config(
                                clone=self.trees[myroot]["vartree"].settings)
-                       self._slot_pkg_map[myroot] = {}
+                       self.pkg_node_map[myroot] = {}
+                       self._slot_node_map[myroot] = {}
                        vardb = self.trees[myroot]["vartree"].dbapi
-                       preload_installed_pkgs = "--nodeps" not in self.myopts and \
-                               "--buildpkgonly" not in self.myopts
+                       self.roots[myroot] = RootConfig(self.trees[myroot])
                        # This fakedbapi instance will model the state that the vdb will
                        # have after new packages have been installed.
-                       fakedb = PackageVirtualDbapi(vardb.settings)
-                       if preload_installed_pkgs:
-                               for pkg in vardb:
-                                       self.spinner.update()
-                                       # This triggers metadata updates via FakeVartree.
-                                       vardb.aux_get(pkg.cpv, [])
-                                       fakedb.cpv_inject(pkg)
+                       fakedb = portage.fakedbapi(settings=self.pkgsettings[myroot])
                        self.mydbapi[myroot] = fakedb
-                       def graph_tree():
-                               pass
-                       graph_tree.dbapi = fakedb
-                       self._graph_trees[myroot] = {}
-                       self._filtered_trees[myroot] = {}
-                       # Substitute the graph tree for the vartree in dep_check() since we
-                       # want atom selections to be consistent with package selections
-                       # have already been made.
-                       self._graph_trees[myroot]["porttree"]   = graph_tree
-                       self._graph_trees[myroot]["vartree"]    = graph_tree
-                       def filtered_tree():
-                               pass
-                       filtered_tree.dbapi = self._dep_check_composite_db(self, myroot)
-                       self._filtered_trees[myroot]["porttree"] = filtered_tree
-
-                       # Passing in graph_tree as the vartree here could lead to better
-                       # atom selections in some cases by causing atoms for packages that
-                       # have been added to the graph to be preferred over other choices.
-                       # However, it can trigger atom selections that result in
-                       # unresolvable direct circular dependencies. For example, this
-                       # happens with gwydion-dylan which depends on either itself or
-                       # gwydion-dylan-bin. In case gwydion-dylan is not yet installed,
-                       # gwydion-dylan-bin needs to be selected in order to avoid a
-                       # an unresolvable direct circular dependency.
-                       #
-                       # To solve the problem described above, pass in "graph_db" so that
-                       # packages that have been added to the graph are distinguishable
-                       # from other available packages and installed packages. Also, pass
-                       # the parent package into self._select_atoms() calls so that
-                       # unresolvable direct circular dependencies can be detected and
-                       # avoided when possible.
-                       self._filtered_trees[myroot]["graph_db"] = graph_tree.dbapi
-                       self._filtered_trees[myroot]["vartree"] = self.trees[myroot]["vartree"]
-
-                       dbs = []
-                       portdb = self.trees[myroot]["porttree"].dbapi
-                       bindb  = self.trees[myroot]["bintree"].dbapi
-                       vardb  = self.trees[myroot]["vartree"].dbapi
-                       #               (db, pkg_type, built, installed, db_keys)
-                       if "--usepkgonly" not in self.myopts:
-                               db_keys = list(portdb._aux_cache_keys)
-                               dbs.append((portdb, "ebuild", False, False, db_keys))
-                       if "--usepkg" in self.myopts:
-                               db_keys = list(bindb._aux_cache_keys)
-                               dbs.append((bindb,  "binary", True, False, db_keys))
-                       db_keys = self._mydbapi_keys
-                       dbs.append((vardb, "installed", True, True, db_keys))
-                       self._filtered_trees[myroot]["dbs"] = dbs
+                       if "--nodeps" not in self.myopts and \
+                               "--buildpkgonly" not in self.myopts:
+                               # --nodeps bypasses this, since it isn't needed in this case
+                               # and the cache pulls might trigger (slow) cache generation.
+                               for pkg in vardb.cpv_all():
+                                       self.spinner.update()
+                                       fakedb.cpv_inject(pkg,
+                                               metadata=dict(izip(self._mydbapi_keys,
+                                               vardb.aux_get(pkg, self._mydbapi_keys))))
+                       del vardb, fakedb
                        if "--usepkg" in self.myopts:
                                self.trees[myroot]["bintree"].populate(
                                        "--getbinpkg" in self.myopts,
@@ -2141,43 +1463,29 @@ class depgraph(object):
                del trees
 
                self.digraph=portage.digraph()
+               # Tracks simple parent/child relationships (PDEPEND relationships are
+               # not reversed).
+               self._parent_child_digraph = digraph()
                # contains all sets added to the graph
                self._sets = {}
                # contains atoms given as arguments
-               self._sets["args"] = InternalPackageSet()
+               self._sets["args"] = AtomSet()
                # contains all atoms from all sets added to the graph, including
                # atoms given as arguments
-               self._set_atoms = InternalPackageSet()
-               self._atom_arg_map = {}
+               self._set_atoms = AtomSet()
                # contains all nodes pulled in by self._set_atoms
                self._set_nodes = set()
-               # Contains only Blocker -> Uninstall edges
-               self._blocker_uninstalls = digraph()
-               # Contains only Package -> Blocker edges
-               self._blocker_parents = digraph()
-               # Contains only irrelevant Package -> Blocker edges
-               self._irrelevant_blockers = digraph()
-               # Contains only unsolvable Package -> Blocker edges
-               self._unsolvable_blockers = digraph()
+               self.blocker_digraph = digraph()
+               self.blocker_parents = {}
+               self._unresolved_blocker_parents = {}
                self._slot_collision_info = set()
                # Slot collision nodes are not allowed to block other packages since
                # blocker validation is only able to account for one package per slot.
                self._slot_collision_nodes = set()
-               self._serialized_tasks_cache = None
-               self._displayed_list = None
+               self._altlist_cache = {}
                self._pprovided_args = []
                self._missing_args = []
-               self._masked_installed = set()
-               self._unsatisfied_deps_for_display = []
-               self._unsatisfied_blockers_for_display = None
-               self._circular_deps_for_display = None
-               self._dep_stack = []
-               self._unsatisfied_deps = []
-               self._ignored_deps = []
-               self._required_set_names = set(["system", "world"])
-               self._select_atoms = self._select_atoms_highest_available
-               self._select_package = self._select_pkg_highest_available
-               self._highest_pkg_cache = {}
+               self._masked_installed = []
 
        def _show_slot_collision_notice(self):
                """Show an informational message advising the user to mask one of the
@@ -2186,16 +1494,10 @@ class depgraph(object):
                already been selected) will be required in order to handle all possible
                cases."""
 
-               if not self._slot_collision_info:
-                       return
-
-               self._show_merge_list()
-
                msg = []
                msg.append("\n!!! Multiple versions within a single " + \
-                       "package slot have been pulled\n")
-               msg.append("!!! into the dependency graph, resulting" + \
-                       " in a slot conflict:\n\n")
+                       "package slot have been \n")
+               msg.append("!!! pulled into the dependency graph:\n\n")
                indent = "  "
                # Max number of parents shown, to avoid flooding the display.
                max_parents = 3
@@ -2204,36 +1506,28 @@ class depgraph(object):
                        msg.append("\n\n")
                        slot_nodes = []
                        for node in self._slot_collision_nodes:
-                               if node.slot_atom == slot_atom:
+                               type_name, pkg_root, cpv, pkg_status = node
+                               if pkg_root != root:
+                                       continue
+                               mydb = self.roots[root].trees[
+                                       self.pkg_tree_map[type_name]].dbapi
+                               slot = mydb.aux_get(cpv, ["SLOT"])[0]
+                               if slot_atom == "%s:%s" % (portage.cpv_getkey(cpv), slot):
                                        slot_nodes.append(node)
-                       slot_nodes.append(self._slot_pkg_map[root][slot_atom])
+                       slot_nodes.append(self._slot_node_map[root][slot_atom])
                        for node in slot_nodes:
                                msg.append(indent)
                                msg.append(str(node))
-                               parents = self.digraph.parent_nodes(node)
+                               parents = self._parent_child_digraph.parent_nodes(node)
                                if parents:
                                        omitted_parents = 0
                                        if len(parents) > max_parents:
+                                               omitted_parents = len(parents) - max_parents
                                                pruned_list = []
-                                               # When generating the pruned list, prefer instances
-                                               # of DependencyArg over instances of Package.
-                                               for parent in parents:
-                                                       if isinstance(parent, DependencyArg):
-                                                               pruned_list.append(parent)
-                                               # Prefer Packages instances that themselves have been
-                                               # pulled into collision slots.
                                                for parent in parents:
-                                                       if isinstance(parent, Package) and \
-                                                               (parent.slot_atom, parent.root) \
-                                                               in self._slot_collision_info:
-                                                               pruned_list.append(parent)
-                                               for parent in parents:
-                                                       if len(pruned_list) >= max_parents:
+                                                       pruned_list.append(parent)
+                                                       if len(pruned_list) == max_parents:
                                                                break
-                                                       if not isinstance(parent, DependencyArg) and \
-                                                               parent not in pruned_list:
-                                                               pruned_list.append(parent)
-                                               omitted_parents = len(parents) - len(pruned_list)
                                                parents = pruned_list
                                        msg.append(" pulled in by\n")
                                        for parent in parents:
@@ -2283,8 +1577,8 @@ class depgraph(object):
                """Return a set of flags that trigger reinstallation, or None if there
                are no such flags."""
                if "--newuse" in self.myopts:
-                       flags = set(orig_iuse.symmetric_difference(
-                               cur_iuse).difference(forced_flags))
+                       flags = orig_iuse.symmetric_difference(
+                               cur_iuse).difference(forced_flags)
                        flags.update(orig_iuse.intersection(orig_use).symmetric_difference(
                                cur_iuse.intersection(cur_use)))
                        if flags:
@@ -2296,79 +1590,8 @@ class depgraph(object):
                                return flags
                return None
 
-       def _create_graph(self, allow_unsatisfied=False):
-               dep_stack = self._dep_stack
-               while dep_stack:
-                       self.spinner.update()
-                       dep = dep_stack.pop()
-                       if isinstance(dep, Package):
-                               if not self._add_pkg_deps(dep,
-                                       allow_unsatisfied=allow_unsatisfied):
-                                       return 0
-                               continue
-                       if not self._add_dep(dep, allow_unsatisfied=allow_unsatisfied):
-                               return 0
-               return 1
-
-       def _add_dep(self, dep, allow_unsatisfied=False):
-               debug = "--debug" in self.myopts
-               buildpkgonly = "--buildpkgonly" in self.myopts
-               nodeps = "--nodeps" in self.myopts
-               empty = "empty" in self.myparams
-               deep = "deep" in self.myparams
-               update = "--update" in self.myopts and dep.depth <= 1
-               if dep.blocker:
-                       if not buildpkgonly and \
-                               not nodeps and \
-                               dep.parent not in self._slot_collision_nodes:
-                               if dep.parent.onlydeps:
-                                       # It's safe to ignore blockers if the
-                                       # parent is an --onlydeps node.
-                                       return 1
-                               # The blocker applies to the root where
-                               # the parent is or will be installed.
-                               blocker = Blocker(atom=dep.atom, root=dep.parent.root)
-                               self._blocker_parents.add(blocker, dep.parent)
-                       return 1
-               dep_pkg, existing_node = self._select_package(dep.root, dep.atom,
-                       onlydeps=dep.onlydeps)
-               if not dep_pkg:
-                       if allow_unsatisfied:
-                               self._unsatisfied_deps.append(dep)
-                               return 1
-                       self._unsatisfied_deps_for_display.append(
-                               ((dep.root, dep.atom), {"myparent":dep.parent}))
-                       return 0
-               # In some cases, dep_check will return deps that shouldn't
-               # be proccessed any further, so they are identified and
-               # discarded here. Try to discard as few as possible since
-               # discarded dependencies reduce the amount of information
-               # available for optimization of merge order.
-               if dep.priority.satisfied and \
-                       not (existing_node or empty or deep or update):
-                       myarg = None
-                       if dep.root == self.target_root:
-                               try:
-                                       myarg = self._iter_atoms_for_pkg(dep_pkg).next()
-                               except StopIteration:
-                                       pass
-                               except portage_exception.InvalidDependString:
-                                       if not dep_pkg.installed:
-                                               # This shouldn't happen since the package
-                                               # should have been masked.
-                                               raise
-                       if not myarg:
-                               self._ignored_deps.append(dep)
-                               return 1
-
-               if not self._add_pkg(dep_pkg, dep.parent,
-                       priority=dep.priority, depth=dep.depth):
-                       return 0
-               return 1
-
-       def _add_pkg(self, pkg, myparent, priority=None, depth=0):
-               if priority is None:
-                       priority = DepPriority()
+       def create(self, mybigkey, myparent=None, addme=1, metadata=None,
+               priority=DepPriority(), rev_dep=False, arg=None):
                """
                Fills the digraph with nodes comprised of packages to merge.
                mybigkey is the package spec of the package to merge.
@@ -2381,28 +1604,90 @@ class depgraph(object):
                #"no downgrade" emerge
                """
 
+               # unused parameters
+               rev_dep = False
+
+               mytype, myroot, mykey = mybigkey
+
                # select the correct /var database that we'll be checking against
-               vardbapi = self.trees[pkg.root]["vartree"].dbapi
-               pkgsettings = self.pkgsettings[pkg.root]
+               vardbapi = self.trees[myroot]["vartree"].dbapi
+               portdb = self.trees[myroot]["porttree"].dbapi
+               bindb = self.trees[myroot]["bintree"].dbapi
+               pkgsettings = self.pkgsettings[myroot]
 
-               args = None
-               arg_atoms = None
-               if True:
+               # if the package is already on the system, we add a "nomerge"
+               # directive, otherwise we add a "merge" directive.
+
+               mydbapi = self.trees[myroot][self.pkg_tree_map[mytype]].dbapi
+               if metadata is None:
+                       metadata = dict(izip(self._mydbapi_keys,
+                               mydbapi.aux_get(mykey, self._mydbapi_keys)))
+                       if mytype == "ebuild":
+                               pkgsettings.setcpv(mykey, mydb=portdb)
+                               metadata["USE"] = pkgsettings["USE"]
+               myuse = metadata["USE"].split()
+
+               if not arg and myroot == self.target_root:
                        try:
-                               arg_atoms = list(self._iter_atoms_for_pkg(pkg))
+                               arg = self._set_atoms.findAtomForPackage(mykey, metadata)
                        except portage_exception.InvalidDependString, e:
-                               if not pkg.installed:
-                                       show_invalid_depstring_notice(
-                                               pkg, pkg.metadata["PROVIDE"], str(e))
+                               if mytype != "installed":
+                                       show_invalid_depstring_notice(tuple(mybigkey+["merge"]),
+                                               metadata["PROVIDE"], str(e))
                                        return 0
                                del e
-                       else:
-                               args = [arg for arg, atom in arg_atoms]
 
-               if not pkg.onlydeps:
-                       if not pkg.installed and \
+               reinstall_for_flags = None
+               merging=1
+               if mytype == "installed":
+                       merging = 0
+               if addme and mytype != "installed":
+               # this is where we add the node to the list of packages to merge
+                       if "selective" in self.myparams or not arg:
+                               if "empty" not in self.myparams and vardbapi.cpv_exists(mykey):
+                                       merging=0
+
+                       """ If we aren't merging, perform the --newuse check.
+                           If the package has new iuse flags or different use flags then if
+                           --newuse is specified, we need to merge the package. """
+                       if merging == 0 and \
+                               myroot == self.target_root and \
+                               ("--newuse" in self.myopts or
+                               "--reinstall" in self.myopts) and \
+                               vardbapi.cpv_exists(mykey):
+                               pkgsettings.setcpv(mykey, mydb=mydbapi)
+                               forced_flags = set()
+                               forced_flags.update(pkgsettings.useforce)
+                               forced_flags.update(pkgsettings.usemask)
+                               old_use = vardbapi.aux_get(mykey, ["USE"])[0].split()
+                               iuses = set(filter_iuse_defaults(metadata["IUSE"].split()))
+                               old_iuse = set(filter_iuse_defaults(
+                                       vardbapi.aux_get(mykey, ["IUSE"])[0].split()))
+                               reinstall_for_flags = self._reinstall_for_flags(
+                                       forced_flags, old_use, old_iuse, myuse, iuses)
+                               if reinstall_for_flags:
+                                       merging = 1
+
+               if addme and merging == 1:
+                       mybigkey.append("merge")
+               else:
+                       mybigkey.append("nomerge")
+               jbigkey = tuple(mybigkey)
+
+               if addme:
+                       if merging == 0 and vardbapi.cpv_exists(mykey) and \
+                               mytype != "installed":
+                               mytype = "installed"
+                               mybigkey[0] = "installed"
+                               mydbapi = vardbapi
+                               jbigkey = tuple(mybigkey)
+                               metadata = dict(izip(self._mydbapi_keys,
+                                       mydbapi.aux_get(mykey, self._mydbapi_keys)))
+                               myuse = metadata["USE"].split()
+                       slot_atom = "%s:%s" % (portage.dep_getkey(mykey), metadata["SLOT"])
+                       if merging and \
                                "empty" not in self.myparams and \
-                               vardbapi.match(pkg.slot_atom):
+                               vardbapi.match(slot_atom):
                                # Increase the priority of dependencies on packages that
                                # are being rebuilt. This optimizes merge order so that
                                # dependencies are rebuilt/updated as soon as possible,
@@ -2413,15 +1698,14 @@ class depgraph(object):
                                # are being merged in that case.
                                priority.rebuild = True
 
-                       existing_node = self._slot_pkg_map[pkg.root].get(pkg.slot_atom)
+                       existing_node = self._slot_node_map[myroot].get(
+                               slot_atom, None)
                        slot_collision = False
                        if existing_node:
-                               if pkg.cpv == existing_node.cpv:
+                               e_type, myroot, e_cpv, e_status = existing_node
+                               if mykey == e_cpv:
                                        # The existing node can be reused.
-                                       if args:
-                                               for arg in args:
-                                                       self.digraph.add(existing_node, arg,
-                                                               priority=priority)
+                                       self._parent_child_digraph.add(existing_node, myparent)
                                        # If a direct circular dependency is not an unsatisfied
                                        # buildtime dependency then drop it here since otherwise
                                        # it can skew the merge order calculation in an unwanted
@@ -2432,61 +1716,99 @@ class depgraph(object):
                                                        priority=priority)
                                        return 1
                                else:
-                                       if pkg in self._slot_collision_nodes:
+                                       if jbigkey in self._slot_collision_nodes:
                                                return 1
                                        # A slot collision has occurred.  Sometimes this coincides
                                        # with unresolvable blockers, so the slot collision will be
                                        # shown later if there are no unresolvable blockers.
-                                       self._slot_collision_info.add((pkg.slot_atom, pkg.root))
-                                       self._slot_collision_nodes.add(pkg)
+                                       self._slot_collision_info.add((slot_atom, myroot))
+                                       self._slot_collision_nodes.add(jbigkey)
                                        slot_collision = True
 
                        if slot_collision:
                                # Now add this node to the graph so that self.display()
-                               # can show use flags and --tree portage.output.  This node is
+                               # can show use flags and --tree output.  This node is
                                # only being partially added to the graph.  It must not be
                                # allowed to interfere with the other nodes that have been
                                # added.  Do not overwrite data for existing nodes in
-                               # self.mydbapi since that data will be used for blocker
-                               # validation.
+                               # self.pkg_node_map and self.mydbapi since that data will
+                               # be used for blocker validation.
+                               self.pkg_node_map[myroot].setdefault(mykey, jbigkey)
                                # Even though the graph is now invalid, continue to process
                                # dependencies so that things like --fetchonly can still
                                # function despite collisions.
-                               pass
                        else:
-                               self._slot_pkg_map[pkg.root][pkg.slot_atom] = pkg
-                               self.mydbapi[pkg.root].cpv_inject(pkg)
-
-                       self.digraph.addnode(pkg, myparent, priority=priority)
+                               self.mydbapi[myroot].cpv_inject(mykey, metadata=metadata)
+                               self._slot_node_map[myroot][slot_atom] = jbigkey
+                               self.pkg_node_map[myroot][mykey] = jbigkey
+                               if reinstall_for_flags:
+                                       self._reinstall_nodes[jbigkey] = reinstall_for_flags
+
+                       if rev_dep and myparent:
+                               self.digraph.addnode(myparent, jbigkey,
+                                       priority=priority)
+                       else:
+                               self.digraph.addnode(jbigkey, myparent,
+                                       priority=priority)
 
-                       if not pkg.installed:
+                       if mytype != "installed":
                                # Allow this package to satisfy old-style virtuals in case it
                                # doesn't already. Any pre-existing providers will be preferred
                                # over this one.
                                try:
-                                       pkgsettings.setinst(pkg.cpv, pkg.metadata)
+                                       pkgsettings.setinst(mykey, metadata)
                                        # For consistency, also update the global virtuals.
-                                       settings = self.roots[pkg.root].settings
+                                       settings = self.roots[myroot].settings
                                        settings.unlock()
-                                       settings.setinst(pkg.cpv, pkg.metadata)
+                                       settings.setinst(mykey, metadata)
                                        settings.lock()
                                except portage_exception.InvalidDependString, e:
-                                       show_invalid_depstring_notice(
-                                               pkg, pkg.metadata["PROVIDE"], str(e))
+                                       show_invalid_depstring_notice(jbigkey, metadata["PROVIDE"], str(e))
                                        del e
                                        return 0
 
-               if args:
-                       self._set_nodes.add(pkg)
+                       built = mytype != "ebuild"
+                       installed = mytype == "installed"
+                       if installed:
+                               # Warn if all matching ebuilds are masked or
+                               # the installed package itself is masked. Do
+                               # not warn if there are simply no matching
+                               # ebuilds since that would be annoying in some
+                               # cases:
+                               #
+                               #  - binary packages installed from an overlay
+                               #    that is not listed in PORTDIR_OVERLAY
+                               #
+                               #  - multi-slot atoms listed in the world file
+                               #    to prevent depclean from removing them
+
+                               if arg:
+                                       all_ebuilds_masked = bool(
+                                               portdb.xmatch("match-all", arg) and
+                                               not portdb.xmatch("bestmatch-visible", arg))
+                                       if all_ebuilds_masked:
+                                               self._missing_args.append(arg)
+
+                                       if "selective" not in self.myparams:
+                                               self._show_unsatisfied_dep(
+                                                       myroot, arg, myparent=myparent)
+                                               return 0
+
+                               pkg = Package(type_name=mytype, root=myroot,
+                                       cpv=mykey, built=built, installed=installed,
+                                       metadata=metadata)
+
+                               if not visible(pkgsettings, pkg.cpv, pkg.metadata,
+                                       built=pkg.built, installed=pkg.installed):
+                                       self._masked_installed.append((pkg, pkgsettings))
+
+               if arg:
+                       self._set_nodes.add(jbigkey)
 
                # Do this even when addme is False (--onlydeps) so that the
                # parent/child relationship is always known in case
                # self._show_slot_collision_notice() needs to be called later.
-               if pkg.onlydeps:
-                       self.digraph.add(pkg, myparent, priority=priority)
-               if args:
-                       for arg in args:
-                               self.digraph.add(pkg, arg, priority=priority)
+               self._parent_child_digraph.add(jbigkey, myparent)
 
                """ This section determines whether we go deeper into dependencies or not.
                    We want to go deeper on a few occasions:
@@ -2494,42 +1816,27 @@ class depgraph(object):
                    emerge --deep <pkgspec>; we need to recursively check dependencies of pkgspec
                    If we are in --nodeps (no recursion) mode, we obviously only check 1 level of dependencies.
                """
-               dep_stack = self._dep_stack
-               if "recurse" not in self.myparams:
+               if "deep" not in self.myparams and not merging and \
+                       not ("--update" in self.myopts and arg and merging):
+                       return 1
+               elif "recurse" not in self.myparams:
                        return 1
-               elif pkg.installed and \
-                       "deep" not in self.myparams:
-                       dep_stack = self._ignored_deps
 
                self.spinner.update()
 
-               if args:
-                       depth = 0
-               pkg.depth = depth
-               dep_stack.append(pkg)
-               return 1
-
-       def _add_pkg_deps(self, pkg, allow_unsatisfied=False):
-
-               mytype = pkg.type_name
-               myroot = pkg.root
-               mykey = pkg.cpv
-               metadata = pkg.metadata
-               myuse = pkg.use.enabled
-               jbigkey = pkg
-               depth = pkg.depth + 1
+               """ Check DEPEND/RDEPEND/PDEPEND/SLOT
+               Pull from bintree if it's binary package, porttree if it's ebuild.
+               Binpkg's can be either remote or local. """
 
                edepend={}
                depkeys = ["DEPEND","RDEPEND","PDEPEND"]
                for k in depkeys:
                        edepend[k] = metadata[k]
 
-               if not pkg.built and \
-                       "--buildpkgonly" in self.myopts and \
-                       "deep" not in self.myparams and \
-                       "empty" not in self.myparams:
-                       edepend["RDEPEND"] = ""
-                       edepend["PDEPEND"] = ""
+               if mytype == "ebuild":
+                       if "--buildpkgonly" in self.myopts:
+                               edepend["RDEPEND"] = ""
+                               edepend["PDEPEND"] = ""
                bdeps_satisfied = False
                if mytype in ("installed", "binary"):
                        if self.myopts.get("--with-bdeps", "n") == "y":
@@ -2545,55 +1852,34 @@ class depgraph(object):
                                # built packages do not have build time dependencies.
                                edepend["DEPEND"] = ""
 
-               deps = (
-                       ("/", edepend["DEPEND"],
-                               DepPriority(buildtime=True, satisfied=bdeps_satisfied)),
-                       (myroot, edepend["RDEPEND"], DepPriority(runtime=True)),
-                       (myroot, edepend["PDEPEND"], DepPriority(runtime_post=True))
-               )
+               """ We have retrieve the dependency information, now we need to recursively
+                   process them.  DEPEND gets processed for root = "/", {R,P}DEPEND in myroot. """
+               
+               mp = tuple(mybigkey)
 
-               debug = "--debug" in self.myopts
-               strict = mytype != "installed"
                try:
-                       for dep_root, dep_string, dep_priority in deps:
-                               if pkg.onlydeps:
-                                       # Decrease priority so that --buildpkgonly
-                                       # hasallzeros() works correctly.
-                                       dep_priority = DepPriority()
-                               if not dep_string:
-                                       continue
-                               if debug:
-                                       print
-                                       print "Parent:   ", jbigkey
-                                       print "Depstring:", dep_string
-                                       print "Priority:", dep_priority
-                               vardb = self.roots[dep_root].trees["vartree"].dbapi
-                               try:
-                                       selected_atoms = self._select_atoms(dep_root,
-                                               dep_string, myuse=myuse, parent=pkg, strict=strict)
-                               except portage_exception.InvalidDependString, e:
-                                       show_invalid_depstring_notice(jbigkey, dep_string, str(e))
+                       if not self.select_dep("/", edepend["DEPEND"], myparent=mp,
+                               myuse=myuse, priority=DepPriority(buildtime=True,
+                               satisfied=bdeps_satisfied),
+                               parent_arg=arg):
+                               return 0
+                       """RDEPEND is soft by definition.  However, in order to ensure
+                       correct merge order, we make it a hard dependency.  Otherwise, a
+                       build time dependency might not be usable due to it's run time
+                       dependencies not being installed yet.
+                       """
+                       if not self.select_dep(myroot,edepend["RDEPEND"], myparent=mp,
+                               myuse=myuse, priority=DepPriority(runtime=True),
+                               parent_arg=arg):
+                               return 0
+                       if edepend.has_key("PDEPEND") and edepend["PDEPEND"]:
+                               # Post Depend -- Add to the list without a parent, as it depends
+                               # on a package being present AND must be built after that package.
+                               if not self.select_dep(myroot, edepend["PDEPEND"], myparent=mp,
+                                       myuse=myuse, priority=DepPriority(runtime_post=True),
+                                       parent_arg=arg):
                                        return 0
-                               if debug:
-                                       print "Candidates:", selected_atoms
-                               for atom in selected_atoms:
-                                       blocker = atom.startswith("!")
-                                       if blocker:
-                                               atom = atom[1:]
-                                       mypriority = dep_priority.copy()
-                                       if not blocker and vardb.match(atom):
-                                               mypriority.satisfied = True
-                                       if not self._add_dep(Dependency(atom=atom,
-                                               blocker=blocker, depth=depth, parent=pkg,
-                                               priority=mypriority, root=dep_root),
-                                               allow_unsatisfied=allow_unsatisfied):
-                                               return 0
-                               if debug:
-                                       print "Exiting...", jbigkey
                except ValueError, e:
-                       if not e.args or not isinstance(e.args[0], list) or \
-                               len(e.args[0]) < 2:
-                               raise
                        pkgs = e.args[0]
                        portage.writemsg("\n\n!!! An atom in the dependencies " + \
                                "is not fully-qualified. Multiple matches:\n\n", noiselevel=-1)
@@ -2605,7 +1891,6 @@ class depgraph(object):
                                        "!!! This binary package cannot be installed: '%s'\n" % \
                                        mykey, noiselevel=-1)
                        elif mytype == "ebuild":
-                               portdb = self.roots[myroot].trees["porttree"].dbapi
                                myebuild, mylocation = portdb.findname2(mykey)
                                portage.writemsg("!!! This ebuild cannot be installed: " + \
                                        "'%s'\n" % myebuild, noiselevel=-1)
@@ -2614,92 +1899,16 @@ class depgraph(object):
                        return 0
                return 1
 
-       def _dep_expand(self, root_config, atom_without_category):
-               """
-               @param root_config: a root config instance
-               @type root_config: RootConfig
-               @param atom_without_category: an atom without a category component
-               @type atom_without_category: String
-               @rtype: list
-               @returns: a list of atoms containing categories (possibly empty)
-               """
-               null_cp = portage.dep_getkey(insert_category_into_atom(
-                       atom_without_category, "null"))
-               cat, atom_pn = portage.catsplit(null_cp)
-
-               cp_set = set()
-               for db, pkg_type, built, installed, db_keys in \
-                       self._filtered_trees[root_config.root]["dbs"]:
-                       cp_set.update(db.cp_all())
-               for cp in list(cp_set):
-                       cat, pn = portage.catsplit(cp)
-                       if pn != atom_pn:
-                               cp_set.discard(cp)
-               deps = []
-               for cp in cp_set:
-                       cat, pn = portage.catsplit(cp)
-                       deps.append(insert_category_into_atom(
-                               atom_without_category, cat))
-               return deps
-
-       def _have_new_virt(self, root, atom_cp):
-               ret = False
-               for db, pkg_type, built, installed, db_keys in \
-                       self._filtered_trees[root]["dbs"]:
-                       if db.cp_list(atom_cp):
-                               ret = True
-                               break
-               return ret
-
-       def _iter_atoms_for_pkg(self, pkg):
-               # TODO: add multiple $ROOT support
-               if pkg.root != self.target_root:
-                       return
-               atom_arg_map = self._atom_arg_map
-               root_config = self.roots[pkg.root]
-               for atom in self._set_atoms.iterAtomsForPackage(pkg):
-                       atom_cp = portage.dep_getkey(atom)
-                       if atom_cp != pkg.cp and \
-                               self._have_new_virt(pkg.root, atom_cp):
-                               continue
-                       visible_pkgs = root_config.visible_pkgs.match_pkgs(atom)
-                       visible_pkgs.reverse() # descending order
-                       higher_slot = None
-                       for visible_pkg in visible_pkgs:
-                               if visible_pkg.cp != atom_cp:
-                                       continue
-                               if pkg >= visible_pkg:
-                                       # This is descending order, and we're not
-                                       # interested in any versions <= pkg given.
-                                       break
-                               if pkg.slot_atom != visible_pkg.slot_atom:
-                                       higher_slot = visible_pkg
-                                       break
-                       if higher_slot is not None:
-                               continue
-                       for arg in atom_arg_map[(atom, pkg.root)]:
-                               if isinstance(arg, PackageArg) and \
-                                       arg.package != pkg:
-                                       continue
-                               yield arg, atom
-
-       def select_files(self, myfiles):
-               """Given a list of .tbz2s, .ebuilds sets, and deps, create the
-               appropriate depgraph and return a favorite list."""
-               debug = "--debug" in self.myopts
-               root_config = self.roots[self.target_root]
-               sets = root_config.sets
-               getSetAtoms = root_config.setconfig.getSetAtoms
+       def select_files(self,myfiles):
+               "given a list of .tbz2s, .ebuilds and deps, create the appropriate depgraph and return a favorite list"
                myfavorites=[]
                myroot = self.target_root
-               dbs = self._filtered_trees[myroot]["dbs"]
                vardb = self.trees[myroot]["vartree"].dbapi
-               real_vardb = self._trees_orig[myroot]["vartree"].dbapi
                portdb = self.trees[myroot]["porttree"].dbapi
                bindb = self.trees[myroot]["bintree"].dbapi
+               bindb_keys = list(bindb._aux_cache_keys)
                pkgsettings = self.pkgsettings[myroot]
-               args = []
-               onlydeps = "--onlydeps" in self.myopts
+               arg_atoms = []
                for x in myfiles:
                        ext = os.path.splitext(x)[1]
                        if ext==".tbz2":
@@ -2720,14 +1929,10 @@ class depgraph(object):
                                        os.path.realpath(self.trees[myroot]["bintree"].getname(mykey)):
                                        print colorize("BAD", "\n*** You need to adjust PKGDIR to emerge this package.\n")
                                        return 0, myfavorites
-                               metadata = izip(self._mydbapi_keys,
-                                       bindb.aux_get(mykey, self._mydbapi_keys))
-                               pkg = Package(type_name="binary", root_config=root_config,
-                                       cpv=mykey, built=True, metadata=metadata,
-                                       onlydeps=onlydeps)
-                               self._pkg_cache[pkg] = pkg
-                               args.append(PackageArg(arg=x, package=pkg,
-                                       root_config=root_config))
+                               if not self.create(["binary", myroot, mykey],
+                                       addme=("--onlydeps" not in self.myopts), arg=x):
+                                       return (0,myfavorites)
+                               arg_atoms.append((x, "="+mykey))
                        elif ext==".ebuild":
                                ebuild_path = portage_util.normalize_path(os.path.abspath(x))
                                pkgdir = os.path.dirname(ebuild_path)
@@ -2758,324 +1963,160 @@ class depgraph(object):
                                else:
                                        raise portage_exception.PackageNotFound(
                                                "%s is not in a valid portage tree hierarchy or does not exist" % x)
-                               metadata = izip(self._mydbapi_keys,
-                                       portdb.aux_get(mykey, self._mydbapi_keys))
-                               pkg = Package(type_name="ebuild", root_config=root_config,
-                                       cpv=mykey, metadata=metadata, onlydeps=onlydeps)
-                               pkgsettings.setcpv(pkg)
-                               pkg.metadata["USE"] = pkgsettings["PORTAGE_USE"]
-                               self._pkg_cache[pkg] = pkg
-                               args.append(PackageArg(arg=x, package=pkg,
-                                       root_config=root_config))
-                       elif x.startswith(os.path.sep):
-                               if not x.startswith(myroot):
-                                       portage.writemsg(("\n\n!!! '%s' does not start with" + \
-                                               " $ROOT.\n") % x, noiselevel=-1)
-                                       return 0, []
-                               relative_path = x[len(myroot):]
-                               owner_cpv = None
-                               for pkg, relative_path in \
-                                       real_vardb._owners.iter_owners([relative_path]):
-                                       owner_cpv = pkg.mycpv
-                                       break
-
-                               if owner_cpv is None:
-                                       portage.writemsg(("\n\n!!! '%s' is not claimed " + \
-                                               "by any package.\n") % x, noiselevel=-1)
-                                       return 0, []
-                               slot = vardb.aux_get(owner_cpv, ["SLOT"])[0]
-                               if not slot:
-                                       # portage now masks packages with missing slot, but it's
-                                       # possible that one was installed by an older version
-                                       atom = portage.cpv_getkey(owner_cpv)
-                               else:
-                                       atom = "%s:%s" % (portage.cpv_getkey(owner_cpv), slot)
-                               args.append(AtomArg(arg=atom, atom=atom,
-                                       root_config=root_config))
+                               if not self.create(["ebuild", myroot, mykey],
+                                       None, "--onlydeps" not in self.myopts, arg=x):
+                                       return (0,myfavorites)
+                               arg_atoms.append((x, "="+mykey))
                        else:
-                               if x in ("system", "world"):
-                                       x = SETPREFIX + x
-                               if x.startswith(SETPREFIX):
-                                       s = x[len(SETPREFIX):]
-                                       if s not in sets:
-                                               raise portage_exception.PackageNotFound(
-                                                       "emerge: there are no sets to satisfy '%s'." % s)
-                                       if s in self._sets:
-                                               continue
-                                       # Recursively expand sets so that containment tests in
-                                       # self._get_parent_sets() properly match atoms in nested
-                                       # sets (like if world contains system).
-                                       expanded_set = InternalPackageSet(
-                                               initial_atoms=getSetAtoms(s))
-                                       self._sets[s] = expanded_set
-                                       args.append(SetArg(arg=x, set=expanded_set,
-                                               root_config=root_config))
-                                       myfavorites.append(x)
-                                       if s == "world":
-                                               # pull in the system set too
-                                               s = "system"
-                                               x = SETPREFIX + s
-                                               expanded_set = InternalPackageSet(
-                                                       initial_atoms=getSetAtoms(s))
-                                               self._sets[s] = expanded_set
-                                               args.append(SetArg(arg=x, set=expanded_set,
-                                                       root_config=root_config))
-                                               myfavorites.append(x)
-                                       continue
                                if not is_valid_package_atom(x):
                                        portage.writemsg("\n\n!!! '%s' is not a valid package atom.\n" % x,
                                                noiselevel=-1)
                                        portage.writemsg("!!! Please check ebuild(5) for full details.\n")
                                        portage.writemsg("!!! (Did you specify a version but forget to prefix with '='?)\n")
                                        return (0,[])
-                               # Don't expand categories or old-style virtuals here unless
-                               # necessary. Expansion of old-style virtuals here causes at
-                               # least the following problems:
-                               #   1) It's more difficult to determine which set(s) an atom
-                               #      came from, if any.
-                               #   2) It takes away freedom from the resolver to choose other
-                               #      possible expansions when necessary.
-                               if "/" in x:
-                                       args.append(AtomArg(arg=x, atom=x,
-                                               root_config=root_config))
-                                       continue
-                               expanded_atoms = self._dep_expand(root_config, x)
-                               installed_cp_set = set()
-                               for atom in expanded_atoms:
-                                       atom_cp = portage.dep_getkey(atom)
-                                       if vardb.cp_list(atom_cp):
-                                               installed_cp_set.add(atom_cp)
-                               if len(expanded_atoms) > 1 and len(installed_cp_set) == 1:
-                                       installed_cp = iter(installed_cp_set).next()
-                                       expanded_atoms = [atom for atom in expanded_atoms \
-                                               if portage.dep_getkey(atom) == installed_cp]
-
-                               if len(expanded_atoms) > 1:
+                               try:
+                                       mykey = None
+                                       if "--usepkg" in self.myopts:
+                                               mykey = portage.dep_expand(x, mydb=bindb,
+                                                       settings=pkgsettings)
+                                       if ("--usepkgonly" in self.myopts or mykey) and \
+                                               not portage.dep_getkey(mykey).startswith("null/"):
+                                               arg_atoms.append((x, mykey))
+                                               continue
+
+                                       if "--usepkgonly" in self.myopts:
+                                               mykey = portage.dep_expand(x, mydb=vardb,
+                                                       settings=pkgsettings)
+                                               arg_atoms.append((x, mykey))
+                                               continue
+
+                                       try:
+                                               mykey = portage.dep_expand(x,
+                                                       mydb=portdb, settings=pkgsettings)
+                                       except ValueError, e:
+                                               mykey = portage.dep_expand(x,
+                                                       mydb=vardb, settings=pkgsettings)
+                                               cp = portage.dep_getkey(mykey)
+                                               if cp.startswith("null/") or \
+                                                       cp not in e[0]:
+                                                       raise
+                                               del e
+                                       arg_atoms.append((x, mykey))
+                               except ValueError, errpkgs:
                                        print "\n\n!!! The short ebuild name \"" + x + "\" is ambiguous.  Please specify"
                                        print "!!! one of the following fully-qualified ebuild names instead:\n"
-                                       expanded_atoms = set(portage.dep_getkey(atom) \
-                                               for atom in expanded_atoms)
-                                       for i in sorted(expanded_atoms):
+                                       for i in errpkgs[0]:
                                                print "    " + green(i)
                                        print
-                                       return False, myfavorites
-                               if expanded_atoms:
-                                       atom = expanded_atoms[0]
-                               else:
-                                       null_atom = insert_category_into_atom(x, "null")
-                                       null_cp = portage.dep_getkey(null_atom)
-                                       cat, atom_pn = portage.catsplit(null_cp)
-                                       virts_p = root_config.settings.get_virts_p().get(atom_pn)
-                                       if virts_p:
-                                               # Allow the depgraph to choose which virtual.
-                                               atom = insert_category_into_atom(x, "virtual")
-                                       else:
-                                               atom = insert_category_into_atom(x, "null")
-
-                               args.append(AtomArg(arg=x, atom=atom,
-                                       root_config=root_config))
+                                       sys.exit(1)
 
                if "--update" in self.myopts:
-                       # Enable greedy SLOT atoms for atoms given as arguments.
-                       # This is currently disabled for sets since greedy SLOT
-                       # atoms could be a property of the set itself.
+                       """Make sure all installed slots are updated when possible. Do this
+                       with --emptytree also, to ensure that all slots are remerged."""
+                       vardb = self.trees[self.target_root]["vartree"].dbapi
                        greedy_atoms = []
-                       for arg in args:
-                               # In addition to any installed slots, also try to pull
-                               # in the latest new slot that may be available.
-                               greedy_atoms.append(arg)
-                               if not isinstance(arg, (AtomArg, PackageArg)):
-                                       continue
-                               atom_cp = portage.dep_getkey(arg.atom)
-                               slots = set()
-                               for cpv in vardb.match(arg.atom):
-                                       slots.add(vardb.aux_get(cpv, ["SLOT"])[0])
-                               for slot in slots:
-                                       greedy_atoms.append(
-                                               AtomArg(arg=arg.arg, atom="%s:%s" % (atom_cp, slot),
-                                                       root_config=root_config))
-                       args = greedy_atoms
-                       del greedy_atoms
-
-               # Create the "args" package set from atoms and
-               # packages given as arguments.
+                       for myarg, myatom in arg_atoms:
+                               greedy_atoms.append((myarg, myatom))
+                               myslots = set()
+                               for cpv in vardb.match(myatom):
+                                       myslots.add(vardb.aux_get(cpv, ["SLOT"])[0])
+                               if myslots:
+                                       best_pkgs = []
+                                       if "--usepkg" in self.myopts:
+                                               best_pkg = None
+                                               for cpv in reversed(bindb.match(myatom)):
+                                                       metadata = dict(izip(bindb_keys,
+                                                               bindb.aux_get(cpv, bindb_keys)))
+                                                       if visible(pkgsettings, cpv, metadata, built=True):
+                                                               best_pkg = cpv
+                                                               break
+                                               if best_pkg:
+                                                       best_slot = bindb.aux_get(best_pkg, ["SLOT"])[0]
+                                                       best_pkgs.append(("binary", best_pkg, best_slot))
+                                       if "--usepkgonly" not in self.myopts:
+                                               best_pkg = portage.best(portdb.match(myatom))
+                                               if best_pkg:
+                                                       best_slot = portdb.aux_get(best_pkg, ["SLOT"])[0]
+                                                       best_pkgs.append(("ebuild", best_pkg, best_slot))
+                                       if best_pkgs:
+                                               best_pkg = portage.best([x[1] for x in best_pkgs])
+                                               best_pkgs = [x for x in best_pkgs if x[1] == best_pkg]
+                                               best_slot = best_pkgs[0][2]
+                                               myslots.add(best_slot)
+                               if len(myslots) > 1:
+                                       for myslot in myslots:
+                                               myslot_atom = "%s:%s" % \
+                                                       (portage.dep_getkey(myatom), myslot)
+                                               available = False
+                                               if "--usepkgonly" not in self.myopts and \
+                                                       self.trees[self.target_root][
+                                                       "porttree"].dbapi.match(myslot_atom):
+                                                       available = True
+                                               elif "--usepkg" in self.myopts:
+                                                       for cpv in bindb.match(myslot_atom):
+                                                               metadata = dict(izip(bindb_keys,
+                                                                       bindb.aux_get(cpv, bindb_keys)))
+                                                               if visible(pkgsettings, cpv, metadata, built=True):
+                                                                       available = True
+                                                                       break
+                                               if available:
+                                                       greedy_atoms.append((myarg, myslot_atom))
+                       arg_atoms = greedy_atoms
+
+               oneshot = "--oneshot" in self.myopts or \
+                       "--onlydeps" in self.myopts
+               """ These are used inside self.create() in order to ensure packages
+               that happen to match arguments are not incorrectly marked as nomerge."""
                args_set = self._sets["args"]
-               for arg in args:
-                       if not isinstance(arg, (AtomArg, PackageArg)):
-                               continue
-                       myatom = arg.atom
+               for myarg, myatom in arg_atoms:
                        if myatom in args_set:
                                continue
                        args_set.add(myatom)
-                       myfavorites.append(myatom)
-               self._set_atoms.update(chain(*self._sets.itervalues()))
-               atom_arg_map = self._atom_arg_map
-               for arg in args:
-                       for atom in arg.set:
-                               atom_key = (atom, myroot)
-                               refs = atom_arg_map.get(atom_key)
-                               if refs is None:
-                                       refs = []
-                                       atom_arg_map[atom_key] = refs
-                                       if arg not in refs:
-                                               refs.append(arg)
-               pprovideddict = pkgsettings.pprovideddict
-               if debug:
-                       portage.writemsg("\n", noiselevel=-1)
-               # Order needs to be preserved since a feature of --nodeps
-               # is to allow the user to force a specific merge order.
-               args.reverse()
-               while args:
-                       arg = args.pop()
-                       for atom in arg.set:
-                               self.spinner.update()
-                               atom_cp = portage.dep_getkey(atom)
+                       self._set_atoms.add(myatom)
+                       if not oneshot:
+                               myfavorites.append(myatom)
+               for myarg, myatom in arg_atoms:
                                try:
-                                       pprovided = pprovideddict.get(portage.dep_getkey(atom))
-                                       if pprovided and portage.match_from_list(atom, pprovided):
-                                               # A provided package has been specified on the command line.
-                                               self._pprovided_args.append((arg, atom))
-                                               continue
-                                       if isinstance(arg, PackageArg):
-                                               if not self._add_pkg(arg.package, arg) or \
-                                                       not self._create_graph():
-                                                       sys.stderr.write(("\n\n!!! Problem resolving " + \
-                                                               "dependencies for %s\n") % arg.arg)
-                                                       return 0, myfavorites
-                                               continue
-                                       if debug:
-                                               portage.writemsg("      Arg: %s\n     Atom: %s\n" % \
-                                                       (arg, atom), noiselevel=-1)
-                                       pkg, existing_node = self._select_package(
-                                               myroot, atom, onlydeps=onlydeps)
-                                       if not pkg:
-                                               if not (isinstance(arg, SetArg) and \
-                                                       arg.name in ("system", "world")):
-                                                       self._unsatisfied_deps_for_display.append(
-                                                               ((myroot, atom), {}))
-                                                       return 0, myfavorites
-                                               self._missing_args.append((arg, atom))
-                                               continue
-                                       if atom_cp != pkg.cp:
-                                               # For old-style virtuals, we need to repeat the
-                                               # package.provided check against the selected package.
-                                               expanded_atom = atom.replace(atom_cp, pkg.cp)
-                                               pprovided = pprovideddict.get(pkg.cp)
-                                               if pprovided and \
-                                                       portage.match_from_list(expanded_atom, pprovided):
-                                                       # A provided package has been
-                                                       # specified on the command line.
-                                                       self._pprovided_args.append((arg, atom))
-                                                       continue
-                                       if pkg.installed and "selective" not in self.myparams:
-                                               self._unsatisfied_deps_for_display.append(
-                                                       ((myroot, atom), {}))
-                                               # Previous behavior was to bail out in this case, but
-                                               # since the dep is satisfied by the installed package,
-                                               # it's more friendly to continue building the graph
-                                               # and just show a warning message. Therefore, only bail
-                                               # out here if the atom is not from either the system or
-                                               # world set.
-                                               if not (isinstance(arg, SetArg) and \
-                                                       arg.name in ("system", "world")):
-                                                       return 0, myfavorites
-
-                                       dep = Dependency(atom=atom, onlydeps=onlydeps,
-                                               root=myroot, parent=arg)
-
-                                       # Add the selected package to the graph as soon as possible
-                                       # so that later dep_check() calls can use it as feedback
-                                       # for making more consistent atom selections.
-                                       if not self._add_pkg(pkg, dep.parent,
-                                               priority=dep.priority, depth=dep.depth):
-                                               if isinstance(arg, SetArg):
-                                                       sys.stderr.write(("\n\n!!! Problem resolving " + \
-                                                               "dependencies for %s from %s\n") % \
-                                                               (atom, arg.arg))
-                                               else:
-                                                       sys.stderr.write(("\n\n!!! Problem resolving " + \
-                                                               "dependencies for %s\n") % atom)
-                                               return 0, myfavorites
-
+                                       self.mysd = self.select_dep(myroot, myatom, arg=myarg)
                                except portage_exception.MissingSignature, e:
                                        portage.writemsg("\n\n!!! A missing gpg signature is preventing portage from calculating the\n")
                                        portage.writemsg("!!! required dependencies. This is a security feature enabled by the admin\n")
                                        portage.writemsg("!!! to aid in the detection of malicious intent.\n\n")
                                        portage.writemsg("!!! THIS IS A POSSIBLE INDICATION OF TAMPERED FILES -- CHECK CAREFULLY.\n")
                                        portage.writemsg("!!! Affected file: %s\n" % (e), noiselevel=-1)
-                                       return 0, myfavorites
+                                       sys.exit(1)
                                except portage_exception.InvalidSignature, e:
                                        portage.writemsg("\n\n!!! An invalid gpg signature is preventing portage from calculating the\n")
                                        portage.writemsg("!!! required dependencies. This is a security feature enabled by the admin\n")
                                        portage.writemsg("!!! to aid in the detection of malicious intent.\n\n")
                                        portage.writemsg("!!! THIS IS A POSSIBLE INDICATION OF TAMPERED FILES -- CHECK CAREFULLY.\n")
                                        portage.writemsg("!!! Affected file: %s\n" % (e), noiselevel=-1)
-                                       return 0, myfavorites
+                                       sys.exit(1)
                                except SystemExit, e:
                                        raise # Needed else can't exit
                                except Exception, e:
-                                       print >> sys.stderr, "\n\n!!! Problem in '%s' dependencies." % atom
+                                       print >> sys.stderr, "\n\n!!! Problem in '%s' dependencies." % mykey
                                        print >> sys.stderr, "!!!", str(e), getattr(e, "__module__", None)
                                        raise
 
-               # Now that the root packages have been added to the graph,
-               # process the dependencies.
-               if not self._create_graph():
-                       return 0, myfavorites
+                               if not self.mysd:
+                                       return (0,myfavorites)
 
                missing=0
                if "--usepkgonly" in self.myopts:
                        for xs in self.digraph.all_nodes():
-                               if not isinstance(xs, Package):
-                                       continue
                                if len(xs) >= 4 and xs[0] != "binary" and xs[3] == "merge":
                                        if missing == 0:
                                                print
                                        missing += 1
                                        print "Missing binary for:",xs[2]
 
-               try:
-                       self.altlist()
-               except self._unknown_internal_error:
+               if not self.validate_blockers():
                        return False, myfavorites
-
+               
                # We're true here unless we are missing binaries.
                return (not missing,myfavorites)
 
-       def _select_atoms_from_graph(self, *pargs, **kwargs):
-               """
-               Prefer atoms matching packages that have already been
-               added to the graph or those that are installed and have
-               not been scheduled for replacement.
-               """
-               kwargs["trees"] = self._graph_trees
-               return self._select_atoms_highest_available(*pargs, **kwargs)
-
-       def _select_atoms_highest_available(self, root, depstring,
-               myuse=None, parent=None, strict=True, trees=None):
-               """This will raise InvalidDependString if necessary. If trees is
-               None then self._filtered_trees is used."""
-               pkgsettings = self.pkgsettings[root]
-               if trees is None:
-                       trees = self._filtered_trees
-               if True:
-                       try:
-                               if parent is not None:
-                                       trees[root]["parent"] = parent
-                               if not strict:
-                                       portage_dep._dep_check_strict = False
-                               mycheck = portage.dep_check(depstring, None,
-                                       pkgsettings, myuse=myuse,
-                                       myroot=root, trees=trees)
-                       finally:
-                               if parent is not None:
-                                       trees[root].pop("parent")
-                               portage_dep._dep_check_strict = True
-                       if not mycheck[0]:
-                               raise portage_exception.InvalidDependString(mycheck[1])
-                       selected_atoms = mycheck[1]
-               return selected_atoms
-
        def _show_unsatisfied_dep(self, root, atom, myparent=None, arg=None):
                xinfo = '"%s"' % atom
                if arg:
@@ -3092,10 +2133,20 @@ class depgraph(object):
                pkgsettings = self.pkgsettings[root]
                root_config = self.roots[root]
                portdb = self.roots[root].trees["porttree"].dbapi
-               dbs = self._filtered_trees[root]["dbs"]
+               dbs = []
+               portdb = self.trees[root]["porttree"].dbapi
+               bindb  = self.trees[root]["bintree"].dbapi
+               vardb  = self.trees[root]["vartree"].dbapi
+               #               (db, pkg_type, built, installed, db_keys)
+               if "--usepkgonly" not in self.myopts:
+                       db_keys = list(portdb._aux_cache_keys)
+                       dbs.append((portdb, "ebuild", False, False, db_keys))
+               if "--usepkg" in self.myopts:
+                       db_keys = list(bindb._aux_cache_keys)
+                       dbs.append((bindb,  "binary", True, False, db_keys))
+               db_keys = self._mydbapi_keys
+               dbs.append((vardb, "installed", True, True, db_keys))
                for db, pkg_type, built, installed, db_keys in dbs:
-                       if installed:
-                               continue
                        match = db.match
                        if hasattr(db, "xmatch"):
                                cpv_list = db.xmatch("match-all", atom)
@@ -3123,452 +2174,274 @@ class depgraph(object):
                                for line in wrap(msg, 75):
                                        print line
                        print
-                       show_mask_docs()
+                       print "For more information, see MASKED PACKAGES section in the emerge man page or "
+                       print "refer to the Gentoo Handbook."
                else:
                        print "\nemerge: there are no ebuilds to satisfy "+green(xinfo)+"."
                if myparent:
                        print xfrom
                print
 
-       def _select_pkg_highest_available(self, root, atom, onlydeps=False):
-               cache_key = (root, atom, onlydeps)
-               ret = self._highest_pkg_cache.get(cache_key)
-               if ret is not None:
-                       pkg, existing = ret
-                       if pkg and not existing:
-                               existing = self._slot_pkg_map[root].get(pkg.slot_atom)
-                               if existing and existing == pkg:
-                                       # Update the cache to reflect that the
-                                       # package has been added to the graph.
-                                       ret = pkg, pkg
-                                       self._highest_pkg_cache[cache_key] = ret
-                       return ret
-               ret = self._select_pkg_highest_available_imp(root, atom, onlydeps=onlydeps)
-               self._highest_pkg_cache[cache_key] = ret
-               return ret
-
-       def _select_pkg_highest_available_imp(self, root, atom, onlydeps=False):
-               root_config = self.roots[root]
-               pkgsettings = self.pkgsettings[root]
-               dbs = self._filtered_trees[root]["dbs"]
-               vardb = self.roots[root].trees["vartree"].dbapi
-               portdb = self.roots[root].trees["porttree"].dbapi
-               # List of acceptable packages, ordered by type preference.
-               matched_packages = []
-               highest_version = None
-               if not isinstance(atom, portage_dep.Atom):
-                       atom = portage_dep.Atom(atom)
-               atom_cp = atom.cp
-               existing_node = None
-               myeb = None
-               usepkgonly = "--usepkgonly" in self.myopts
-               empty = "empty" in self.myparams
-               selective = "selective" in self.myparams
-               reinstall = False
-               noreplace = "--noreplace" in self.myopts
-               # Behavior of the "selective" parameter depends on
-               # whether or not a package matches an argument atom.
-               # If an installed package provides an old-style
-               # virtual that is no longer provided by an available
-               # package, the installed package may match an argument
-               # atom even though none of the available packages do.
-               # Therefore, "selective" logic does not consider
-               # whether or not an installed package matches an
-               # argument atom. It only considers whether or not
-               # available packages match argument atoms, which is
-               # represented by the found_available_arg flag.
-               found_available_arg = False
-               for find_existing_node in True, False:
-                       if existing_node:
-                               break
-                       for db, pkg_type, built, installed, db_keys in dbs:
-                               if existing_node:
-                                       break
-                               if installed and not find_existing_node:
-                                       want_reinstall = reinstall or empty or \
-                                               (found_available_arg and not selective)
-                                       if want_reinstall and matched_packages:
-                                               continue
-                               if hasattr(db, "xmatch"):
-                                       cpv_list = db.xmatch("match-all", atom)
+       def select_dep(self, myroot, depstring, myparent=None, arg=None,
+               myuse=None, raise_on_missing=False, priority=DepPriority(),
+               rev_deps=False, parent_arg=None):
+               """ Given a depstring, create the depgraph such that all dependencies are satisfied.
+                   myroot = $ROOT from environment, where {R,P}DEPENDs are merged to.
+                   myparent = the node whose depstring is being passed in
+                   arg = package was specified on the command line, merge even if it's already installed
+                   myuse = USE flags at present
+                   raise_on_missing = Given that the depgraph is not proper, raise an exception if true
+                   else continue trying.
+                   return 1 on success, 0 for failure
+               """
+
+               portdb = self.trees[myroot]["porttree"].dbapi
+               bindb  = self.trees[myroot]["bintree"].dbapi
+               vardb  = self.trees[myroot]["vartree"].dbapi
+               pkgsettings = self.pkgsettings[myroot]
+               if myparent:
+                       p_type, p_root, p_key, p_status = myparent
+
+               if "--debug" in self.myopts:
+                       print
+                       print "Parent:   ",myparent
+                       print "Depstring:",depstring
+                       if rev_deps:
+                               print "Reverse:", rev_deps
+                       print "Priority:", priority
+
+               #processing dependencies
+               """ Call portage.dep_check to evaluate the use? conditionals and make sure all
+               dependencies are satisfiable. """
+               if arg:
+                       mymerge = [depstring]
+                       pprovided = pkgsettings.pprovideddict.get(
+                               portage.dep_getkey(depstring))
+                       if pprovided and portage.match_from_list(depstring, pprovided):
+                               mymerge = []
+               else:
+                       try:
+                               if myparent and p_status == "nomerge":
+                                       portage_dep._dep_check_strict = False
+                               mycheck = portage.dep_check(depstring, None,
+                                       pkgsettings, myuse=myuse,
+                                       use_binaries=("--usepkgonly" in self.myopts),
+                                       myroot=myroot, trees=self.trees)
+                       finally:
+                               portage_dep._dep_check_strict = True
+
+                       if not mycheck[0]:
+                               if myparent:
+                                       show_invalid_depstring_notice(
+                                               myparent, depstring, mycheck[1])
                                else:
-                                       cpv_list = db.match(atom)
-
-                               # USE=multislot can make an installed package appear as if
-                               # it doesn't satisfy a slot dependency. Rebuilding the ebuild
-                               # won't do any good as long as USE=multislot is enabled since
-                               # the newly built package still won't have the expected slot.
-                               # Therefore, assume that such SLOT dependencies are already
-                               # satisfied rather than forcing a rebuild.
-                               if installed and not cpv_list and atom.slot:
-                                       for cpv in db.match(atom.cp):
-                                               slot_available = False
-                                               for other_db, other_type, other_built, \
-                                                       other_installed, other_keys in dbs:
-                                                       try:
-                                                               if atom.slot == \
-                                                                       other_db.aux_get(cpv, ["SLOT"])[0]:
-                                                                       slot_available = True
-                                                                       break
-                                                       except KeyError:
-                                                               pass
-                                               if not slot_available:
-                                                       continue
-                                               inst_pkg = self._pkg(cpv, "installed",
-                                                       root_config, installed=installed)
-                                               # Remove the slot from the atom and verify that
-                                               # the package matches the resulting atom.
-                                               atom_without_slot = portage_dep.remove_slot(atom)
-                                               atom_without_slot = portage_dep.Atom(atom_without_slot)
-                                               if portage.match_from_list(
-                                                       atom_without_slot, [inst_pkg]):
-                                                       cpv_list = [inst_pkg.cpv]
-                                               break
+                                       sys.stderr.write("\n%s\n%s\n" % (depstring, mycheck[1]))
+                               return 0
+                       mymerge = mycheck[1]
 
-                               if not cpv_list:
-                                       continue
-                               pkg_status = "merge"
-                               if installed or onlydeps:
-                                       pkg_status = "nomerge"
-                               # descending order
-                               cpv_list.reverse()
-                               for cpv in cpv_list:
-                                       # Make --noreplace take precedence over --newuse.
-                                       if not installed and noreplace and \
-                                               cpv in vardb.match(atom):
-                                               # If the installed version is masked, it may
-                                               # be necessary to look at lower versions,
-                                               # in case there is a visible downgrade.
+               if not mymerge and arg:
+                       # A provided package has been specified on the command line.  The
+                       # package will not be merged and a warning will be displayed.
+                       if depstring in self._set_atoms:
+                               self._pprovided_args.append((arg, depstring))
+
+               if "--debug" in self.myopts:
+                       print "Candidates:",mymerge
+               for x in mymerge:
+                       selected_pkg = None
+                       if x.startswith("!"):
+                               if "--buildpkgonly" not in self.myopts and \
+                                       "--nodeps" not in self.myopts and \
+                                       myparent not in self._slot_collision_nodes:
+                                       p_type, p_root, p_key, p_status = myparent
+                                       if  p_type != "installed" and p_status != "merge":
+                                               # It's safe to ignore blockers from --onlydeps nodes.
                                                continue
-                                       reinstall_for_flags = None
-                                       cache_key = (pkg_type, root, cpv, pkg_status)
-                                       calculated_use = True
-                                       pkg = self._pkg_cache.get(cache_key)
-                                       if pkg is None:
-                                               calculated_use = False
-                                               try:
-                                                       metadata = izip(self._mydbapi_keys,
-                                                               db.aux_get(cpv, self._mydbapi_keys))
-                                               except KeyError:
+                                       self.blocker_parents.setdefault(
+                                               ("blocks", p_root, x[1:]), set()).add(myparent)
+                               continue
+                       else:
+                               # List of acceptable packages, ordered by type preference.
+                               matched_packages = []
+                               myeb_matches = portdb.xmatch("match-visible", x)
+                               myeb = None
+                               myeb_pkg = None
+                               metadata = None
+                               existing_node = None
+                               if myeb_matches:
+                                       myeb = portage.best(myeb_matches)
+                                       # For best performance, try to reuse an exising node
+                                       # and it's cached metadata. The portdbapi caches SLOT
+                                       # metadata in memory so it's really only pulled once.
+                                       slot_atom = "%s:%s" % (portage.dep_getkey(myeb),
+                                               portdb.aux_get(myeb, ["SLOT"])[0])
+                                       existing_node = self._slot_node_map[myroot].get(slot_atom)
+                                       if existing_node:
+                                               e_type, myroot, e_cpv, e_status = existing_node
+                                               metadata = dict(izip(self._mydbapi_keys,
+                                                       self.mydbapi[myroot].aux_get(e_cpv, self._mydbapi_keys)))
+                                               cpv_slot = "%s:%s" % (e_cpv, metadata["SLOT"])
+                                               if portage.match_from_list(x, [cpv_slot]):
+                                                       matched_packages.append(
+                                                               ([e_type, myroot, e_cpv], metadata))
+                                               else:
+                                                       existing_node = None
+
+                               if not existing_node and \
+                                       "--usepkg" in self.myopts:
+                                       # The next line assumes the binarytree has been populated.
+                                       # XXX: Need to work out how we use the binary tree with roots.
+                                       usepkgonly = "--usepkgonly" in self.myopts
+                                       chost = pkgsettings["CHOST"]
+                                       myeb_pkg_matches = []
+                                       bindb_keys = list(bindb._aux_cache_keys)
+                                       for pkg in bindb.match(x):
+                                               metadata = dict(izip(bindb_keys,
+                                                       bindb.aux_get(pkg, bindb_keys)))
+                                               if not visible(pkgsettings, pkg, metadata, built=True):
                                                        continue
-                                               pkg = Package(built=built, cpv=cpv,
-                                                       installed=installed, metadata=metadata,
-                                                       onlydeps=onlydeps, root_config=root_config,
-                                                       type_name=pkg_type)
-                                               metadata = pkg.metadata
-                                               if not built and ("?" in metadata["LICENSE"] or \
-                                                       "?" in metadata["PROVIDE"]):
-                                                       # This is avoided whenever possible because
-                                                       # it's expensive. It only needs to be done here
-                                                       # if it has an effect on visibility.
-                                                       pkgsettings.setcpv(pkg)
-                                                       metadata["USE"] = pkgsettings["PORTAGE_USE"]
-                                                       calculated_use = True
-                                               self._pkg_cache[pkg] = pkg
-
-                                       if not installed or (installed and matched_packages):
-                                               # Only enforce visibility on installed packages
-                                               # if there is at least one other visible package
-                                               # available. By filtering installed masked packages
-                                               # here, packages that have been masked since they
-                                               # were installed can be automatically downgraded
-                                               # to an unmasked version.
-                                               try:
-                                                       if not visible(pkgsettings, pkg):
-                                                               continue
-                                               except portage_exception.InvalidDependString:
-                                                       if not installed:
-                                                               continue
-
-                                               # Enable upgrade or downgrade to a version
-                                               # with visible KEYWORDS when the installed
-                                               # version is masked by KEYWORDS, but never
-                                               # reinstall the same exact version only due
-                                               # to a KEYWORDS mask.
-                                               if installed and matched_packages and \
-                                                       pkgsettings._getMissingKeywords(
-                                                       pkg.cpv, pkg.metadata):
-                                                       different_version = None
-                                                       for avail_pkg in matched_packages:
-                                                               if not portage_dep.cpvequal(
-                                                                       pkg.cpv, avail_pkg.cpv):
-                                                                       different_version = avail_pkg
-                                                                       break
-                                                       if different_version is not None:
-                                                               # Only reinstall for KEYWORDS if
-                                                               # it's not the same version.
-                                                               continue
-
-                                       if not built and not calculated_use:
-                                               # This is avoided whenever possible because
-                                               # it's expensive.
-                                               pkgsettings.setcpv(pkg)
-                                               pkg.metadata["USE"] = pkgsettings["PORTAGE_USE"]
+                                               myeb_pkg_matches.append(pkg)
+                                       if myeb_pkg_matches:
+                                               myeb_pkg = portage.best(myeb_pkg_matches)
+                                               # For best performance, try to reuse an exising node
+                                               # and it's cached metadata. The bindbapi caches SLOT
+                                               # metadata in memory so it's really only pulled once.
+                                               slot_atom = "%s:%s" % (portage.dep_getkey(myeb_pkg),
+                                                       bindb.aux_get(myeb_pkg, ["SLOT"])[0])
+                                               existing_node = self._slot_node_map[myroot].get(slot_atom)
+                                               if existing_node:
+                                                       e_type, myroot, e_cpv, e_status = existing_node
+                                                       metadata = dict(izip(self._mydbapi_keys,
+                                                               self.mydbapi[myroot].aux_get(e_cpv, self._mydbapi_keys)))
+                                                       cpv_slot = "%s:%s" % (e_cpv, metadata["SLOT"])
+                                                       if portage.match_from_list(x, [cpv_slot]):
+                                                               myeb_pkg = None
+                                                               matched_packages.append(
+                                                                       ([e_type, myroot, e_cpv], metadata))
+                                                       else:
+                                                               existing_node = None
+                                               if not existing_node:
+                                                       # For best performance, avoid pulling
+                                                       # metadata whenever possible.
+                                                       metadata = dict(izip(self._mydbapi_keys,
+                                                               bindb.aux_get(myeb_pkg, self._mydbapi_keys)))
+
+                               if not existing_node and \
+                                       myeb_pkg and \
+                                       ("--newuse" in self.myopts or \
+                                       "--reinstall" in self.myopts):
+                                       iuses = set(filter_iuse_defaults(metadata["IUSE"].split()))
+                                       old_use = metadata["USE"].split()
+                                       mydb = None
+                                       if "--usepkgonly" not in self.myopts and myeb:
+                                               mydb = portdb
+                                       if myeb:
+                                               pkgsettings.setcpv(myeb, mydb=mydb)
+                                       else:
+                                               pkgsettings.setcpv(myeb_pkg, mydb=mydb)
+                                       now_use = pkgsettings["USE"].split()
+                                       forced_flags = set()
+                                       forced_flags.update(pkgsettings.useforce)
+                                       forced_flags.update(pkgsettings.usemask)
+                                       cur_iuse = iuses
+                                       if "--usepkgonly" not in self.myopts and myeb:
+                                               cur_iuse = set(filter_iuse_defaults(
+                                                       portdb.aux_get(myeb, ["IUSE"])[0].split()))
+                                       if self._reinstall_for_flags(
+                                               forced_flags, old_use, iuses, now_use, cur_iuse):
+                                               myeb_pkg = None
+                               if myeb_pkg:
+                                       matched_packages.append(
+                                               (["binary", myroot, myeb_pkg], metadata))
+
+                               if not existing_node and \
+                                       myeb and \
+                                       "--usepkgonly" not in self.myopts:
+                                       metadata = dict(izip(self._mydbapi_keys,
+                                               portdb.aux_get(myeb, self._mydbapi_keys)))
+                                       pkgsettings.setcpv(myeb, mydb=portdb)
+                                       metadata["USE"] = pkgsettings["USE"]
+                                       matched_packages.append(
+                                               (["ebuild", myroot, myeb], metadata))
+
+                               if not matched_packages and \
+                                       not (arg and "selective" not in self.myparams):
+                                       """Fall back to the installed package database.  This is a
+                                       last resort because the metadata tends to diverge from that
+                                       of the ebuild in the tree."""
+                                       myeb_inst_matches = vardb.match(x)
+                                       myeb_inst = None
+                                       if myeb_inst_matches:
+                                               myeb_inst = portage.best(myeb_inst_matches)
+                                       if myeb_inst:
+                                               metadata = dict(izip(self._mydbapi_keys,
+                                                       vardb.aux_get(myeb_inst, self._mydbapi_keys)))
+                                               matched_packages.append(
+                                                       (["installed", myroot, myeb_inst], metadata))
+
+                               if not matched_packages:
+                                       if raise_on_missing:
+                                               raise portage_exception.PackageNotFound(x)
+                                       self._show_unsatisfied_dep(myroot, x,
+                                               myparent=myparent)
+                                       return 0
 
+                               if "--debug" in self.myopts:
+                                       for pkg, metadata in matched_packages:
+                                               print (pkg[0] + ":").rjust(10), pkg[2]
+
+                               if len(matched_packages) > 1:
+                                       bestmatch = portage.best(
+                                               [pkg[2] for pkg, metadata in matched_packages])
+                                       matched_packages = [pkg for pkg in matched_packages \
+                                               if pkg[0][2] == bestmatch]
+
+                               # ordered by type preference ("ebuild" type is the last resort)
+                               selected_pkg =  matched_packages[0]
+
+                               # In some cases, dep_check will return deps that shouldn't
+                               # be proccessed any further, so they are identified and
+                               # discarded here. Try to discard as few as possible since
+                               # discarded dependencies reduce the amount of information
+                               # available for optimization of merge order.
+                               if myparent and not arg and vardb.match(x) and \
+                                       not existing_node and \
+                                       "empty" not in self.myparams and \
+                                       "deep" not in self.myparams and \
+                                       not ("--update" in self.myopts and parent_arg):
+                                       (mytype, myroot, mykey), metadata = selected_pkg
                                        myarg = None
-                                       if root == self.target_root:
+                                       if myroot == self.target_root:
                                                try:
-                                                       # Ebuild USE must have been calculated prior
-                                                       # to this point, in case atoms have USE deps.
-                                                       myarg = self._iter_atoms_for_pkg(pkg).next()
-                                               except StopIteration:
-                                                       pass
+                                                       myarg = self._set_atoms.findAtomForPackage(
+                                                               mykey, metadata)
                                                except portage_exception.InvalidDependString:
-                                                       if not installed:
-                                                               # masked by corruption
-                                                               continue
-                                       if not installed and myarg:
-                                               found_available_arg = True
-
-                                       if pkg.cp == atom_cp:
-                                               if highest_version is None:
-                                                       highest_version = pkg
-                                               elif pkg > highest_version:
-                                                       highest_version = pkg
-                                       # At this point, we've found the highest visible
-                                       # match from the current repo. Any lower versions
-                                       # from this repo are ignored, so this so the loop
-                                       # will always end with a break statement below
-                                       # this point.
-                                       if find_existing_node:
-                                               e_pkg = self._slot_pkg_map[root].get(pkg.slot_atom)
-                                               if not e_pkg:
-                                                       break
-                                               if portage_dep.match_from_list(atom, [e_pkg]):
-                                                       if highest_version and \
-                                                               e_pkg.cp == atom_cp and \
-                                                               e_pkg < highest_version and \
-                                                               e_pkg.slot_atom != highest_version.slot_atom:
-                                                               # There is a higher version available in a
-                                                               # different slot, so this existing node is
-                                                               # irrelevant.
-                                                               pass
-                                                       else:
-                                                               matched_packages.append(e_pkg)
-                                                               existing_node = e_pkg
-                                               break
-                                       # Compare built package to current config and
-                                       # reject the built package if necessary.
-                                       if built and not installed and \
-                                               ("--newuse" in self.myopts or \
-                                               "--reinstall" in self.myopts):
-                                               iuses = pkg.iuse.all
-                                               old_use = pkg.use.enabled
-                                               if myeb:
-                                                       pkgsettings.setcpv(myeb)
-                                               else:
-                                                       pkgsettings.setcpv(pkg)
-                                               now_use = pkgsettings["PORTAGE_USE"].split()
-                                               forced_flags = set()
-                                               forced_flags.update(pkgsettings.useforce)
-                                               forced_flags.update(pkgsettings.usemask)
-                                               cur_iuse = iuses
-                                               if myeb and not usepkgonly:
-                                                       cur_iuse = myeb.iuse.all
-                                               if self._reinstall_for_flags(forced_flags,
-                                                       old_use, iuses,
-                                                       now_use, cur_iuse):
-                                                       break
-                                       # Compare current config to installed package
-                                       # and do not reinstall if possible.
-                                       if not installed and \
-                                               ("--newuse" in self.myopts or \
-                                               "--reinstall" in self.myopts) and \
-                                               cpv in vardb.match(atom):
-                                               pkgsettings.setcpv(pkg)
-                                               forced_flags = set()
-                                               forced_flags.update(pkgsettings.useforce)
-                                               forced_flags.update(pkgsettings.usemask)
-                                               old_use = vardb.aux_get(cpv, ["USE"])[0].split()
-                                               old_iuse = set(filter_iuse_defaults(
-                                                       vardb.aux_get(cpv, ["IUSE"])[0].split()))
-                                               cur_use = pkgsettings["PORTAGE_USE"].split()
-                                               cur_iuse = pkg.iuse.all
-                                               reinstall_for_flags = \
-                                                       self._reinstall_for_flags(
-                                                       forced_flags, old_use, old_iuse,
-                                                       cur_use, cur_iuse)
-                                               if reinstall_for_flags:
-                                                       reinstall = True
-                                       if not built:
-                                               myeb = pkg
-                                       matched_packages.append(pkg)
-                                       if reinstall_for_flags:
-                                               self._reinstall_nodes[pkg] = \
-                                                       reinstall_for_flags
-                                       break
-
-               if not matched_packages:
-                       return None, None
-
-               if "--debug" in self.myopts:
-                       for pkg in matched_packages:
-                               portage.writemsg("%s %s\n" % \
-                                       ((pkg.type_name + ":").rjust(10), pkg.cpv), noiselevel=-1)
-
-               # Filter out any old-style virtual matches if they are
-               # mixed with new-style virtual matches.
-               cp = portage.dep_getkey(atom)
-               if len(matched_packages) > 1 and \
-                       "virtual" == portage.catsplit(cp)[0]:
-                       for pkg in matched_packages:
-                               if pkg.cp != cp:
-                                       continue
-                               # Got a new-style virtual, so filter
-                               # out any old-style virtuals.
-                               matched_packages = [pkg for pkg in matched_packages \
-                                       if pkg.cp == cp]
-                               break
-
-               if len(matched_packages) > 1:
-                       bestmatch = portage.best(
-                               [pkg.cpv for pkg in matched_packages])
-                       matched_packages = [pkg for pkg in matched_packages \
-                               if portage_dep.cpvequal(pkg.cpv, bestmatch)]
-
-               # ordered by type preference ("ebuild" type is the last resort)
-               return  matched_packages[-1], existing_node
-
-       def _select_pkg_from_graph(self, root, atom, onlydeps=False):
-               """
-               Select packages that have already been added to the graph or
-               those that are installed and have not been scheduled for
-               replacement.
-               """
-               graph_db = self._graph_trees[root]["porttree"].dbapi
-               matches = graph_db.match(atom)
-               if not matches:
-                       return None, None
-               cpv = matches[-1] # highest match
-               slot_atom = "%s:%s" % (portage.cpv_getkey(cpv),
-                       graph_db.aux_get(cpv, ["SLOT"])[0])
-               e_pkg = self._slot_pkg_map[root].get(slot_atom)
-               if e_pkg:
-                       return e_pkg, e_pkg
-               # Since this cpv exists in the graph_db,
-               # we must have a cached Package instance.
-               cache_key = ("installed", root, cpv, "nomerge")
-               return (self._pkg_cache[cache_key], None)
-
-       def _complete_graph(self):
-               """
-               Add any deep dependencies of required sets (args, system, world) that
-               have not been pulled into the graph yet. This ensures that the graph
-               is consistent such that initially satisfied deep dependencies are not
-               broken in the new graph. Initially unsatisfied dependencies are
-               irrelevant since we only want to avoid breaking dependencies that are
-               intially satisfied.
-
-               Since this method can consume enough time to disturb users, it is
-               currently only enabled by the --complete-graph option, or when
-               dep calculation time exceeds self._complete_threshold.
-               """
-               if "--buildpkgonly" in self.myopts or \
-                       "recurse" not in self.myparams:
-                       return 1
-
-               if "complete" not in self.myparams:
-                       if time.time() - self._creation_time > self._complete_threshold:
-                               self.myparams.add("complete")
-                       else:
-                               # Skip this to avoid consuming enough time to disturb users.
-                               return 1
+                                                       # This is already handled inside
+                                                       # self.create() when necessary.
+                                                       pass
+                                       if not myarg:
+                                               continue
 
-               # Put the depgraph into a mode that causes it to only
-               # select packages that have already been added to the
-               # graph or those that are installed and have not been
-               # scheduled for replacement. Also, toggle the "deep"
-               # parameter so that all dependencies are traversed and
-               # accounted for.
-               self._select_atoms = self._select_atoms_from_graph
-               self._select_package = self._select_pkg_from_graph
-               already_deep = "deep" in self.myparams
-               if not already_deep:
-                       self.myparams.add("deep")
-
-               for root in self.roots:
-                       required_set_names = self._required_set_names.copy()
-                       if root == self.target_root and \
-                               (already_deep or "empty" in self.myparams):
-                               required_set_names.difference_update(self._sets)
-                       if not required_set_names and not self._ignored_deps:
-                               continue
-                       root_config = self.roots[root]
-                       setconfig = root_config.setconfig
-                       args = []
-                       # Reuse existing SetArg instances when available.
-                       for arg in self.digraph.root_nodes():
-                               if not isinstance(arg, SetArg):
-                                       continue
-                               if arg.root_config != root_config:
-                                       continue
-                               if arg.name in required_set_names:
-                                       args.append(arg)
-                                       required_set_names.remove(arg.name)
-                       # Create new SetArg instances only when necessary.
-                       for s in required_set_names:
-                               expanded_set = InternalPackageSet(
-                                       initial_atoms=setconfig.getSetAtoms(s))
-                               atom = SETPREFIX + s
-                               args.append(SetArg(arg=atom, set=expanded_set,
-                                       root_config=root_config))
-                       vardb = root_config.trees["vartree"].dbapi
-                       for arg in args:
-                               for atom in arg.set:
-                                       self._dep_stack.append(
-                                               Dependency(atom=atom, root=root, parent=arg))
-                       if self._ignored_deps:
-                               self._dep_stack.extend(self._ignored_deps)
-                               self._ignored_deps = []
-                       if not self._create_graph(allow_unsatisfied=True):
-                               return 0
-                       # Check the unsatisfied deps to see if any initially satisfied deps
-                       # will become unsatisfied due to an upgrade. Initially unsatisfied
-                       # deps are irrelevant since we only want to avoid breaking deps
-                       # that are initially satisfied.
-                       while self._unsatisfied_deps:
-                               dep = self._unsatisfied_deps.pop()
-                               matches = vardb.match_pkgs(dep.atom)
-                               if not matches:
-                                       # Initially unsatisfied.
-                                       continue
-                               # An scheduled installation broke a deep dependency.
-                               # Add the installed package to the graph so that it
-                               # will be appropriately reported as a slot collision
-                               # (possibly solvable via backtracking).
-                               pkg = matches[-1] # highest match
-                               if not self._add_pkg(pkg, dep.parent,
-                                       priority=dep.priority, depth=dep.depth):
+                       if myparent:
+                               #we are a dependency, so we want to be unconditionally added
+                               mypriority = priority.copy()
+                               if vardb.match(x):
+                                       mypriority.satisfied = True
+                               if not self.create(selected_pkg[0], myparent=myparent,
+                                       metadata=selected_pkg[1], priority=mypriority,
+                                       rev_dep=rev_deps, arg=arg):
                                        return 0
-                               if not self._create_graph(allow_unsatisfied=True):
+                       else:
+                               #if mysource is not set, then we are a command-line dependency and should not be added
+                               #if --onlydeps is specified.
+                               if not self.create(selected_pkg[0], myparent=myparent,
+                                       addme=("--onlydeps" not in self.myopts),
+                                       metadata=selected_pkg[1], rev_dep=rev_deps, arg=arg):
                                        return 0
-               return 1
 
-       def _pkg(self, cpv, type_name, root_config, installed=False):
-               """
-               Get a package instance from the cache, or create a new
-               one if necessary. Raises KeyError from aux_get if it
-               failures for some reason (package does not exist or is
-               corrupt).
-               """
-               operation = "merge"
-               if installed:
-                       operation = "nomerge"
-               pkg = self._pkg_cache.get(
-                       (type_name, root_config.root, cpv, operation))
-               if pkg is None:
-                       db = root_config.trees[
-                               self.pkg_tree_map[type_name]].dbapi
-                       metadata = izip(Package.metadata_keys,
-                               db.aux_get(cpv, Package.metadata_keys))
-                       pkg = Package(cpv=cpv, metadata=metadata,
-                               root_config=root_config, installed=installed)
-                       if type_name == "ebuild":
-                               settings = self.pkgsettings[root_config.root]
-                               settings.setcpv(pkg)
-                               pkg.metadata["USE"] = settings["PORTAGE_USE"]
-                       self._pkg_cache[pkg] = pkg
-               return pkg
+               if "--debug" in self.myopts:
+                       print "Exiting...",myparent
+               return 1
 
        def validate_blockers(self):
                """Remove any blockers from the digraph that do not match any of the
@@ -3580,6 +2453,17 @@ class depgraph(object):
                        "--nodeps" in self.myopts:
                        return True
 
+               modified_slots = {}
+               for myroot in self.trees:
+                       myslots = {}
+                       modified_slots[myroot] = myslots
+                       final_db = self.mydbapi[myroot]
+                       slot_node_map = self._slot_node_map[myroot]
+                       for slot_atom, mynode in slot_node_map.iteritems():
+                               mytype, myroot, mycpv, mystatus = mynode
+                               if mystatus == "merge":
+                                       myslots[slot_atom] = mycpv
+
                #if "deep" in self.myparams:
                if True:
                        # Pull in blockers from all installed packages that haven't already
@@ -3587,122 +2471,43 @@ class depgraph(object):
                        # due to the performance penalty that is incurred by all the
                        # additional dep_check calls that are required.
 
+                       # Optimization hack for dep_check calls that minimizes the
+                       # available matches by replacing the portdb with a fakedbapi
+                       # instance.
+                       class FakePortageTree(object):
+                               def __init__(self, mydb):
+                                       self.dbapi = mydb
+                       dep_check_trees = {}
+                       for myroot in self.trees:
+                               dep_check_trees[myroot] = self.trees[myroot].copy()
+                               dep_check_trees[myroot]["porttree"] = \
+                                       FakePortageTree(self.mydbapi[myroot])
+
                        dep_keys = ["DEPEND","RDEPEND","PDEPEND"]
                        for myroot in self.trees:
+                               pkg_node_map = self.pkg_node_map[myroot]
                                vardb = self.trees[myroot]["vartree"].dbapi
                                portdb = self.trees[myroot]["porttree"].dbapi
                                pkgsettings = self.pkgsettings[myroot]
                                final_db = self.mydbapi[myroot]
-
-                               graph_complete_for_root = "complete" in self.myparams or \
-                                       (myroot == self.target_root and \
-                                       ("deep" in self.myparams or "empty" in self.myparams) and \
-                                       not self._required_set_names.difference(self._sets))
-
+                               cpv_all_installed = self.trees[myroot]["vartree"].dbapi.cpv_all()
                                blocker_cache = BlockerCache(myroot, vardb)
-                               stale_cache = set(blocker_cache)
-                               for pkg in vardb:
-                                       cpv = pkg.cpv
-                                       stale_cache.discard(cpv)
-                                       pkg_in_graph = self.digraph.contains(pkg)
-
-                                       # Check for masked installed packages. For keyword
-                                       # mask there are a couple of common cases that are
-                                       # likely to generate unwanted noise:
-                                       #
-                                       #  * Packages missing /var/db/pkg/*/*/KEYWORDS entries
-                                       #    due to having been installed by an old version of
-                                       #    portage.
-                                       #
-                                       #  * Packages installed by overriding ACCEPT_KEYWORDS
-                                       #    via the environment.
-                                       #
-                                       # To avoid unwanted noise, only warn about keyword
-                                       # masks if all of the following are true:
-                                       #
-                                       #  * KEYWORDS is not empty (not installed by old portage).
-                                       #
-                                       #  * The graph is complete and the package has not been
-                                       #    pulled into the dependency graph. It's eligible for
-                                       #    depclean, but depclean may fail to recognize it as
-                                       #    such due to differences in visibility filtering which
-                                       #    can lead to differences in || dep evaluation.
-                                       #    TODO: Share visibility code to fix this inconsistency.
-
-                                       if pkg in final_db:
-                                               if pkg_in_graph and not visible(pkgsettings, pkg):
-                                                       self._masked_installed.add(pkg)
-                                               elif graph_complete_for_root and \
-                                                       pkgsettings._getMissingKeywords(
-                                                       pkg.cpv, pkg.metadata) and \
-                                                       pkg.metadata["KEYWORDS"].split() and \
-                                                       not pkg_in_graph:
-                                                       try:
-                                                               ebuild = self._pkg(pkg.cpv,
-                                                                       "ebuild", pkg.root_config)
-                                                       except KeyError:
-                                                               ebuild = None
-                                                       else:
-                                                               try:
-                                                                       if not visible(pkgsettings, ebuild):
-                                                                               ebuild = None
-                                                               except portage_exception.InvalidDependString:
-                                                                       ebuild = None
-                                                       if ebuild is None:
-                                                               self._masked_installed.add(pkg)
-
+                               for pkg in cpv_all_installed:
                                        blocker_atoms = None
-                                       blockers = None
-                                       if pkg_in_graph:
-                                               blockers = []
-                                               try:
-                                                       blockers.extend(
-                                                               self._blocker_parents.child_nodes(pkg))
-                                               except KeyError:
-                                                       pass
-                                               try:
-                                                       blockers.extend(
-                                                               self._irrelevant_blockers.child_nodes(pkg))
-                                               except KeyError:
-                                                       pass
-                                       if blockers is not None:
-                                               blockers = set("!" + blocker.atom \
-                                                       for blocker in blockers)
-
+                                       matching_node = pkg_node_map.get(pkg, None)
+                                       if matching_node and \
+                                               matching_node[3] == "nomerge":
+                                               continue
                                        # If this node has any blockers, create a "nomerge"
                                        # node for it so that they can be enforced.
                                        self.spinner.update()
-                                       blocker_data = blocker_cache.get(cpv)
-                                       if blocker_data is not None and \
-                                               blocker_data.counter != long(pkg.metadata["COUNTER"]):
-                                               blocker_data = None
-
-                                       # If blocker data from the graph is available, use
-                                       # it to validate the cache and update the cache if
-                                       # it seems invalid.
-                                       if blocker_data is not None and \
-                                               blockers is not None:
-                                               if not blockers.symmetric_difference(
-                                                       blocker_data.atoms):
-                                                       continue
-                                               blocker_data = None
-
-                                       if blocker_data is None and \
-                                               blockers is not None:
-                                               # Re-use the blockers from the graph.
-                                               blocker_atoms = sorted(blockers)
-                                               counter = long(pkg.metadata["COUNTER"])
-                                               blocker_data = \
-                                                       blocker_cache.BlockerData(counter, blocker_atoms)
-                                               blocker_cache[pkg.cpv] = blocker_data
-                                               continue
-
+                                       blocker_data = blocker_cache.get(pkg)
                                        if blocker_data:
                                                blocker_atoms = blocker_data.atoms
                                        else:
-                                               # Use aux_get() to trigger FakeVartree global
-                                               # updates on *DEPEND when appropriate.
-                                               depstr = " ".join(vardb.aux_get(pkg.cpv, dep_keys))
+                                               dep_vals = vardb.aux_get(pkg, dep_keys)
+                                               myuse = vardb.aux_get(pkg, ["USE"])[0].split()
+                                               depstr = " ".join(dep_vals)
                                                # It is crucial to pass in final_db here in order to
                                                # optimize dep_check calls by eliminating atoms via
                                                # dep_wordreduce and dep_eval calls.
@@ -3710,8 +2515,8 @@ class depgraph(object):
                                                        portage_dep._dep_check_strict = False
                                                        try:
                                                                success, atoms = portage.dep_check(depstr,
-                                                                       final_db, pkgsettings, myuse=pkg.use.enabled,
-                                                                       trees=self._graph_trees, myroot=myroot)
+                                                                       final_db, pkgsettings, myuse=myuse,
+                                                                       trees=dep_check_trees, myroot=myroot)
                                                        except Exception, e:
                                                                if isinstance(e, SystemExit):
                                                                        raise
@@ -3720,169 +2525,161 @@ class depgraph(object):
                                                                # matches (this can happen if an atom lacks a
                                                                # category).
                                                                show_invalid_depstring_notice(
-                                                                       pkg, depstr, str(e))
+                                                                       ("installed", myroot, pkg, "nomerge"),
+                                                                       depstr, str(e))
                                                                del e
                                                                raise
                                                finally:
                                                        portage_dep._dep_check_strict = True
                                                if not success:
-                                                       replacement_pkg = final_db.match_pkgs(pkg.slot_atom)
-                                                       if replacement_pkg and \
-                                                               replacement_pkg[0].operation == "merge":
+                                                       slot_atom = "%s:%s" % (portage.dep_getkey(pkg),
+                                                               vardb.aux_get(pkg, ["SLOT"])[0])
+                                                       if slot_atom in modified_slots[myroot]:
                                                                # This package is being replaced anyway, so
                                                                # ignore invalid dependencies so as not to
                                                                # annoy the user too much (otherwise they'd be
                                                                # forced to manually unmerge it first).
                                                                continue
-                                                       show_invalid_depstring_notice(pkg, depstr, atoms)
+                                                       show_invalid_depstring_notice(
+                                                               ("installed", myroot, pkg, "nomerge"),
+                                                               depstr, atoms)
                                                        return False
                                                blocker_atoms = [myatom for myatom in atoms \
                                                        if myatom.startswith("!")]
-                                               blocker_atoms.sort()
-                                               counter = long(pkg.metadata["COUNTER"])
-                                               blocker_cache[cpv] = \
+                                               counter = long(vardb.aux_get(pkg, ["COUNTER"])[0])
+                                               blocker_cache[pkg] = \
                                                        blocker_cache.BlockerData(counter, blocker_atoms)
                                        if blocker_atoms:
+                                               # Don't store this parent in pkg_node_map, because it's
+                                               # not needed there and it might overwrite a "merge"
+                                               # node with the same cpv.
+                                               myparent = ("installed", myroot, pkg, "nomerge")
                                                for myatom in blocker_atoms:
-                                                       blocker = Blocker(atom=myatom[1:], root=myroot)
-                                                       self._blocker_parents.add(blocker, pkg)
-                               for cpv in stale_cache:
-                                       del blocker_cache[cpv]
+                                                       blocker = ("blocks", myroot, myatom[1:])
+                                                       myparents = \
+                                                               self.blocker_parents.get(blocker, None)
+                                                       if not myparents:
+                                                               myparents = set()
+                                                               self.blocker_parents[blocker] = myparents
+                                                       myparents.add(myparent)
                                blocker_cache.flush()
                                del blocker_cache
 
-               # Discard any "uninstall" tasks scheduled by previous calls
-               # to this method, since those tasks may not make sense given
-               # the current graph state.
-               previous_uninstall_tasks = self._blocker_uninstalls.leaf_nodes()
-               if previous_uninstall_tasks:
-                       self._blocker_uninstalls = digraph()
-                       self.digraph.difference_update(previous_uninstall_tasks)
-
-               for blocker in self._blocker_parents.leaf_nodes():
-                       self.spinner.update()
-                       root_config = self.roots[blocker.root]
-                       virtuals = root_config.settings.getvirtuals()
+               for blocker in self.blocker_parents.keys():
                        mytype, myroot, mydep = blocker
                        initial_db = self.trees[myroot]["vartree"].dbapi
                        final_db = self.mydbapi[myroot]
-                       
-                       provider_virtual = False
-                       if blocker.cp in virtuals and \
-                               not self._have_new_virt(blocker.root, blocker.cp):
-                               provider_virtual = True
-
-                       if provider_virtual:
-                               atoms = []
-                               for provider_entry in virtuals[blocker.cp]:
-                                       provider_cp = \
-                                               portage.dep_getkey(provider_entry)
-                                       atoms.append(blocker.atom.replace(
-                                               blocker.cp, provider_cp))
-                       else:
-                               atoms = [blocker.atom]
-
-                       blocked_initial = []
-                       for atom in atoms:
-                               blocked_initial.extend(initial_db.match_pkgs(atom))
-
-                       blocked_final = []
-                       for atom in atoms:
-                               blocked_final.extend(final_db.match_pkgs(atom))
-
+                       blocked_initial = initial_db.match(mydep)
+                       blocked_final = final_db.match(mydep)
                        if not blocked_initial and not blocked_final:
-                               parent_pkgs = self._blocker_parents.parent_nodes(blocker)
-                               self._blocker_parents.remove(blocker)
-                               # Discard any parents that don't have any more blockers.
-                               for pkg in parent_pkgs:
-                                       self._irrelevant_blockers.add(blocker, pkg)
-                                       if not self._blocker_parents.child_nodes(pkg):
-                                               self._blocker_parents.remove(pkg)
+                               del self.blocker_parents[blocker]
                                continue
-                       for parent in self._blocker_parents.parent_nodes(blocker):
+                       blocked_slots_initial = {}
+                       blocked_slots_final = {}
+                       for cpv in blocked_initial:
+                               blocked_slots_initial[cpv] = \
+                                       "%s:%s" % (portage.dep_getkey(cpv),
+                                               initial_db.aux_get(cpv, ["SLOT"])[0])
+                       for cpv in blocked_final:
+                               blocked_slots_final[cpv] = \
+                                       "%s:%s" % (portage.dep_getkey(cpv),
+                                               final_db.aux_get(cpv, ["SLOT"])[0])
+                       for parent in list(self.blocker_parents[blocker]):
+                               ptype, proot, pcpv, pstatus = parent
+                               pdbapi = self.trees[proot][self.pkg_tree_map[ptype]].dbapi
+                               pslot = pdbapi.aux_get(pcpv, ["SLOT"])[0]
+                               pslot_atom = "%s:%s" % (portage.dep_getkey(pcpv), pslot)
+                               parent_static = pslot_atom not in modified_slots[proot]
                                unresolved_blocks = False
                                depends_on_order = set()
-                               for pkg in blocked_initial:
-                                       if pkg.slot_atom == parent.slot_atom:
-                                               # TODO: Support blocks within slots in cases where it
-                                               # might make sense.  For example, a new version might
-                                               # require that the old version be uninstalled at build
-                                               # time.
+                               for cpv in blocked_initial:
+                                       slot_atom = blocked_slots_initial[cpv]
+                                       if slot_atom == pslot_atom:
+                                               # The parent blocks an initial package in the same
+                                               # slot as itself.  The merge/nomerge status of neither
+                                               # node matters.  In any case, this particular block is
+                                               # automatically resolved.
                                                continue
-                                       if parent.installed:
-                                               # Two currently installed packages conflict with
-                                               # eachother. Ignore this case since the damage
-                                               # is already done and this would be likely to
-                                               # confuse users if displayed like a normal blocker.
-                                               continue
-                                       if parent.operation == "merge":
-                                               # Maybe the blocked package can be replaced or simply
-                                               # unmerged to resolve this block.
-                                               depends_on_order.add((pkg, parent))
+                                       if parent_static and \
+                                               slot_atom not in modified_slots[myroot]:
+                                               # This blocker will be handled the next time that a
+                                               # merge of either package is triggered.
                                                continue
+                                       if pstatus == "merge" and \
+                                               slot_atom in modified_slots[myroot]:
+                                               replacement = final_db.match(slot_atom)
+                                               if replacement:
+                                                       slot = portage_dep.dep_getslot(slot_atom)
+                                                       if not portage.match_from_list(
+                                                               mydep, ["%s:%s" % (replacement[0], slot)]):
+                                                               # Apparently a replacement may be able to
+                                                               # invalidate this block.
+                                                               replacement_node = \
+                                                                       self.pkg_node_map[proot][replacement[0]]
+                                                               depends_on_order.add((replacement_node, parent))
+                                                               continue
                                        # None of the above blocker resolutions techniques apply,
                                        # so apparently this one is unresolvable.
                                        unresolved_blocks = True
-                               for pkg in blocked_final:
-                                       if pkg.slot_atom == parent.slot_atom:
-                                               # TODO: Support blocks within slots.
+                               for cpv in blocked_final:
+                                       slot_atom = blocked_slots_final[cpv]
+                                       if slot_atom == pslot_atom:
+                                               # The parent blocks itself, so the merge order does not
+                                               # need to be enforced.
                                                continue
-                                       if parent.operation == "nomerge" and \
-                                               pkg.operation == "nomerge":
+                                       if parent_static and \
+                                               slot_atom not in modified_slots[myroot]:
                                                # This blocker will be handled the next time that a
                                                # merge of either package is triggered.
                                                continue
-
-                                       # Maybe the blocking package can be
-                                       # unmerged to resolve this block.
-                                       if parent.operation == "merge" and pkg.installed:
-                                               depends_on_order.add((pkg, parent))
-                                               continue
-                                       elif parent.operation == "nomerge":
-                                               depends_on_order.add((parent, pkg))
-                                               continue
+                                       if not parent_static and pstatus == "nomerge" and \
+                                               slot_atom in modified_slots[myroot]:
+                                               replacement = final_db.match(pslot_atom)
+                                               if replacement:
+                                                       replacement_node = \
+                                                               self.pkg_node_map[proot][replacement[0]]
+                                                       if replacement_node not in \
+                                                               self.blocker_parents[blocker]:
+                                                               # Apparently a replacement may be able to
+                                                               # invalidate this block.
+                                                               blocked_node = self.pkg_node_map[proot][cpv]
+                                                               depends_on_order.add(
+                                                                       (replacement_node, blocked_node))
+                                                               continue
                                        # None of the above blocker resolutions techniques apply,
                                        # so apparently this one is unresolvable.
                                        unresolved_blocks = True
-
-                               # Make sure we don't unmerge any package that have been pulled
-                               # into the graph.
                                if not unresolved_blocks and depends_on_order:
-                                       for inst_pkg, inst_task in depends_on_order:
-                                               if self.digraph.contains(inst_pkg) and \
-                                                       self.digraph.parent_nodes(inst_pkg):
-                                                       unresolved_blocks = True
-                                                       break
-
-                               if not unresolved_blocks and depends_on_order:
-                                       for inst_pkg, inst_task in depends_on_order:
-                                               uninst_task = Package(built=inst_pkg.built,
-                                                       cpv=inst_pkg.cpv, installed=inst_pkg.installed,
-                                                       metadata=inst_pkg.metadata,
-                                                       operation="uninstall",
-                                                       root_config=inst_pkg.root_config,
-                                                       type_name=inst_pkg.type_name)
-                                               self._pkg_cache[uninst_task] = uninst_task
+                                       for node, pnode in depends_on_order:
                                                # Enforce correct merge order with a hard dep.
-                                               self.digraph.addnode(uninst_task, inst_task,
-                                                       priority=BlockerDepPriority.instance)
+                                               self.digraph.addnode(node, pnode,
+                                                       priority=DepPriority(buildtime=True))
                                                # Count references to this blocker so that it can be
                                                # invalidated after nodes referencing it have been
                                                # merged.
-                                               self._blocker_uninstalls.addnode(uninst_task, blocker)
+                                               self.blocker_digraph.addnode(node, blocker)
                                if not unresolved_blocks and not depends_on_order:
-                                       self._irrelevant_blockers.add(blocker, parent)
-                                       self._blocker_parents.remove_edge(blocker, parent)
-                                       if not self._blocker_parents.parent_nodes(blocker):
-                                               self._blocker_parents.remove(blocker)
-                                       if not self._blocker_parents.child_nodes(parent):
-                                               self._blocker_parents.remove(parent)
+                                       self.blocker_parents[blocker].remove(parent)
                                if unresolved_blocks:
-                                       self._unsolvable_blockers.add(blocker, parent)
-
+                                       self._unresolved_blocker_parents.setdefault(
+                                               blocker, set()).add(parent)
+                       if not self.blocker_parents[blocker]:
+                               del self.blocker_parents[blocker]
+               # Validate blockers that depend on merge order.
+               if not self.blocker_digraph.empty():
+                       self.altlist()
+               if self._slot_collision_info:
+                       # The user is only notified of a slot collision if there are no
+                       # unresolvable blocks.
+                       for x in self.altlist():
+                               if x[0] == "blocks":
+                                       return True
+                       self._show_slot_collision_notice()
+                       if not self._accept_collisions():
+                               return False
                return True
 
-       def _accept_blocker_conflicts(self):
+       def _accept_collisions(self):
                acceptable = False
                for x in ("--buildpkgonly", "--fetchonly",
                        "--fetch-all-uri", "--nodeps", "--pretend"):
@@ -3896,73 +2693,20 @@ class depgraph(object):
                optimal leaf node selection."""
                node_info = {}
                for node in mygraph.order:
-                       node_info[node] = len(mygraph.parent_nodes(node))
-               def cmp_merge_preference(node1, node2):
-                       return node_info[node2] - node_info[node1]
-               mygraph.order.sort(cmp_merge_preference)
-
-       def altlist(self, reversed=False):
-
-               while self._serialized_tasks_cache is None:
-                       self._resolve_conflicts()
-                       try:
-                               self._serialized_tasks_cache = self._serialize_tasks()
-                       except self._serialize_tasks_retry:
-                               pass
-
-               retlist = self._serialized_tasks_cache[:]
-               if reversed:
-                       retlist.reverse()
-               return retlist
-
-       def break_refs(self, mergelist):
-               """
-               Take a mergelist like that returned from self.altlist() and
-               break any references that lead back to the depgraph. This is
-               useful if you want to hold references to packages without
-               also holding the depgraph on the heap.
-               """
-               for node in mergelist:
-                       if not isinstance(node, Package):
-                               continue
-
-                       # The visible packages cache has fullfilled it's purpose
-                       # and it's no longer needed, so free the memory.
-                       node.root_config.visible_pkgs.clear()
-
-                       if isinstance(node.root_config.trees["vartree"], FakeVartree):
-                               # The FakeVartree references the _package_cache which
-                               # references the depgraph. So that Package instances don't
-                               # hold the depgraph and FakeVartree on the heap, replace
-                               # the FakeVartree reference with the real vartree.
-                               node.root_config.trees["vartree"] = \
-                                       self._trees_orig[node.root]["vartree"]
-
-       def _resolve_conflicts(self):
-               if not self._complete_graph():
-                       raise self._unknown_internal_error()
-
-               if not self.validate_blockers():
-                       raise self._unknown_internal_error()
+                       node_info[node] = len(mygraph.parent_nodes(node))
+               def cmp_merge_preference(node1, node2):
+                       return node_info[node2] - node_info[node1]
+               mygraph.order.sort(cmp_merge_preference)
 
-       def _serialize_tasks(self):
+       def altlist(self, reversed=False):
+               if reversed in self._altlist_cache:
+                       return self._altlist_cache[reversed][:]
+               if reversed:
+                       retlist = self.altlist()
+                       retlist.reverse()
+                       self._altlist_cache[reversed] = retlist[:]
+                       return retlist
                mygraph=self.digraph.copy()
-               # Prune "nomerge" root nodes if nothing depends on them, since
-               # otherwise they slow down merge order calculation. Don't remove
-               # non-root nodes since they help optimize merge order in some cases
-               # such as revdep-rebuild.
-               removed_nodes = set()
-               while True:
-                       for node in mygraph.root_nodes():
-                               if not isinstance(node, Package) or \
-                                       node.installed or node.onlydeps:
-                                       removed_nodes.add(node)
-                       if removed_nodes:
-                               self.spinner.update()
-                               mygraph.difference_update(removed_nodes)
-                       if not removed_nodes:
-                               break
-                       removed_nodes.clear()
                self._merge_order_bias(mygraph)
                def cmp_circular_bias(n1, n2):
                        """
@@ -3979,73 +2723,21 @@ class depgraph(object):
                        elif n1_n2_medium:
                                return 1
                        return -1
-               myblocker_uninstalls = self._blocker_uninstalls.copy()
+               myblockers = self.blocker_digraph.copy()
                retlist=[]
-               # Contains uninstall tasks that have been scheduled to
-               # occur after overlapping blockers have been installed.
-               scheduled_uninstalls = set()
-               # Contains any Uninstall tasks that have been ignored
-               # in order to avoid the circular deps code path. These
-               # correspond to blocker conflicts that could not be
-               # resolved.
-               ignored_uninstall_tasks = set()
-               have_uninstall_task = False
-               complete = "complete" in self.myparams
-               myblocker_parents = self._blocker_parents.copy()
+               circular_blocks = False
+               blocker_deps = None
                asap_nodes = []
-
-               def get_nodes(**kwargs):
-                       """
-                       Returns leaf nodes excluding Uninstall instances
-                       since those should be executed as late as possible.
-                       """
-                       return [node for node in mygraph.leaf_nodes(**kwargs) \
-                               if isinstance(node, Package) and \
-                                       (node.operation != "uninstall" or \
-                                       node in scheduled_uninstalls)]
-
-               # sys-apps/portage needs special treatment if ROOT="/"
-               running_root = "/"
-               from portage_const import PORTAGE_PACKAGE_ATOM
-               runtime_deps = InternalPackageSet(
-                       initial_atoms=[PORTAGE_PACKAGE_ATOM])
-               running_portage = self.trees[running_root]["vartree"].dbapi.match_pkgs(
-                       PORTAGE_PACKAGE_ATOM)
-               replacement_portage = self.mydbapi[running_root].match_pkgs(
-                       PORTAGE_PACKAGE_ATOM)
-
-               if running_portage:
-                       running_portage = running_portage[0]
-               else:
-                       running_portage = None
-
-               if replacement_portage:
-                       replacement_portage = replacement_portage[0]
+               portage_node = None
+               if reversed:
+                       get_nodes = mygraph.root_nodes
                else:
-                       replacement_portage = None
-
-               if replacement_portage == running_portage:
-                       replacement_portage = None
-
-               if replacement_portage is not None:
-                       # update from running_portage to replacement_portage asap
-                       asap_nodes.append(replacement_portage)
-
-               if running_portage is not None:
-                       try:
-                               portage_rdepend = self._select_atoms_highest_available(
-                                       running_root, running_portage.metadata["RDEPEND"],
-                                       myuse=running_portage.use.enabled,
-                                       parent=running_portage, strict=False)
-                       except portage_exception.InvalidDependString, e:
-                               portage.writemsg("!!! Invalid RDEPEND in " + \
-                                       "'%svar/db/pkg/%s/RDEPEND': %s\n" % \
-                                       (running_root, running_portage.cpv, e), noiselevel=-1)
-                               del e
-                               portage_rdepend = []
-                       runtime_deps.update(atom for atom in portage_rdepend \
-                               if not atom.startswith("!"))
-
+                       get_nodes = mygraph.leaf_nodes
+                       for cpv, node in self.pkg_node_map["/"].iteritems():
+                               if "portage" == portage.catsplit(portage.dep_getkey(cpv))[-1]:
+                                       portage_node = node
+                                       asap_nodes.append(node)
+                                       break
                ignore_priority_soft_range = [None]
                ignore_priority_soft_range.extend(
                        xrange(DepPriority.MIN, DepPriority.MEDIUM_SOFT + 1))
@@ -4076,7 +2768,6 @@ class depgraph(object):
                # unresolved blockers or circular dependencies.
 
                while not mygraph.empty():
-                       self.spinner.update()
                        selected_nodes = None
                        ignore_priority = None
                        if prefer_asap and asap_nodes:
@@ -4099,18 +2790,8 @@ class depgraph(object):
                                        if ignore_priority is None and not tree_mode:
                                                # Greedily pop all of these nodes since no relationship
                                                # has been ignored.  This optimization destroys --tree
-                                               # output, so it's disabled in reversed mode. If there
-                                               # is a mix of merge and uninstall nodes, save the
-                                               # uninstall nodes from later since sometimes a merge
-                                               # node will render an install node unnecessary, and
-                                               # we want to avoid doing a separate uninstall task in
-                                               # that case.
-                                               merge_nodes = [node for node in nodes \
-                                                       if node.operation == "merge"]
-                                               if merge_nodes:
-                                                       selected_nodes = merge_nodes
-                                               else:
-                                                       selected_nodes = nodes
+                                               # output, so it's disabled in reversed mode.
+                                               selected_nodes = nodes
                                        else:
                                                # For optimal merge order:
                                                #  * Only pop one node.
@@ -4138,8 +2819,7 @@ class depgraph(object):
                                                        return True
                                                if node not in mergeable_nodes:
                                                        return False
-                                               if node == replacement_portage and \
-                                                       mygraph.child_nodes(node,
+                                               if node == portage_node and mygraph.child_nodes(node,
                                                        ignore_priority=DepPriority.MEDIUM_SOFT):
                                                        # Make sure that portage always has all of it's
                                                        # RDEPENDs installed first.
@@ -4213,173 +2893,64 @@ class depgraph(object):
                                        selected_nodes = list(selected_nodes)
                                selected_nodes.sort(cmp_circular_bias)
 
-                       if not selected_nodes and not myblocker_uninstalls.is_empty():
-                               # An Uninstall task needs to be executed in order to
-                               # avoid conflict if possible.
-                               min_parent_deps = None
-                               uninst_task = None
-                               for task in myblocker_uninstalls.leaf_nodes():
-                                       # Do some sanity checks so that system or world packages
-                                       # don't get uninstalled inappropriately here (only really
-                                       # necessary when --complete-graph has not been enabled).
-
-                                       if task in ignored_uninstall_tasks:
-                                               continue
-
-                                       if task in scheduled_uninstalls:
-                                               # It's been scheduled but it hasn't
-                                               # been executed yet due to dependence
-                                               # on installation of blocking packages.
-                                               continue
-
-                                       root_config = self.roots[task.root]
-                                       inst_pkg = self._pkg_cache[
-                                               ("installed", task.root, task.cpv, "nomerge")]
-
-                                       if self.digraph.contains(inst_pkg):
-                                               continue
-
-                                       if running_root == task.root:
-                                               # Never uninstall sys-apps/portage or it's essential
-                                               # dependencies, except through replacement.
-                                               try:
-                                                       runtime_dep_atoms = \
-                                                               list(runtime_deps.iterAtomsForPackage(task))
-                                               except portage_exception.InvalidDependString, e:
-                                                       portage.writemsg("!!! Invalid PROVIDE in " + \
-                                                               "'%svar/db/pkg/%s/PROVIDE': %s\n" % \
-                                                               (task.root, task.cpv, e), noiselevel=-1)
-                                                       del e
-                                                       continue
-
-                                               # Don't uninstall a runtime dep if it appears
-                                               # to be the only suitable one installed.
-                                               skip = False
-                                               vardb = root_config.trees["vartree"].dbapi
-                                               for atom in runtime_dep_atoms:
-                                                       other_version = None
-                                                       for pkg in vardb.match_pkgs(atom):
-                                                               if pkg.cpv == task.cpv and \
-                                                                       pkg.metadata["COUNTER"] == \
-                                                                       task.metadata["COUNTER"]:
-                                                                       continue
-                                                               other_version = pkg
-                                                               break
-                                                       if other_version is None:
-                                                               skip = True
-                                                               break
-                                               if skip:
-                                                       continue
-
-                                               # For packages in the system set, don't take
-                                               # any chances. If the conflict can't be resolved
-                                               # by a normal replacement operation then abort.
-                                               skip = False
-                                               try:
-                                                       for atom in root_config.sets[
-                                                               "system"].iterAtomsForPackage(task):
-                                                               skip = True
-                                                               break
-                                               except portage_exception.InvalidDependString, e:
-                                                       portage.writemsg("!!! Invalid PROVIDE in " + \
-                                                               "'%svar/db/pkg/%s/PROVIDE': %s\n" % \
-                                                               (task.root, task.cpv, e), noiselevel=-1)
-                                                       del e
-                                                       skip = True
-                                               if skip:
-                                                       continue
-
-                                       # Note that the world check isn't always
-                                       # necessary since self._complete_graph() will
-                                       # add all packages from the system and world sets to the
-                                       # graph. This just allows unresolved conflicts to be
-                                       # detected as early as possible, which makes it possible
-                                       # to avoid calling self._complete_graph() when it is
-                                       # unnecessary due to blockers triggering an abortion.
-                                       if not complete:
-                                               # For packages in the world set, go ahead an uninstall
-                                               # when necessary, as long as the atom will be satisfied
-                                               # in the final state.
-                                               graph_db = self.mydbapi[task.root]
-                                               skip = False
-                                               try:
-                                                       for atom in root_config.sets[
-                                                               "world"].iterAtomsForPackage(task):
-                                                               satisfied = False
-                                                               for pkg in graph_db.match_pkgs(atom):
-                                                                       if pkg == inst_pkg:
-                                                                               continue
-                                                                       satisfied = True
-                                                                       break
-                                                               if not satisfied:
-                                                                       skip = True
-                                                                       break
-                                               except portage_exception.InvalidDependString, e:
-                                                       portage.writemsg("!!! Invalid PROVIDE in " + \
-                                                               "'%svar/db/pkg/%s/PROVIDE': %s\n" % \
-                                                               (task.root, task.cpv, e), noiselevel=-1)
-                                                       del e
-                                                       skip = True
-                                               if skip:
-                                                       continue
-
-                                       # Check the deps of parent nodes to ensure that
-                                       # the chosen task produces a leaf node. Maybe
-                                       # this can be optimized some more to make the
-                                       # best possible choice, but the current algorithm
-                                       # is simple and should be near optimal for most
-                                       # common cases.
-                                       parent_deps = set()
-                                       for parent in mygraph.parent_nodes(task):
-                                               parent_deps.update(mygraph.child_nodes(parent,
-                                                       ignore_priority=DepPriority.MEDIUM_SOFT))
-                                       parent_deps.remove(task)
-                                       if min_parent_deps is None or \
-                                               len(parent_deps) < min_parent_deps:
-                                               min_parent_deps = len(parent_deps)
-                                               uninst_task = task
-
-                               if uninst_task is not None:
-                                       # The uninstall is performed only after blocking
-                                       # packages have been merged on top of it. File
-                                       # collisions between blocking packages are detected
-                                       # and removed from the list of files to be uninstalled.
-                                       scheduled_uninstalls.add(uninst_task)
-                                       parent_nodes = mygraph.parent_nodes(uninst_task)
-
-                                       # Reverse the parent -> uninstall edges since we want
-                                       # to do the uninstall after blocking packages have
-                                       # been merged on top of it.
-                                       mygraph.remove(uninst_task)
-                                       for blocked_pkg in parent_nodes:
-                                               mygraph.add(blocked_pkg, uninst_task,
-                                                       priority=BlockerDepPriority.instance)
-                               else:
-                                       # None of the Uninstall tasks are acceptable, so
-                                       # the corresponding blockers are unresolvable.
-                                       # We need to drop an Uninstall task here in order
-                                       # to avoid the circular deps code path, but the
-                                       # blocker will still be counted as an unresolved
-                                       # conflict.
-                                       for node in myblocker_uninstalls.leaf_nodes():
-                                               try:
-                                                       mygraph.remove(node)
-                                               except KeyError:
-                                                       pass
-                                               else:
-                                                       ignored_uninstall_tasks.add(node)
+                       if not selected_nodes:
+                               if not myblockers.is_empty():
+                                       """A blocker couldn't be circumnavigated while keeping all
+                                       dependencies satisfied.  The user will have to resolve this
+                                       manually.  This is a panic condition and thus the order
+                                       doesn't really matter, so just pop a random node in order
+                                       to avoid a circular dependency panic if possible."""
+                                       if not circular_blocks:
+                                               circular_blocks = True
+                                               blocker_deps = myblockers.leaf_nodes()
+                                       while blocker_deps:
+                                               # Some of these nodes might have already been selected
+                                               # by the normal node selection process after the
+                                               # circular_blocks flag has been set.  Therefore, we
+                                               # have to verify that they're still in the graph so
+                                               # that they're not selected more than once.
+                                               node = blocker_deps.pop()
+                                               if mygraph.contains(node):
+                                                       selected_nodes = [node]
                                                        break
 
-                               # After dropping an Uninstall task, reset
-                               # the state variables for leaf node selection and
-                               # continue trying to select leaf nodes.
-                               prefer_asap = True
-                               accept_root_node = False
-                               continue
-
                        if not selected_nodes:
-                               self._circular_deps_for_display = mygraph
-                               raise self._unknown_internal_error()
+                               # No leaf nodes are available, so we have a circular
+                               # dependency panic situation.  Reduce the noise level to a
+                               # minimum via repeated elimination of root nodes since they
+                               # have no parents and thus can not be part of a cycle.
+                               while True:
+                                       root_nodes = mygraph.root_nodes(
+                                               ignore_priority=DepPriority.SOFT)
+                                       if not root_nodes:
+                                               break
+                                       for node in root_nodes:
+                                               mygraph.remove(node)
+                               # Display the USE flags that are enabled on nodes that are part
+                               # of dependency cycles in case that helps the user decide to
+                               # disable some of them.
+                               display_order = []
+                               tempgraph = mygraph.copy()
+                               while not tempgraph.empty():
+                                       nodes = tempgraph.leaf_nodes()
+                                       if not nodes:
+                                               node = tempgraph.order[0]
+                                       else:
+                                               node = nodes[0]
+                                       display_order.append(list(node))
+                                       tempgraph.remove(node)
+                               display_order.reverse()
+                               self.myopts.pop("--quiet", None)
+                               self.myopts.pop("--verbose", None)
+                               self.myopts["--tree"] = True
+                               self.display(display_order)
+                               print "!!! Error: circular dependencies:"
+                               print
+                               mygraph.debug_print()
+                               print
+                               print "!!! Note that circular dependencies can often be avoided by temporarily"
+                               print "!!! disabling USE flags that trigger optional dependencies."
+                               sys.exit(1)
 
                        # At this point, we've succeeded in selecting one or more nodes, so
                        # it's now safe to reset the prefer_asap and accept_root_node flags
@@ -4387,170 +2958,117 @@ class depgraph(object):
                        prefer_asap = True
                        accept_root_node = False
 
-                       mygraph.difference_update(selected_nodes)
-
                        for node in selected_nodes:
-                               if isinstance(node, Package) and \
-                                       node.operation == "nomerge":
+                               if node[-1] != "nomerge":
+                                       retlist.append(list(node))
+                               mygraph.remove(node)
+                               if not reversed and not circular_blocks and myblockers.contains(node):
+                                       """This node may have invalidated one or more blockers."""
+                                       myblockers.remove(node)
+                                       for blocker in myblockers.root_nodes():
+                                               if not myblockers.child_nodes(blocker):
+                                                       myblockers.remove(blocker)
+                                                       unresolved = \
+                                                               self._unresolved_blocker_parents.get(blocker)
+                                                       if unresolved:
+                                                               self.blocker_parents[blocker] = unresolved
+                                                       else:
+                                                               del self.blocker_parents[blocker]
+
+               if not reversed:
+                       """Blocker validation does not work with reverse mode,
+                       so self.altlist() should first be called with reverse disabled
+                       so that blockers are properly validated."""
+                       self.blocker_digraph = myblockers
+
+               """ Add any unresolved blocks so that they can be displayed."""
+               for blocker in self.blocker_parents:
+                       retlist.append(list(blocker))
+               self._altlist_cache[reversed] = retlist[:]
+               return retlist
+
+       def xcreate(self,mode="system"):
+               myroot = self.target_root
+               pkgsettings = self.pkgsettings[myroot]
+               vardb = self.trees[self.target_root]["vartree"].dbapi
+               portdb = self.trees[self.target_root]["porttree"].dbapi
+               bindb = self.trees[self.target_root]["bintree"].dbapi
+               bindb_keys = list(bindb._aux_cache_keys)
+               world_problems = False
+
+               root_config = self.roots[self.target_root]
+               world_set = root_config.sets["world"]
+               system_set = root_config.sets["system"]
+               mylist = list(system_set)
+               self._sets["system"] = system_set
+               if mode == "world":
+                       self._sets["world"] = world_set
+                       for x in world_set:
+                               if not portage.isvalidatom(x):
+                                       world_problems = True
                                        continue
+                               elif not vardb.match(x):
+                                       world_problems = True
+                                       available = False
+                                       if "--usepkgonly" not in self.myopts and \
+                                               portdb.match(x):
+                                               available = True
+                                       elif "--usepkg" in self.myopts:
+                                               for cpv in bindb.match(x):
+                                                       metadata = dict(izip(bindb_keys,
+                                                               bindb.aux_get(cpv, bindb_keys)))
+                                                       if visible(pkgsettings, cpv, metadata, built=True):
+                                                               available = True
+                                                               break
+                                       if not available:
+                                               continue
+                               mylist.append(x)
 
-                               # Handle interactions between blockers
-                               # and uninstallation tasks.
-                               solved_blockers = set()
-                               uninst_task = None
-                               if isinstance(node, Package) and \
-                                       "uninstall" == node.operation:
-                                       have_uninstall_task = True
-                                       uninst_task = node
-                               else:
-                                       vardb = self.trees[node.root]["vartree"].dbapi
-                                       previous_cpv = vardb.match(node.slot_atom)
-                                       if previous_cpv:
-                                               # The package will be replaced by this one, so remove
-                                               # the corresponding Uninstall task if necessary.
-                                               previous_cpv = previous_cpv[0]
-                                               uninst_task = \
-                                                       ("installed", node.root, previous_cpv, "uninstall")
-                                               try:
-                                                       mygraph.remove(uninst_task)
-                                               except KeyError:
-                                                       pass
+               for myatom in mylist:
+                       self._set_atoms.add(myatom)
 
-                               if uninst_task is not None and \
-                                       uninst_task not in ignored_uninstall_tasks and \
-                                       myblocker_uninstalls.contains(uninst_task):
-                                       blocker_nodes = myblocker_uninstalls.parent_nodes(uninst_task)
-                                       myblocker_uninstalls.remove(uninst_task)
-                                       # Discard any blockers that this Uninstall solves.
-                                       for blocker in blocker_nodes:
-                                               if not myblocker_uninstalls.child_nodes(blocker):
-                                                       myblocker_uninstalls.remove(blocker)
-                                                       solved_blockers.add(blocker)
-
-                               retlist.append(node)
-
-                               if (isinstance(node, Package) and \
-                                       "uninstall" == node.operation) or \
-                                       (uninst_task is not None and \
-                                       uninst_task in scheduled_uninstalls):
-                                       # Include satisfied blockers in the merge list
-                                       # since the user might be interested and also
-                                       # it serves as an indicator that blocking packages
-                                       # will be temporarily installed simultaneously.
-                                       for blocker in solved_blockers:
-                                               retlist.append(Blocker(atom=blocker.atom,
-                                                       root=blocker.root, satisfied=True))
-
-               unsolvable_blockers = set(self._unsolvable_blockers.leaf_nodes())
-               for node in myblocker_uninstalls.root_nodes():
-                       unsolvable_blockers.add(node)
-
-               for blocker in unsolvable_blockers:
-                       retlist.append(blocker)
-
-               # If any Uninstall tasks need to be executed in order
-               # to avoid a conflict, complete the graph with any
-               # dependencies that may have been initially
-               # neglected (to ensure that unsafe Uninstall tasks
-               # are properly identified and blocked from execution).
-               if have_uninstall_task and \
-                       not complete and \
-                       not unsolvable_blockers:
-                       self.myparams.add("complete")
-                       raise self._serialize_tasks_retry("")
-
-               if unsolvable_blockers and \
-                       not self._accept_blocker_conflicts():
-                       self._unsatisfied_blockers_for_display = unsolvable_blockers
-                       self._serialized_tasks_cache = retlist[:]
-                       raise self._unknown_internal_error()
-
-               if self._slot_collision_info and \
-                       not self._accept_blocker_conflicts():
-                       self._serialized_tasks_cache = retlist[:]
-                       raise self._unknown_internal_error()
+               missing_atoms = self._missing_args
+               for mydep in mylist:
+                       try:
+                               if not self.select_dep(
+                                       self.target_root, mydep, raise_on_missing=True, arg=mydep):
+                                       print >> sys.stderr, "\n\n!!! Problem resolving dependencies for", mydep
+                                       return 0
+                       except portage_exception.PackageNotFound:
+                               missing_atoms.append(mydep)
 
-               return retlist
+               masked_packages = []
+               for pkg, pkgsettings in self._masked_installed:
+                       root_config = self.roots[pkg.root]
+                       mreasons = get_masking_status(pkg, pkgsettings, root_config)
+                       masked_packages.append((root_config, pkgsettings,
+                               pkg.cpv, pkg.metadata, mreasons))
+               if masked_packages:
+                       sys.stderr.write("\n" + colorize("BAD", "!!!") + \
+                               " The following installed packages are masked:\n")
+                       show_masked_packages(masked_packages)
 
-       def _show_circular_deps(self, mygraph):
-               # No leaf nodes are available, so we have a circular
-               # dependency panic situation.  Reduce the noise level to a
-               # minimum via repeated elimination of root nodes since they
-               # have no parents and thus can not be part of a cycle.
-               while True:
-                       root_nodes = mygraph.root_nodes(
-                               ignore_priority=DepPriority.MEDIUM_SOFT)
-                       if not root_nodes:
-                               break
-                       mygraph.difference_update(root_nodes)
-               # Display the USE flags that are enabled on nodes that are part
-               # of dependency cycles in case that helps the user decide to
-               # disable some of them.
-               display_order = []
-               tempgraph = mygraph.copy()
-               while not tempgraph.empty():
-                       nodes = tempgraph.leaf_nodes()
-                       if not nodes:
-                               node = tempgraph.order[0]
-                       else:
-                               node = nodes[0]
-                       display_order.append(node)
-                       tempgraph.remove(node)
-               display_order.reverse()
-               self.myopts.pop("--quiet", None)
-               self.myopts.pop("--verbose", None)
-               self.myopts["--tree"] = True
-               portage.writemsg("\n\n", noiselevel=-1)
-               self.display(display_order)
-               prefix = colorize("BAD", " * ")
-               portage.writemsg("\n", noiselevel=-1)
-               portage.writemsg(prefix + "Error: circular dependencies:\n",
-                       noiselevel=-1)
-               portage.writemsg("\n", noiselevel=-1)
-               mygraph.debug_print()
-               portage.writemsg("\n", noiselevel=-1)
-               portage.writemsg(prefix + "Note that circular dependencies " + \
-                       "can often be avoided by temporarily\n", noiselevel=-1)
-               portage.writemsg(prefix + "disabling USE flags that trigger " + \
-                       "optional dependencies.\n", noiselevel=-1)
-
-       def _show_merge_list(self):
-               if self._serialized_tasks_cache is not None and \
-                       not (self._displayed_list and \
-                       (self._displayed_list == self._serialized_tasks_cache or \
-                       self._displayed_list == \
-                               list(reversed(self._serialized_tasks_cache)))):
-                       display_list = self._serialized_tasks_cache[:]
-                       if "--tree" in self.myopts:
-                               display_list.reverse()
-                       self.display(display_list)
-
-       def _show_unsatisfied_blockers(self, blockers):
-               self._show_merge_list()
-               msg = "Error: The above package list contains " + \
-                       "packages which cannot be installed " + \
-                       "at the same time on the same system."
-               prefix = colorize("BAD", " * ")
-               from textwrap import wrap
-               portage.writemsg("\n", noiselevel=-1)
-               for line in wrap(msg, 70):
-                       portage.writemsg(prefix + line + "\n", noiselevel=-1)
-               if "--quiet" not in self.myopts:
-                       show_blocker_docs_link()
+               if not self.validate_blockers():
+                       return False
 
-       def display(self, mylist, favorites=[], verbosity=None):
+               if world_problems:
+                       print >> sys.stderr, "\n!!! Problems have been detected with your world file"
+                       print >> sys.stderr, "!!! Please run "+green("emaint --check world")+"\n"
+
+               if missing_atoms:
+                       print >> sys.stderr, "\n" + colorize("BAD", "!!!") + \
+                               " Ebuilds for the following packages are either all"
+                       print >> sys.stderr, colorize("BAD", "!!!") + " masked or don't exist:"
+                       print >> sys.stderr, " ".join(missing_atoms) + "\n"
 
-               # This is used to prevent display_problems() from
-               # redundantly displaying this exact same merge list
-               # again via _show_merge_list().
-               self._displayed_list = mylist
+               return 1
 
+       def display(self, mylist, favorites=[], verbosity=None):
                if verbosity is None:
                        verbosity = ("--quiet" in self.myopts and 1 or \
                                "--verbose" in self.myopts and 3 or 2)
-               favorites_set = InternalPackageSet(favorites)
-               oneshot = "--oneshot" in self.myopts or \
-                       "--onlydeps" in self.myopts
+               favorites_set = AtomSet()
+               favorites_set.update(favorites)
                changelogs=[]
                p=[]
                blockers = []
@@ -4632,69 +3150,15 @@ class depgraph(object):
 
                tree_nodes = []
                display_list = []
-               mygraph = self.digraph.copy()
-
-               # If there are any Uninstall instances, add the corresponding
-               # blockers to the digraph (useful for --tree display).
-
-               executed_uninstalls = set(node for node in mylist \
-                       if isinstance(node, Package) and node.operation == "unmerge")
-
-               for uninstall in self._blocker_uninstalls.leaf_nodes():
-                       uninstall_parents = \
-                               self._blocker_uninstalls.parent_nodes(uninstall)
-                       if not uninstall_parents:
-                               continue
-
-                       # Remove the corresponding "nomerge" node and substitute
-                       # the Uninstall node.
-                       inst_pkg = self._pkg_cache[
-                               ("installed", uninstall.root, uninstall.cpv, "nomerge")]
-                       try:
-                               mygraph.remove(inst_pkg)
-                       except KeyError:
-                               pass
-
-                       try:
-                               inst_pkg_blockers = self._blocker_parents.child_nodes(inst_pkg)
-                       except KeyError:
-                               inst_pkg_blockers = []
-
-                       # Break the Package -> Uninstall edges.
-                       mygraph.remove(uninstall)
-
-                       # Resolution of a package's blockers
-                       # depend on it's own uninstallation.
-                       for blocker in inst_pkg_blockers:
-                               mygraph.add(uninstall, blocker)
-
-                       # Expand Package -> Uninstall edges into
-                       # Package -> Blocker -> Uninstall edges.
-                       for blocker in uninstall_parents:
-                               mygraph.add(uninstall, blocker)
-                               for parent in self._blocker_parents.parent_nodes(blocker):
-                                       if parent != inst_pkg:
-                                               mygraph.add(blocker, parent)
-
-                       # If the uninstall task did not need to be executed because
-                       # of an upgrade, display Blocker -> Upgrade edges since the
-                       # corresponding Blocker -> Uninstall edges will not be shown.
-                       upgrade_node = \
-                               self._slot_pkg_map[uninstall.root].get(uninstall.slot_atom)
-                       if upgrade_node is not None and \
-                               uninstall not in executed_uninstalls:
-                               for blocker in uninstall_parents:
-                                       mygraph.add(upgrade_node, blocker)
-
-               unsatisfied_blockers = []
+               mygraph = self._parent_child_digraph
                i = 0
                depth = 0
                shown_edges = set()
                for x in mylist:
-                       if isinstance(x, Blocker) and not x.satisfied:
-                               unsatisfied_blockers.append(x)
+                       if "blocks" == x[0]:
+                               display_list.append((x, 0, True))
                                continue
-                       graph_key = x
+                       graph_key = tuple(x)
                        if "--tree" in self.myopts:
                                depth = len(tree_nodes)
                                while depth and graph_key not in \
@@ -4720,8 +3184,6 @@ class depgraph(object):
                                                        selected_parent = None
                                                        # First, try to avoid a direct cycle.
                                                        for node in parent_nodes:
-                                                               if not isinstance(node, (Blocker, Package)):
-                                                                       continue
                                                                if node not in traversed_nodes and \
                                                                        node not in child_nodes:
                                                                        edge = (current_node, node)
@@ -4732,8 +3194,6 @@ class depgraph(object):
                                                        if not selected_parent:
                                                                # A direct cycle is unavoidable.
                                                                for node in parent_nodes:
-                                                                       if not isinstance(node, (Blocker, Package)):
-                                                                               continue
                                                                        if node not in traversed_nodes:
                                                                                edge = (current_node, node)
                                                                                if edge in shown_edges:
@@ -4744,7 +3204,7 @@ class depgraph(object):
                                                                shown_edges.add((current_node, selected_parent))
                                                                traversed_nodes.add(selected_parent)
                                                                add_parents(selected_parent, False)
-                                               display_list.append((current_node,
+                                               display_list.append((list(current_node),
                                                        len(tree_nodes), ordered))
                                                tree_nodes.append(current_node)
                                        tree_nodes = []
@@ -4752,8 +3212,6 @@ class depgraph(object):
                        else:
                                display_list.append((x, depth, True))
                mylist = display_list
-               for x in unsatisfied_blockers:
-                       mylist.append((x, 0, True))
 
                last_merge_depth = 0
                for i in xrange(len(mylist)-1,-1,-1):
@@ -4765,6 +3223,8 @@ class depgraph(object):
                                # being filled in.
                                del mylist[i]
                                continue
+                       if "blocks" == graph_key[0]:
+                               continue
                        if ordered and graph_key[-1] != "nomerge":
                                last_merge_depth = depth
                                continue
@@ -4781,6 +3241,7 @@ class depgraph(object):
 
                for mylist_index in xrange(len(mylist)):
                        x, depth, ordered = mylist[mylist_index]
+                       pkg_node = tuple(x)
                        pkg_type = x[0]
                        myroot = x[1]
                        pkg_key = x[2]
@@ -4791,50 +3252,38 @@ class depgraph(object):
                        pkgsettings = self.pkgsettings[myroot]
 
                        fetch=" "
-                       indent = " " * depth
 
-                       if isinstance(x, Blocker):
-                               if x.satisfied:
-                                       blocker_style = "PKG_BLOCKER_SATISFIED"
-                                       addl = "%s  %s  " % (colorize(blocker_style, "b"), fetch)
-                               else:
-                                       blocker_style = "PKG_BLOCKER"
-                                       addl = "%s  %s  " % (colorize(blocker_style, "B"), fetch)
+                       if x[0]=="blocks":
+                               addl=""+red("B")+"  "+fetch+"  "
                                if ordered:
                                        counters.blocks += 1
-                                       if x.satisfied:
-                                               counters.blocks_satisfied += 1
                                resolved = portage.key_expand(
                                        pkg_key, mydb=vardb, settings=pkgsettings)
                                if "--columns" in self.myopts and "--quiet" in self.myopts:
-                                       addl += " " + colorize(blocker_style, resolved)
+                                       addl = addl + " " + red(resolved)
                                else:
-                                       addl = "[%s %s] %s%s" % \
-                                               (colorize(blocker_style, "blocks"),
-                                               addl, indent, colorize(blocker_style, resolved))
-                               block_parents = self._blocker_parents.parent_nodes(x)
+                                       addl = "[blocks " + addl + "] " + red(resolved)
+                               block_parents = self.blocker_parents[tuple(x)]
                                block_parents = set([pnode[2] for pnode in block_parents])
                                block_parents = ", ".join(block_parents)
                                if resolved!=x[2]:
-                                       addl += colorize(blocker_style,
-                                               " (\"%s\" is blocking %s)") % \
+                                       addl += bad(" (\"%s\" is blocking %s)") % \
                                                (pkg_key, block_parents)
                                else:
-                                       addl += colorize(blocker_style,
-                                               " (is blocking %s)") % block_parents
-                               if isinstance(x, Blocker) and x.satisfied:
-                                       p.append(addl)
-                               else:
-                                       blockers.append(addl)
+                                       addl += bad(" (is blocking %s)") % block_parents
+                               blockers.append(addl)
                        else:
                                pkg_status = x[3]
-                               pkg_merge = ordered and pkg_status == "merge"
-                               if not pkg_merge and pkg_status == "merge":
-                                       pkg_status = "nomerge"
-                               built = pkg_type != "ebuild"
-                               installed = pkg_type == "installed"
-                               pkg = x
-                               metadata = pkg.metadata
+                               pkg_merge = ordered and pkg_status != "nomerge"
+                               if pkg_node in self._slot_collision_nodes or \
+                                       (pkg_status == "nomerge" and pkg_type != "installed"):
+                                       # The metadata isn't cached due to a slot collision or
+                                       # --onlydeps.
+                                       mydbapi = self.trees[myroot][self.pkg_tree_map[pkg_type]].dbapi
+                               else:
+                                       mydbapi = self.mydbapi[myroot] # contains cached metadata
+                               metadata = dict(izip(self._mydbapi_keys,
+                                       mydbapi.aux_get(pkg_key, self._mydbapi_keys)))
                                ebuild_path = None
                                repo_name = metadata["repository"]
                                if pkg_type == "ebuild":
@@ -4843,16 +3292,20 @@ class depgraph(object):
                                                raise portage_exception.PackageNotFound(pkg_key)
                                        repo_path_real = os.path.dirname(os.path.dirname(
                                                os.path.dirname(ebuild_path)))
+                                       pkgsettings.setcpv(pkg_key, mydb=mydbapi)
+                                       metadata["USE"] = pkgsettings["USE"]
                                else:
                                        repo_path_real = portdb.getRepositoryPath(repo_name)
-                               pkg_use = list(pkg.use.enabled)
+                               pkg_use = metadata["USE"].split()
+
                                try:
                                        restrict = flatten(use_reduce(paren_reduce(
-                                               pkg.metadata["RESTRICT"]), uselist=pkg_use))
+                                               mydbapi.aux_get(pkg_key, ["RESTRICT"])[0]),
+                                               uselist=pkg_use))
                                except portage_exception.InvalidDependString, e:
-                                       if not pkg.installed:
-                                               show_invalid_depstring_notice(x,
-                                                       pkg.metadata["RESTRICT"], str(e))
+                                       if pkg_status != "nomerge":
+                                               restrict = mydbapi.aux_get(pkg_key, ["RESTRICT"])[0]
+                                               show_invalid_depstring_notice(x, restrict, str(e))
                                                del e
                                                return 1
                                        restrict = []
@@ -4868,21 +3321,21 @@ class depgraph(object):
 
                                #we need to use "--emptrytree" testing here rather than "empty" param testing because "empty"
                                #param is used for -u, where you still *do* want to see when something is being upgraded.
-                               myoldbest = []
-                               myinslotlist = None
+                               myoldbest=""
                                installed_versions = vardb.match(portage.cpv_getkey(pkg_key))
                                if vardb.cpv_exists(pkg_key):
                                        addl="  "+yellow("R")+fetch+"  "
-                                       if ordered:
-                                               if pkg_merge:
+                                       if x[3] != "nomerge":
+                                               if ordered:
                                                        counters.reinst += 1
-                                               elif pkg_status == "uninstall":
-                                                       counters.uninst += 1
                                # filter out old-style virtual matches
                                elif installed_versions and \
                                        portage.cpv_getkey(installed_versions[0]) == \
                                        portage.cpv_getkey(pkg_key):
-                                       myinslotlist = vardb.match(pkg.slot_atom)
+                                       mynewslot = mydbapi.aux_get(pkg_key, ["SLOT"])[0]
+                                       slot_atom = "%s:%s" % \
+                                               (portage.cpv_getkey(pkg_key), mynewslot)
+                                       myinslotlist = vardb.match(slot_atom)
                                        # If this is the first install of a new-style virtual, we
                                        # need to filter out old-style virtual matches.
                                        if myinslotlist and \
@@ -4890,57 +3343,62 @@ class depgraph(object):
                                                portage.cpv_getkey(pkg_key):
                                                myinslotlist = None
                                        if myinslotlist:
-                                               myoldbest = myinslotlist[:]
-                                               addl = "   " + fetch
-                                               if not portage_dep.cpvequal(pkg_key,
-                                                       portage.best([pkg_key] + myoldbest)):
+                                               myoldbest=portage.best(myinslotlist)
+                                               addl="   "+fetch
+                                               if portage.pkgcmp(portage.pkgsplit(x[2]), portage.pkgsplit(myoldbest)) < 0:
                                                        # Downgrade in slot
-                                                       addl += turquoise("U")+blue("D")
+                                                       addl+=turquoise("U")+blue("D")
                                                        if ordered:
                                                                counters.downgrades += 1
                                                else:
                                                        # Update in slot
-                                                       addl += turquoise("U") + " "
+                                                       addl+=turquoise("U")+" "
                                                        if ordered:
                                                                counters.upgrades += 1
                                        else:
                                                # New slot, mark it new.
-                                               addl = " " + green("NS") + fetch + "  "
-                                               myoldbest = vardb.match(portage.cpv_getkey(pkg_key))
+                                               addl=" "+green("NS")+fetch+"  "
                                                if ordered:
                                                        counters.newslot += 1
 
                                        if "--changelog" in self.myopts:
-                                               inst_matches = vardb.match(pkg.slot_atom)
+                                               slot_atom = "%s:%s" % (portage.dep_getkey(pkg_key),
+                                                       mydbapi.aux_get(pkg_key, ["SLOT"])[0])
+                                               inst_matches = vardb.match(slot_atom)
                                                if inst_matches:
                                                        changelogs.extend(self.calc_changelog(
                                                                portdb.findname(pkg_key),
                                                                inst_matches[0], pkg_key))
                                else:
-                                       addl = " " + green("N") + " " + fetch + "  "
+                                       addl=" "+green("N")+" "+fetch+"  "
                                        if ordered:
                                                counters.new += 1
 
-                               verboseadd = ""
+                               verboseadd=""
                                
                                if True:
                                        # USE flag display
+                                       cur_iuse = list(filter_iuse_defaults(
+                                               mydbapi.aux_get(pkg_key, ["IUSE"])[0].split()))
+
                                        forced_flags = set()
-                                       pkgsettings.setcpv(pkg) # for package.use.{mask,force}
+                                       pkgsettings.setcpv(pkg_key, mydb=mydbapi) # for package.use.{mask,force}
                                        forced_flags.update(pkgsettings.useforce)
                                        forced_flags.update(pkgsettings.usemask)
 
-                                       cur_use = [flag for flag in pkg.use.enabled \
-                                               if flag in pkg.iuse.all]
-                                       cur_iuse = sorted(pkg.iuse.all)
+                                       cur_iuse = portage.unique_array(cur_iuse)
+                                       cur_iuse.sort()
+                                       cur_use = pkg_use
+                                       cur_use = [flag for flag in cur_use if flag in cur_iuse]
 
-                                       if myoldbest and myinslotlist:
-                                               previous_cpv = myoldbest[0]
+                                       if myoldbest:
+                                               pkg = myoldbest
                                        else:
-                                               previous_cpv = pkg.cpv
-                                       if vardb.cpv_exists(previous_cpv):
-                                               old_iuse, old_use = vardb.aux_get(
-                                                               previous_cpv, ["IUSE", "USE"])
+                                               pkg = x[2]
+                                       if self.trees[x[1]]["vartree"].dbapi.cpv_exists(pkg):
+                                               old_iuse, old_use = \
+                                                       self.trees[x[1]]["vartree"].dbapi.aux_get(
+                                                               pkg, ["IUSE", "USE"])
                                                old_iuse = list(set(
                                                        filter_iuse_defaults(old_iuse.split())))
                                                old_iuse.sort()
@@ -4985,7 +3443,7 @@ class depgraph(object):
                                        # Prevent USE_EXPAND_HIDDEN flags from being hidden if they
                                        # are the only thing that triggered reinstallation.
                                        reinst_flags_map = {}
-                                       reinstall_for_flags = self._reinstall_nodes.get(pkg)
+                                       reinstall_for_flags = self._reinstall_nodes.get(pkg_node)
                                        reinst_expand_map = None
                                        if reinstall_for_flags:
                                                reinst_flags_map = map_to_use_expand(
@@ -5040,8 +3498,7 @@ class depgraph(object):
                                                                if myfetchfile not in myfetchlist:
                                                                        mysize+=myfilesdict[myfetchfile]
                                                                        myfetchlist.append(myfetchfile)
-                                                       if ordered:
-                                                               counters.totalsize += mysize
+                                                       counters.totalsize += mysize
                                                verboseadd+=format_size(mysize)+" "
 
                                        # overlay verbose
@@ -5058,7 +3515,7 @@ class depgraph(object):
 
                                        # now use the data to generate output
                                        repoadd = None
-                                       if pkg.installed or not has_previous:
+                                       if pkg_status == "nomerge" or not has_previous:
                                                repoadd = repo_display.repoStr(repo_path_real)
                                        else:
                                                repo_path_prev = None
@@ -5068,7 +3525,7 @@ class depgraph(object):
                                                # To avoid false positives during the transition
                                                # period, don't show ? if the installed package
                                                # is missing a repository label. Stages starting
-                                               # with 2008.0 will come with repository labels.
+                                               # with 2007.1 will come with repository lables.
                                                ignore_missing_labels = True
                                                if (ignore_missing_labels and not repo_path_prev) or \
                                                        repo_path_prev == repo_path_real:
@@ -5081,12 +3538,11 @@ class depgraph(object):
                                                show_repos = True
                                                verboseadd += teal("[%s]" % repoadd)
 
-                               xs = [portage.cpv_getkey(pkg_key)] + \
-                                       list(portage.catpkgsplit(pkg_key)[2:])
-                               if xs[2] == "r0":
-                                       xs[2] = ""
+                               xs=portage.pkgsplit(x[2])
+                               if xs[2]=="r0":
+                                       xs[2]=""
                                else:
-                                       xs[2] = "-" + xs[2]
+                                       xs[2]="-"+xs[2]
 
                                mywidth = 130
                                if "COLUMNWIDTH" in self.settings:
@@ -5098,20 +3554,16 @@ class depgraph(object):
                                                        "!!! Unable to parse COLUMNWIDTH='%s'\n" % \
                                                        self.settings["COLUMNWIDTH"], noiselevel=-1)
                                                del e
-                               oldlp = mywidth - 30
-                               newlp = oldlp - 30
+                               oldlp=mywidth-30
+                               newlp=oldlp-30
 
-                               # Convert myoldbest from a list to a string.
-                               if not myoldbest:
-                                       myoldbest = ""
-                               else:
-                                       for pos, key in enumerate(myoldbest):
-                                               key = portage.catpkgsplit(key)[2] + \
-                                                       "-" + portage.catpkgsplit(key)[3]
-                                               if key[-3:] == "-r0":
-                                                       key = key[:-3]
-                                               myoldbest[pos] = key
-                                       myoldbest = blue("["+", ".join(myoldbest)+"]")
+                               indent = " " * depth
+
+                               if myoldbest:
+                                       myoldbest=portage.pkgsplit(myoldbest)[1]+"-"+portage.pkgsplit(myoldbest)[2]
+                                       if myoldbest[-3:]=="-r0":
+                                               myoldbest=myoldbest[:-3]
+                                       myoldbest=blue("["+myoldbest+"]")
 
                                pkg_cp = xs[0]
                                root_config = self.roots[myroot]
@@ -5121,35 +3573,33 @@ class depgraph(object):
                                pkg_system = False
                                pkg_world = False
                                try:
-                                       pkg_system = system_set.findAtomForPackage(pkg)
-                                       pkg_world  = world_set.findAtomForPackage(pkg)
-                                       if not (oneshot or pkg_world) and \
-                                               myroot == self.target_root and \
-                                               favorites_set.findAtomForPackage(pkg):
+                                       pkg_system = system_set.findAtomForPackage(pkg_key, metadata)
+                                       pkg_world  = world_set.findAtomForPackage(pkg_key, metadata)
+                                       if not pkg_world and myroot == self.target_root and \
+                                               favorites_set.findAtomForPackage(pkg_key, metadata):
                                                # Maybe it will be added to world now.
-                                               if create_world_atom(pkg, favorites_set, root_config):
+                                               if create_world_atom(pkg_key, metadata,
+                                                       favorites_set, root_config):
                                                        pkg_world = True
                                except portage_exception.InvalidDependString:
                                        # This is reported elsewhere if relevant.
                                        pass
 
-                               def pkgprint(pkg_str):
+                               def pkgprint(pkg):
                                        if pkg_merge:
                                                if pkg_system:
-                                                       return colorize("PKG_MERGE_SYSTEM", pkg_str)
+                                                       return colorize("PKG_MERGE_SYSTEM", pkg)
                                                elif pkg_world:
-                                                       return colorize("PKG_MERGE_WORLD", pkg_str)
+                                                       return colorize("PKG_MERGE_WORLD", pkg)
                                                else:
-                                                       return colorize("PKG_MERGE", pkg_str)
-                                       elif pkg_status == "uninstall":
-                                               return colorize("PKG_UNINSTALL", pkg_str)
+                                                       return colorize("PKG_MERGE", pkg)
                                        else:
                                                if pkg_system:
-                                                       return colorize("PKG_NOMERGE_SYSTEM", pkg_str)
+                                                       return colorize("PKG_NOMERGE_SYSTEM", pkg)
                                                elif pkg_world:
-                                                       return colorize("PKG_NOMERGE_WORLD", pkg_str)
+                                                       return colorize("PKG_NOMERGE_WORLD", pkg)
                                                else:
-                                                       return colorize("PKG_NOMERGE", pkg_str)
+                                                       return colorize("PKG_NOMERGE", pkg)
 
                                if x[1]!="/":
                                        if myoldbest:
@@ -5161,14 +3611,7 @@ class depgraph(object):
                                                        myprint=myprint+myoldbest
                                                        myprint=myprint+darkgreen("to "+x[1])
                                                else:
-                                                       if not pkg_merge:
-                                                               myprint = "[%s] %s%s" % \
-                                                                       (pkgprint(pkg_status.ljust(13)),
-                                                                       indent, pkgprint(pkg.cp))
-                                                       else:
-                                                               myprint = "[%s %s] %s%s" % \
-                                                                       (pkgprint(pkg.type_name), addl,
-                                                                       indent, pkgprint(pkg.cp))
+                                                       myprint="["+pkgprint(pkg_type)+" "+addl+"] "+indent+pkgprint(pkg_cp)
                                                        if (newlp-nc_len(myprint)) > 0:
                                                                myprint=myprint+(" "*(newlp-nc_len(myprint)))
                                                        myprint=myprint+"["+darkblue(xs[1]+xs[2])+"] "
@@ -5178,7 +3621,7 @@ class depgraph(object):
                                                        myprint=myprint+darkgreen("to "+x[1])+" "+verboseadd
                                        else:
                                                if not pkg_merge:
-                                                       myprint = "[%s] " % pkgprint(pkg_status.ljust(13))
+                                                       myprint = "[%s      ] " % pkgprint("nomerge")
                                                else:
                                                        myprint = "[" + pkg_type + " " + addl + "] "
                                                myprint += indent + pkgprint(pkg_key) + " " + \
@@ -5191,14 +3634,7 @@ class depgraph(object):
                                                        myprint=myprint+" "+green(xs[1]+xs[2])+" "
                                                        myprint=myprint+myoldbest
                                                else:
-                                                       if not pkg_merge:
-                                                               myprint = "[%s] %s%s" % \
-                                                                       (pkgprint(pkg_status.ljust(13)),
-                                                                       indent, pkgprint(pkg.cp))
-                                                       else:
-                                                               myprint = "[%s %s] %s%s" % \
-                                                                       (pkgprint(pkg.type_name), addl,
-                                                                       indent, pkgprint(pkg.cp))
+                                                       myprint="["+pkgprint(pkg_type)+" "+addl+"] "+indent+pkgprint(pkg_cp)
                                                        if (newlp-nc_len(myprint)) > 0:
                                                                myprint=myprint+(" "*(newlp-nc_len(myprint)))
                                                        myprint=myprint+green(" ["+xs[1]+xs[2]+"] ")
@@ -5207,31 +3643,28 @@ class depgraph(object):
                                                        myprint=myprint+myoldbest+"  "+verboseadd
                                        else:
                                                if not pkg_merge:
-                                                       myprint = "[%s] %s%s %s %s" % \
-                                                               (pkgprint(pkg_status.ljust(13)),
-                                                               indent, pkgprint(pkg.cpv),
-                                                               myoldbest, verboseadd)
+                                                       myprint="["+pkgprint("nomerge")+"      ] "+indent+pkgprint(pkg_key)+" "+myoldbest+" "+verboseadd
                                                else:
                                                        myprint="["+pkgprint(pkg_type)+" "+addl+"] "+indent+pkgprint(pkg_key)+" "+myoldbest+" "+verboseadd
                                p.append(myprint)
 
-                               mysplit = [portage.cpv_getkey(pkg_key)] + \
-                                       list(portage.catpkgsplit(pkg_key)[2:])
-                               if "--tree" not in self.myopts and mysplit and \
-                                       len(mysplit) == 3 and mysplit[0] == "sys-apps/portage" and \
-                                       x[1] == "/":
-       
-                                       if mysplit[2] == "r0":
-                                               myversion = mysplit[1]
-                                       else:
-                                               myversion = "%s-%s" % (mysplit[1], mysplit[2])
-       
-                                       if myversion != portage.VERSION and "--quiet" not in self.myopts:
-                                               if mylist_index < len(mylist) - 1:
-                                                       p.append(colorize("WARN", "*** Portage will stop merging at this point and reload itself,"))
-                                                       p.append(colorize("WARN", "    then resume the merge."))
-                                                       print
-                               del mysplit
+                       mysplit = portage.pkgsplit(x[2])
+                       if "--tree" not in self.myopts and mysplit and \
+                               len(mysplit) == 3 and mysplit[0] == "sys-apps/portage" and \
+                               x[1] == "/":
+
+                               if mysplit[2] == "r0":
+                                       myversion = mysplit[1]
+                               else:
+                                       myversion = "%s-%s" % (mysplit[1], mysplit[2])
+
+                               if myversion != portage.VERSION and "--quiet" not in self.myopts:
+                                       if mylist_index < len(mylist) - 1 and \
+                                               "livecvsportage" not in self.settings.features:
+                                               p.append(colorize("WARN", "*** Portage will stop merging at this point and reload itself,"))
+                                               p.append(colorize("WARN", "    then resume the merge."))
+                                               print
+                       del mysplit
 
                for x in p:
                        print x
@@ -5250,67 +3683,15 @@ class depgraph(object):
                                print bold('*'+revision)
                                sys.stdout.write(text)
 
-               sys.stdout.flush()
-               return os.EX_OK
-
-       def display_problems(self):
-               """
-               Display problems with the dependency graph such as slot collisions.
-               This is called internally by display() to show the problems _after_
-               the merge list where it is most likely to be seen, but if display()
-               is not going to be called then this method should be called explicitly
-               to ensure that the user is notified of problems with the graph.
-               """
-
-               if self._circular_deps_for_display is not None:
-                       self._show_circular_deps(
-                               self._circular_deps_for_display)
-
-               # The user is only notified of a slot conflict if
-               # there are no unresolvable blocker conflicts.
-               if self._unsatisfied_blockers_for_display is not None:
-                       self._show_unsatisfied_blockers(
-                               self._unsatisfied_blockers_for_display)
-               else:
-                       self._show_slot_collision_notice()
-
-               # TODO: Add generic support for "set problem" handlers so that
-               # the below warnings aren't special cases for world only.
-
-               if self._missing_args:
-                       world_problems = False
-                       if "world" in self._sets:
-                               for arg, atom in self._missing_args:
-                                       if arg.name == "world":
-                                               world_problems = True
-                                               break
-
-                       if world_problems:
-                               sys.stderr.write("\n!!! Problems have been " + \
-                                       "detected with your world file\n")
-                               sys.stderr.write("!!! Please run " + \
-                                       green("emaint --check world")+"\n\n")
-
-               if self._missing_args:
-                       sys.stderr.write("\n" + colorize("BAD", "!!!") + \
-                               " Ebuilds for the following packages are either all\n")
-                       sys.stderr.write(colorize("BAD", "!!!") + \
-                               " masked or don't exist:\n")
-                       sys.stderr.write(" ".join(atom for arg, atom in \
-                               self._missing_args) + "\n")
-
                if self._pprovided_args:
                        arg_refs = {}
-                       for arg, atom in self._pprovided_args:
-                               if isinstance(arg, SetArg):
-                                       parent = arg.name
-                                       arg_atom = (atom, atom)
-                               else:
-                                       parent = "args"
-                                       arg_atom = (arg.arg, atom)
-                               refs = arg_refs.setdefault(arg_atom, [])
-                               if parent not in refs:
-                                       refs.append(parent)
+                       for arg_atom in self._pprovided_args:
+                               arg, atom = arg_atom
+                               arg_refs[arg_atom] = []
+                               cp = portage.dep_getkey(atom)
+                               for set_name, atom_set in self._sets.iteritems():
+                                       if atom in atom_set:
+                                               arg_refs[arg_atom].append(set_name)
                        msg = []
                        msg.append(bad("\nWARNING: "))
                        if len(self._pprovided_args) > 1:
@@ -5338,23 +3719,7 @@ class depgraph(object):
                                msg.append("The best course of action depends on the reason that an offending\n")
                                msg.append("package.provided entry exists.\n\n")
                        sys.stderr.write("".join(msg))
-
-               masked_packages = []
-               for pkg in self._masked_installed:
-                       root_config = pkg.root_config
-                       pkgsettings = self.pkgsettings[pkg.root]
-                       mreasons = get_masking_status(pkg, pkgsettings, root_config)
-                       masked_packages.append((root_config, pkgsettings,
-                               pkg.cpv, pkg.metadata, mreasons))
-               if masked_packages:
-                       sys.stderr.write("\n" + colorize("BAD", "!!!") + \
-                               " The following installed packages are masked:\n")
-                       show_masked_packages(masked_packages)
-                       show_mask_docs()
-                       print
-
-               for pargs, kwargs in self._unsatisfied_deps_for_display:
-                       self._show_unsatisfied_dep(*pargs, **kwargs)
+               return os.EX_OK
 
        def calc_changelog(self,ebuildpath,current,next):
                if ebuildpath == None or not os.path.exists(ebuildpath):
@@ -5418,7 +3783,7 @@ class depgraph(object):
                root_config = self.roots[self.target_root]
                world_set = root_config.sets["world"]
                world_set.lock()
-               world_set.load() # maybe it's changed on disk
+               world_set.load()
                args_set = self._sets["args"]
                portdb = self.trees[self.target_root]["porttree"].dbapi
                added_favorites = set()
@@ -5426,380 +3791,57 @@ class depgraph(object):
                        pkg_type, root, pkg_key, pkg_status = x
                        if pkg_status != "nomerge":
                                continue
-
+                       metadata = dict(izip(self._mydbapi_keys,
+                               self.mydbapi[root].aux_get(pkg_key, self._mydbapi_keys)))
                        try:
-                               myfavkey = create_world_atom(x, args_set, root_config)
+                               myfavkey = create_world_atom(pkg_key, metadata,
+                                       args_set, root_config)
                                if myfavkey:
                                        if myfavkey in added_favorites:
                                                continue
                                        added_favorites.add(myfavkey)
+                                       world_set.add(myfavkey)
+                                       print ">>> Recording",myfavkey,"in \"world\" favorites file..."
                        except portage_exception.InvalidDependString, e:
                                writemsg("\n\n!!! '%s' has invalid PROVIDE: %s\n" % \
                                        (pkg_key, str(e)), noiselevel=-1)
                                writemsg("!!! see '%s'\n\n" % os.path.join(
                                        root, portage.VDB_PATH, pkg_key, "PROVIDE"), noiselevel=-1)
                                del e
-               all_added = []
-               for k in self._sets:
-                       if k in ("args", "world"):
-                               continue
-                       s = SETPREFIX + k
-                       if s in world_set:
-                               continue
-                       # sets in world are supported in newer portage
-                       #all_added.append(SETPREFIX + k)
-               all_added.extend(added_favorites)
-               all_added.sort()
-               for a in all_added:
-                       print ">>> Recording %s in \"world\" favorites file..." % \
-                               colorize("INFORM", a)
-               if all_added:
-                       world_set.update(all_added)
+               if added_favorites:
                        world_set.save()
                world_set.unlock()
 
-       def loadResumeCommand(self, resume_data):
-               """
-               Add a resume command to the graph and validate it in the process.  This
-               will raise a PackageNotFound exception if a package is not available.
-               """
-
-               if not isinstance(resume_data, dict):
-                       return False
-
-               mergelist = resume_data.get("mergelist")
-               if not isinstance(mergelist, list):
-                       mergelist = []
-
-               skipfirst = "--skipfirst" in self.myopts
-               fakedb = self.mydbapi
-               trees = self.trees
-               serialized_tasks = []
-               masked_tasks = []
-               for x in mergelist:
-                       if not (isinstance(x, list) and len(x) == 4):
-                               continue
-                       pkg_type, myroot, pkg_key, action = x
-                       if pkg_type not in self.pkg_tree_map:
-                               continue
-                       if action != "merge":
-                               continue
-                       mydb = trees[myroot][self.pkg_tree_map[pkg_type]].dbapi
-                       try:
-                               metadata = izip(self._mydbapi_keys,
-                                       mydb.aux_get(pkg_key, self._mydbapi_keys))
-                       except KeyError:
-                               # It does no exist or it is corrupt.
-                               if action == "uninstall":
-                                       continue
-                               raise portage_exception.PackageNotFound(pkg_key)
-                       installed = action == "uninstall"
-                       built = pkg_type != "ebuild"
-                       root_config = self.roots[myroot]
-                       pkg = Package(built=built, cpv=pkg_key,
-                               installed=installed, metadata=metadata,
-                               operation=action, root_config=root_config,
-                               type_name=pkg_type)
-                       if pkg_type == "ebuild":
-                               pkgsettings = self.pkgsettings[myroot]
-                               pkgsettings.setcpv(pkg)
-                               pkg.metadata["USE"] = pkgsettings["PORTAGE_USE"]
-                       self._pkg_cache[pkg] = pkg
-
-                       root_config = self.roots[pkg.root]
-                       if "merge" == pkg.operation and \
-                               not visible(root_config.settings, pkg):
-                               if skipfirst:
-                                       masked_tasks.append(Dependency(root=pkg.root, parent=pkg))
-                               else:
-                                       self._unsatisfied_deps_for_display.append(
-                                               ((pkg.root, "="+pkg.cpv), {"myparent":None}))
-
-                       fakedb[myroot].cpv_inject(pkg)
-                       serialized_tasks.append(pkg)
-                       self.spinner.update()
-
-               if self._unsatisfied_deps_for_display:
-                       return False
-
-               if not serialized_tasks or "--nodeps" in self.myopts:
-                       self._serialized_tasks_cache = serialized_tasks
-               else:
-                       self._select_package = self._select_pkg_from_graph
-                       self.myparams.add("selective")
-
-                       favorites = resume_data.get("favorites")
-                       args_set = self._sets["args"]
-                       if isinstance(favorites, list):
-                               args = self._load_favorites(favorites)
-                       else:
-                               args = []
-
-                       for task in serialized_tasks:
-                               if isinstance(task, Package) and \
-                                       task.operation == "merge":
-                                       if not self._add_pkg(task, None):
-                                               return False
-
-                       # Packages for argument atoms need to be explicitly
-                       # added via _add_pkg() so that they are included in the
-                       # digraph (needed at least for --tree display).
-                       for arg in args:
-                               for atom in arg.set:
-                                       pkg, existing_node = self._select_package(
-                                               arg.root_config.root, atom)
-                                       if existing_node is None and \
-                                               pkg is not None:
-                                               if not self._add_pkg(pkg, arg):
-                                                       return False
-
-                       # Allow unsatisfied deps here to avoid showing a masking
-                       # message for an unsatisfied dep that isn't necessarily
-                       # masked.
-                       if not self._create_graph(allow_unsatisfied=True):
-                               return False
-                       if masked_tasks or self._unsatisfied_deps:
-                               # This probably means that a required package
-                               # was dropped via --skipfirst. It makes the
-                               # resume list invalid, so convert it to a
-                               # UnsatisfiedResumeDep exception.
-                               raise self.UnsatisfiedResumeDep(
-                                       masked_tasks + self._unsatisfied_deps)
-                       self._serialized_tasks_cache = None
-                       try:
-                               self.altlist()
-                       except self._unknown_internal_error:
-                               return False
-
-               return True
-
-       def _load_favorites(self, favorites):
-               """
-               Use a list of favorites to resume state from a
-               previous select_files() call. This creates similar
-               DependencyArg instances to those that would have
-               been created by the original select_files() call.
-               This allows Package instances to be matched with
-               DependencyArg instances during graph creation.
-               """
-               root_config = self.roots[self.target_root]
-               getSetAtoms = root_config.setconfig.getSetAtoms
-               sets = root_config.sets
-               args = []
-               for x in favorites:
-                       if not isinstance(x, basestring):
-                               continue
-                       if x in ("system", "world"):
-                               x = SETPREFIX + x
-                       if x.startswith(SETPREFIX):
-                               s = x[len(SETPREFIX):]
-                               if s not in sets:
-                                       continue
-                               if s in self._sets:
-                                       continue
-                               # Recursively expand sets so that containment tests in
-                               # self._get_parent_sets() properly match atoms in nested
-                               # sets (like if world contains system).
-                               expanded_set = InternalPackageSet(
-                                       initial_atoms=getSetAtoms(s))
-                               self._sets[s] = expanded_set
-                               args.append(SetArg(arg=x, set=expanded_set,
-                                       root_config=root_config))
-                       else:
-                               if not portage.isvalidatom(x):
-                                       continue
-                               args.append(AtomArg(arg=x, atom=x,
-                                       root_config=root_config))
-
-               # Create the "args" package set from atoms and
-               # packages given as arguments.
-               args_set = self._sets["args"]
-               for arg in args:
-                       if not isinstance(arg, (AtomArg, PackageArg)):
-                               continue
-                       myatom = arg.atom
-                       if myatom in args_set:
-                               continue
-                       args_set.add(myatom)
-               self._set_atoms.update(chain(*self._sets.itervalues()))
-               atom_arg_map = self._atom_arg_map
-               for arg in args:
-                       for atom in arg.set:
-                               atom_key = (atom, arg.root_config.root)
-                               refs = atom_arg_map.get(atom_key)
-                               if refs is None:
-                                       refs = []
-                                       atom_arg_map[atom_key] = refs
-                                       if arg not in refs:
-                                               refs.append(arg)
-               return args
-
-       class UnsatisfiedResumeDep(portage_exception.PortageException):
-               """
-               A dependency of a resume list is not installed. This
-               can occur when a required package is dropped from the
-               merge list via --skipfirst.
-               """
-
-       class _internal_exception(portage_exception.PortageException):
-               def __init__(self, value=""):
-                       portage_exception.PortageException.__init__(self, value)
-
-       class _unknown_internal_error(_internal_exception):
-               """
-               Used by the depgraph internally to terminate graph creation.
-               The specific reason for the failure should have been dumped
-               to stderr, unfortunately, the exact reason for the failure
-               may not be known.
-               """
-
-       class _serialize_tasks_retry(_internal_exception):
-               """
-               This is raised by the _serialize_tasks() method when it needs to
-               be called again for some reason. The only case that it's currently
-               used for is when neglected dependencies need to be added to the
-               graph in order to avoid making a potentially unsafe decision.
-               """
-
-       class _dep_check_composite_db(portage.dbapi):
+       def loadResumeCommand(self, resume_data):
                """
-               A dbapi-like interface that is optimized for use in dep_check() calls.
-               This is built on top of the existing depgraph package selection logic.
-               Some packages that have been added to the graph may be masked from this
-               view in order to influence the atom preference selection that occurs
-               via dep_check().
+               Add a resume command to the graph and validate it in the process.  This
+               will raise a PackageNotFound exception if a package is not available.
                """
-               def __init__(self, depgraph, root):
-                       portage.dbapi.__init__(self)
-                       self._depgraph = depgraph
-                       self._root = root
-                       self._match_cache = {}
-                       self._cpv_pkg_map = {}
-
-               def match(self, atom):
-                       ret = self._match_cache.get(atom)
-                       if ret is not None:
-                               return ret[:]
-                       orig_atom = atom
-                       if "/" not in atom:
-                               atom = self._dep_expand(atom)
-                       pkg, existing = self._depgraph._select_package(self._root, atom)
-                       if not pkg:
-                               ret = []
-                       else:
-                               # Return the highest available from select_package() as well as
-                               # any matching slots in the graph db.
-                               slots = set()
-                               slots.add(pkg.metadata["SLOT"])
-                               atom_cp = portage.dep_getkey(atom)
-                               if pkg.cp.startswith("virtual/"):
-                                       # For new-style virtual lookahead that occurs inside
-                                       # dep_check(), examine all slots. This is needed
-                                       # so that newer slots will not unnecessarily be pulled in
-                                       # when a satisfying lower slot is already installed. For
-                                       # example, if virtual/jdk-1.4 is satisfied via kaffe then
-                                       # there's no need to pull in a newer slot to satisfy a
-                                       # virtual/jdk dependency.
-                                       for db, pkg_type, built, installed, db_keys in \
-                                               self._depgraph._filtered_trees[self._root]["dbs"]:
-                                               for cpv in db.match(atom):
-                                                       if portage.cpv_getkey(cpv) != pkg.cp:
-                                                               continue
-                                                       slots.add(db.aux_get(cpv, ["SLOT"])[0])
-                               ret = []
-                               if self._visible(pkg):
-                                       self._cpv_pkg_map[pkg.cpv] = pkg
-                                       ret.append(pkg.cpv)
-                               slots.remove(pkg.metadata["SLOT"])
-                               while slots:
-                                       slot_atom = "%s:%s" % (atom_cp, slots.pop())
-                                       pkg, existing = self._depgraph._select_package(
-                                               self._root, slot_atom)
-                                       if not pkg:
-                                               continue
-                                       if not self._visible(pkg):
-                                               continue
-                                       self._cpv_pkg_map[pkg.cpv] = pkg
-                                       ret.append(pkg.cpv)
-                               if ret:
-                                       self._cpv_sort_ascending(ret)
-                       self._match_cache[orig_atom] = ret
-                       return ret[:]
-
-               def _visible(self, pkg):
-                       if pkg.installed and "selective" not in self._depgraph.myparams:
-                               try:
-                                       arg = self._depgraph._iter_atoms_for_pkg(pkg).next()
-                               except (StopIteration, portage_exception.InvalidDependString):
-                                       arg = None
-                               if arg:
-                                       return False
-                               if pkg.installed:
-                                       try:
-                                               if not visible(
-                                                       self._depgraph.pkgsettings[pkg.root], pkg):
-                                                       return False
-                                       except portage_exception.InvalidDependString:
-                                               pass
-                       return True
-
-               def _dep_expand(self, atom):
-                       """
-                       This is only needed for old installed packages that may
-                       contain atoms that are not fully qualified with a specific
-                       category. Emulate the cpv_expand() function that's used by
-                       dbapi.match() in cases like this. If there are multiple
-                       matches, it's often due to a new-style virtual that has
-                       been added, so try to filter those out to avoid raising
-                       a ValueError.
-                       """
-                       root_config = self._depgraph.roots[self._root]
-                       orig_atom = atom
-                       expanded_atoms = self._depgraph._dep_expand(root_config, atom)
-                       if len(expanded_atoms) > 1:
-                               non_virtual_atoms = []
-                               for x in expanded_atoms:
-                                       if not portage.dep_getkey(x).startswith("virtual/"):
-                                               non_virtual_atoms.append(x)
-                               if len(non_virtual_atoms) == 1:
-                                       expanded_atoms = non_virtual_atoms
-                       if len(expanded_atoms) > 1:
-                               # compatible with portage.cpv_expand()
-                               raise ValueError([portage.dep_getkey(x) \
-                                       for x in expanded_atoms])
-                       if expanded_atoms:
-                               atom = expanded_atoms[0]
-                       else:
-                               null_atom = insert_category_into_atom(atom, "null")
-                               null_cp = portage.dep_getkey(null_atom)
-                               cat, atom_pn = portage.catsplit(null_cp)
-                               virts_p = root_config.settings.get_virts_p().get(atom_pn)
-                               if virts_p:
-                                       # Allow the resolver to choose which virtual.
-                                       atom = insert_category_into_atom(atom, "virtual")
-                               else:
-                                       atom = insert_category_into_atom(atom, "null")
-                       return atom
-
-               def aux_get(self, cpv, wants):
-                       metadata = self._cpv_pkg_map[cpv].metadata
-                       return [metadata.get(x, "") for x in wants]
-
-       class _package_cache(dict):
-               def __init__(self, depgraph):
-                       dict.__init__(self)
-                       self._depgraph = depgraph
-
-               def __setitem__(self, k, v):
-                       dict.__setitem__(self, k, v)
-                       root_config = self._depgraph.roots[v.root]
+               self._sets["args"].update(resume_data.get("favorites", []))
+               mergelist = resume_data.get("mergelist", [])
+               fakedb = self.mydbapi
+               trees = self.trees
+               for x in mergelist:
+                       if len(x) != 4:
+                               continue
+                       pkg_type, myroot, pkg_key, action = x
+                       if pkg_type not in self.pkg_tree_map:
+                               continue
+                       if action != "merge":
+                               continue
+                       mydb = trees[myroot][self.pkg_tree_map[pkg_type]].dbapi
                        try:
-                               if visible(root_config.settings, v) and \
-                                       not (v.installed and \
-                                       v.root_config.settings._getMissingKeywords(v.cpv, v.metadata)):
-                                       root_config.visible_pkgs.cpv_inject(v)
-                       except portage_exception.InvalidDependString:
-                               pass
+                               metadata = dict(izip(self._mydbapi_keys,
+                                       mydb.aux_get(pkg_key, self._mydbapi_keys)))
+                       except KeyError:
+                               # It does no exist or it is corrupt.
+                               raise portage_exception.PackageNotFound(pkg_key)
+                       fakedb[myroot].cpv_inject(pkg_key, metadata=metadata)
+                       if pkg_type == "ebuild":
+                               pkgsettings = self.pkgsettings[myroot]
+                               pkgsettings.setcpv(pkg_key, mydb=fakedb[myroot])
+                               fakedb[myroot].aux_update(pkg_key, {"USE":pkgsettings["USE"]})
+                       self.spinner.update()
 
 class RepoDisplay(object):
        def __init__(self, roots):
@@ -5868,9 +3910,7 @@ class PackageCounters(object):
                self.new        = 0
                self.newslot    = 0
                self.reinst     = 0
-               self.uninst     = 0
                self.blocks     = 0
-               self.blocks_satisfied         = 0
                self.totalsize  = 0
                self.restrict_fetch           = 0
                self.restrict_fetch_satisfied = 0
@@ -5902,9 +3942,9 @@ class PackageCounters(object):
                        details.append("%s reinstall" % self.reinst)
                        if self.reinst > 1:
                                details[-1] += "s"
-               if self.uninst > 0:
-                       details.append("%s uninstall" % self.uninst)
-                       if self.uninst > 1:
+               if self.blocks > 0:
+                       details.append("%s block" % self.blocks)
+                       if self.blocks > 1:
                                details[-1] += "s"
                myoutput.append(", ".join(details))
                if total_installs != 0:
@@ -5918,23 +3958,10 @@ class PackageCounters(object):
                if self.restrict_fetch_satisfied < self.restrict_fetch:
                        myoutput.append(bad(" (%s unsatisfied)") % \
                                (self.restrict_fetch - self.restrict_fetch_satisfied))
-               if self.blocks > 0:
-                       myoutput.append("\nConflict: %s block" % \
-                               self.blocks)
-                       if self.blocks > 1:
-                               myoutput.append("s")
-                       if self.blocks_satisfied < self.blocks:
-                               myoutput.append(bad(" (%s unsatisfied)") % \
-                                       (self.blocks - self.blocks_satisfied))
                return "".join(myoutput)
 
 class MergeTask(object):
 
-       _opts_ignore_blockers = \
-               frozenset(["--buildpkgonly",
-               "--fetchonly", "--fetch-all-uri",
-               "--nodeps", "--pretend"])
-
        def __init__(self, settings, trees, myopts):
                self.settings = settings
                self.target_root = settings["ROOT"]
@@ -5944,50 +3971,13 @@ class MergeTask(object):
                if settings.get("PORTAGE_DEBUG", "") == "1":
                        self.edebug = 1
                self.pkgsettings = {}
-               self._blocker_db = {}
-               for root in trees:
-                       self.pkgsettings[root] = portage.config(
-                               clone=trees[root]["vartree"].settings)
-                       self._blocker_db[root] = BlockerDB(trees[root]["root_config"])
+               self.pkgsettings[self.target_root] = portage.config(clone=settings)
+               if self.target_root != "/":
+                       self.pkgsettings["/"] = \
+                               portage.config(clone=trees["/"]["vartree"].settings)
                self.curval = 0
                self._spawned_pids = []
 
-       def _find_blockers(self, new_pkg):
-               """
-               Returns a callable which should be called only when
-               the vdb lock has been acquired.
-               """
-               def get_blockers():
-                       return self._find_blockers_with_lock(new_pkg, acquire_lock=0)
-               return get_blockers
-
-       def _find_blockers_with_lock(self, new_pkg, acquire_lock=0):
-               if self._opts_ignore_blockers.intersection(self.myopts):
-                       return None
-
-               # Call gc.collect() here to avoid heap overflow that
-               # triggers 'Cannot allocate memory' errors (reported
-               # with python-2.5).
-               import gc
-               gc.collect()
-
-               blocker_dblinks = []
-               for blocking_pkg in self._blocker_db[
-                       new_pkg.root].findInstalledBlockers(new_pkg,
-                       acquire_lock=acquire_lock):
-                       if new_pkg.slot_atom == blocking_pkg.slot_atom:
-                               continue
-                       if new_pkg.cpv == blocking_pkg.cpv:
-                               continue
-                       blocker_dblinks.append(portage.dblink(
-                               blocking_pkg.category, blocking_pkg.pf, blocking_pkg.root,
-                               self.pkgsettings[blocking_pkg.root], treetype="vartree",
-                               vartree=self.trees[blocking_pkg.root]["vartree"]))
-
-               gc.collect()
-
-               return blocker_dblinks
-
        def merge(self, mylist, favorites, mtimedb):
                try:
                        return self._merge(mylist, favorites, mtimedb)
@@ -6017,12 +4007,10 @@ class MergeTask(object):
 
        def _merge(self, mylist, favorites, mtimedb):
                failed_fetches = []
-               buildpkgonly = "--buildpkgonly" in self.myopts
                fetchonly = "--fetchonly" in self.myopts or \
                        "--fetch-all-uri" in self.myopts
-               oneshot = "--oneshot" in self.myopts or \
-                       "--onlydeps" in self.myopts
                pretend = "--pretend" in self.myopts
+               mymergelist=[]
                ldpath_mtimes = mtimedb["ldpath"]
                xterm_titles = "notitles" not in self.settings.features
 
@@ -6030,13 +4018,12 @@ class MergeTask(object):
                        # We're resuming.
                        print colorize("GOOD", "*** Resuming merge...")
                        emergelog(xterm_titles, " *** Resuming merge...")
-
-               # Do this before verifying the ebuild Manifests since it might
-               # be possible for the user to use --resume --skipfirst get past
-               # a non-essential package with a broken digest.
-               mtimedb["resume"]["mergelist"] = [list(x) for x in mylist \
-                       if isinstance(x, Package) and x.operation == "merge"]
-               mtimedb.commit()
+                       mylist = mtimedb["resume"]["mergelist"][:]
+                       if "--skipfirst" in self.myopts and mylist:
+                               del mtimedb["resume"]["mergelist"][0]
+                               del mylist[0]
+                               mtimedb.commit()
+                       mymergelist = mylist
 
                # Verify all the manifests now so that the user is notified of failure
                # as soon as possible.
@@ -6066,14 +4053,17 @@ class MergeTask(object):
                                del x, mytype, myroot, mycpv, mystatus, quiet_config
                        del shown_verifying_msg, quiet_settings
 
-               root_config = self.trees[self.target_root]["root_config"]
+               root_config = RootConfig(self.trees[self.target_root])
                system_set = root_config.sets["system"]
-               args_set = InternalPackageSet(favorites)
+               args_set = AtomSet(favorites)
                world_set = root_config.sets["world"]
+               if "--resume" not in self.myopts:
+                       mymergelist = mylist
+                       mtimedb["resume"]["mergelist"]=mymergelist[:]
+                       mtimedb.commit()
 
-               mymergelist = mylist
                myfeat = self.settings.features[:]
-               bad_resume_opts = set(["--ask", "--changelog", "--skipfirst",
+               bad_resume_opts = set(["--ask", "--tree", "--changelog", "--skipfirst",
                        "--resume"])
                if "parallel-fetch" in myfeat and \
                        not ("--pretend" in self.myopts or \
@@ -6094,9 +4084,7 @@ class MergeTask(object):
                                fetch_env = os.environ.copy()
                                fetch_env["FEATURES"] = fetch_env.get("FEATURES", "") + " -cvs"
                                fetch_env["PORTAGE_NICENESS"] = "0"
-                               fetch_env["PORTAGE_PARALLEL_FETCHONLY"] = "1"
-                               fetch_args = [sys.argv[0], "--resume",
-                                       "--fetchonly", "--nodeps"]
+                               fetch_args = [sys.argv[0], "--resume", "--fetchonly"]
                                resume_opts = self.myopts.copy()
                                # For automatic resume, we need to prevent
                                # any of bad_resume_opts from leaking in
@@ -6121,51 +4109,33 @@ class MergeTask(object):
                metadata_keys = [k for k in portage.auxdbkeys \
                        if not k.startswith("UNUSED_")] + ["USE"]
 
-               task_list = mymergelist
-               # Filter mymergelist so that all the len(mymergelist) calls
-               # below (for display) do not count Uninstall instances.
-               mymergelist = [x for x in mymergelist if x[-1] == "merge"]
                mergecount=0
-               for x in task_list:
-                       if x[0] == "blocks":
-                               continue
-                       pkg_type, myroot, pkg_key, operation = x
+               for x in mymergelist:
+                       mergecount+=1
+                       pkg_type = x[0]
+                       myroot=x[1]
+                       pkg_key = x[2]
                        pkgindex=2
-                       built = pkg_type != "ebuild"
-                       installed = pkg_type == "installed"
                        portdb = self.trees[myroot]["porttree"].dbapi
                        bindb  = self.trees[myroot]["bintree"].dbapi
                        vartree = self.trees[myroot]["vartree"]
-                       vardb = vartree.dbapi
-                       root_config = self.trees[myroot]["root_config"]
                        pkgsettings = self.pkgsettings[myroot]
+                       metadata = {}
                        if pkg_type == "blocks":
                                pass
                        elif pkg_type == "ebuild":
                                mydbapi = portdb
+                               metadata.update(izip(metadata_keys,
+                                       mydbapi.aux_get(pkg_key, metadata_keys)))
+                               pkgsettings.setcpv(pkg_key, mydb=mydbapi)
+                               metadata["USE"] = pkgsettings["USE"]
                        else:
                                if pkg_type == "binary":
                                        mydbapi = bindb
-                               elif pkg_type == "installed":
-                                       mydbapi = vardb
                                else:
                                        raise AssertionError("Package type: '%s'" % pkg_type)
-                       if not installed:
-                               mergecount += 1
-                       pkg = x
-                       metadata = pkg.metadata
-
-                       if pkg.installed:
-                               if not (buildpkgonly or fetchonly or pretend):
-                                       try:
-                                               unmerge(root_config.settings, self.myopts,
-                                                       root_config.trees["vartree"], "unmerge",
-                                                       [pkg.cpv], mtimedb["ldpath"], clean_world=0,
-                                                       raise_on_error=1)
-                                       except UninstallFailure, e:
-                                               return e.status
-                               continue
-
+                               metadata.update(izip(metadata_keys,
+                                       mydbapi.aux_get(pkg_key, metadata_keys)))
                        if x[0]=="blocks":
                                pkgindex=3
                        y = portdb.findname(pkg_key)
@@ -6185,7 +4155,7 @@ class MergeTask(object):
                        #buildsyspkg: Check if we need to _force_ binary package creation
                        issyspkg = ("buildsyspkg" in myfeat) \
                                        and x[0] != "blocks" \
-                                       and system_set.findAtomForPackage(pkg) \
+                                       and system_set.findAtomForPackage(pkg_key, metadata) \
                                        and "--buildpkg" not in self.myopts
                        if x[0] in ["ebuild","blocks"]:
                                if x[0] == "blocks" and "--fetchonly" not in self.myopts:
@@ -6221,7 +4191,7 @@ class MergeTask(object):
                                try:
                                        catdir_lock = portage_locks.lockdir(catdir)
                                        portage_util.ensure_dirs(catdir,
-                                               gid=portage.portage_gid,
+                                               uid=portage.portage_uid, gid=portage.portage_gid,
                                                mode=070, mask=0)
                                        builddir_lock = portage_locks.lockdir(
                                                pkgsettings["PORTAGE_BUILDDIR"])
@@ -6252,12 +4222,14 @@ class MergeTask(object):
                                                retval = portage.doebuild(y, "package", myroot,
                                                        pkgsettings, self.edebug, mydbapi=portdb,
                                                        tree="porttree")
+                                               if retval != os.EX_OK or \
+                                                       "--buildpkgonly" in self.myopts:
+                                                       portage.elog_process(pkg_key, pkgsettings)
                                                if retval != os.EX_OK:
                                                        return retval
                                                bintree = self.trees[myroot]["bintree"]
                                                if bintree.populated:
                                                        bintree.inject(pkg_key)
-
                                                if "--buildpkgonly" not in self.myopts:
                                                        msg = " === (%s of %s) Merging (%s::%s)" % \
                                                                (mergecount, len(mymergelist), pkg_key, y)
@@ -6270,8 +4242,7 @@ class MergeTask(object):
                                                                "build-info"), myroot, pkgsettings,
                                                                myebuild=pkgsettings["EBUILD"],
                                                                mytree="porttree", mydbapi=portdb,
-                                                               vartree=vartree, prev_mtimes=ldpath_mtimes,
-                                                               blockers=self._find_blockers(pkg))
+                                                               vartree=vartree, prev_mtimes=ldpath_mtimes)
                                                        if retval != os.EX_OK:
                                                                return retval
                                                elif "noclean" not in pkgsettings.features:
@@ -6284,26 +4255,14 @@ class MergeTask(object):
                                                short_msg = "emerge: (%s of %s) %s Compile" % \
                                                        (mergecount, len(mymergelist), pkg_key)
                                                emergelog(xterm_titles, msg, short_msg=short_msg)
-                                               retval = portage.doebuild(y, "install", myroot,
+                                               retval = portage.doebuild(y, "merge", myroot,
                                                        pkgsettings, self.edebug, vartree=vartree,
                                                        mydbapi=portdb, tree="porttree",
                                                        prev_mtimes=ldpath_mtimes)
                                                if retval != os.EX_OK:
                                                        return retval
-
-                                               retval = portage.merge(pkgsettings["CATEGORY"],
-                                                       pkgsettings["PF"], pkgsettings["D"],
-                                                       os.path.join(pkgsettings["PORTAGE_BUILDDIR"],
-                                                       "build-info"), myroot, pkgsettings,
-                                                       myebuild=pkgsettings["EBUILD"],
-                                                       mytree="porttree", mydbapi=portdb,
-                                                       vartree=vartree, prev_mtimes=ldpath_mtimes,
-                                                       blockers=self._find_blockers(pkg))
-                                               if retval != os.EX_OK:
-                                                       return retval
                                finally:
                                        if builddir_lock:
-                                               portage.elog_process(pkg.cpv, pkgsettings)
                                                portage_locks.unlockdir(builddir_lock)
                                        try:
                                                if not catdir_lock:
@@ -6376,17 +4335,19 @@ class MergeTask(object):
                                retval = portage.pkgmerge(mytbz2, x[1], pkgsettings,
                                        mydbapi=bindb,
                                        vartree=self.trees[myroot]["vartree"],
-                                       prev_mtimes=ldpath_mtimes,
-                                       blockers=self._find_blockers(pkg))
+                                       prev_mtimes=ldpath_mtimes)
                                if retval != os.EX_OK:
                                        return retval
                                #need to check for errors
-                       if not buildpkgonly:
-                               if not (fetchonly or oneshot or pretend) and \
-                                       args_set.findAtomForPackage(pkg):
+                       if "--buildpkgonly" not in self.myopts:
+                               self.trees[x[1]]["vartree"].inject(x[2])
+                               myfavkey = portage.cpv_getkey(x[2])
+                               if not fetchonly and not pretend and \
+                                       args_set.findAtomForPackage(pkg_key, metadata):
                                        world_set.lock()
                                        world_set.load()
-                                       myfavkey = create_world_atom(pkg, args_set, root_config)
+                                       myfavkey = create_world_atom(pkg_key, metadata,
+                                               args_set, root_config)
                                        if myfavkey:
                                                world_set.add(myfavkey)
                                                print ">>> Recording",myfavkey,"in \"world\" favorites file..."
@@ -6400,9 +4361,23 @@ class MergeTask(object):
                                if "--pretend" not in self.myopts and \
                                        "--fetchonly" not in self.myopts and \
                                        "--fetch-all-uri" not in self.myopts:
+                                       # Clean the old package that we have merged over top of it.
+                                       if pkgsettings.get("AUTOCLEAN", "yes") == "yes":
+                                               xsplit=portage.pkgsplit(x[2])
+                                               emergelog(xterm_titles, " >>> AUTOCLEAN: " + xsplit[0])
+                                               retval = unmerge(pkgsettings, self.myopts, vartree,
+                                                       "clean", [xsplit[0]], ldpath_mtimes, autoclean=1)
+                                               if not retval:
+                                                       emergelog(xterm_titles,
+                                                               " --- AUTOCLEAN: Nothing unmerged.")
+                                       else:
+                                               portage.writemsg_stdout(colorize("WARN", "WARNING:")
+                                                       + " AUTOCLEAN is disabled.  This can cause serious"
+                                                       + " problems due to overlapping packages.\n")
 
                                        # Figure out if we need a restart.
-                                       if myroot == "/" and pkg.cp == "sys-apps/portage":
+                                       mysplit=portage.pkgsplit(x[2])
+                                       if mysplit[0] == "sys-apps/portage" and x[1] == "/":
                                                if "livecvsportage" not in self.settings.features:
                                                        if len(mymergelist) > mergecount:
                                                                emergelog(xterm_titles,
@@ -6479,20 +4454,8 @@ class MergeTask(object):
                                sys.exit(0)
                return os.EX_OK
 
-class UninstallFailure(portage_exception.PortageException):
-       """
-       An instance of this class is raised by unmerge() when
-       an uninstallation fails.
-       """
-       status = 1
-       def __init__(self, *pargs):
-               portage_exception.PortageException.__init__(self, pargs)
-               if pargs:
-                       self.status = pargs[0]
-
-def unmerge(settings, myopts, vartree, unmerge_action,
-       unmerge_files, ldpath_mtimes, autoclean=0,
-       clean_world=1, ordered=0, raise_on_error=0):
+def unmerge(settings, myopts, vartree, unmerge_action, unmerge_files,
+       ldpath_mtimes, autoclean=0):
        candidate_catpkgs=[]
        global_unmerge=0
        xterm_titles = "notitles" not in settings.features
@@ -6614,12 +4577,8 @@ def unmerge(settings, myopts, vartree, unmerge_action,
                        print darkgreen(newline+\
                                ">>> These are the packages that would be unmerged:")
        
-               # Preservation of order is required for --depclean and --prune so
-               # that dependencies are respected. Use all_selected to eliminate
-               # duplicate packages since the same package may be selected by
-               # multiple atoms.
-               pkgmap = []
-               all_selected = set()
+               pkgmap={}
+               numselected=0
                for x in candidate_catpkgs:
                        # cycle through all our candidate deps and determine
                        # what will and will not get unmerged
@@ -6638,19 +4597,22 @@ def unmerge(settings, myopts, vartree, unmerge_action,
                                sys.exit(1)
        
                        if not mymatch and x[0] not in "<>=~":
-                               mymatch = localtree.dep_match(x)
+                               #add a "=" if missing
+                               mymatch=localtree.dep_match("="+x)
                        if not mymatch:
                                portage.writemsg("\n--- Couldn't find '%s' to %s.\n" % \
                                        (x, unmerge_action), noiselevel=-1)
                                continue
-                       pkgmap.append(
-                               {"protected": set(), "selected": set(), "omitted": set()})
-                       mykey = len(pkgmap) - 1
+                       mykey = portage.key_expand(
+                               portage.dep_getkey(
+                                       mymatch[0]), mydb=vartree.dbapi, settings=settings)
+                       if not pkgmap.has_key(mykey):
+                               pkgmap[mykey]={"protected":[], "selected":[], "omitted":[] }
                        if unmerge_action=="unmerge":
                                        for y in mymatch:
-                                               if y not in all_selected:
-                                                       pkgmap[mykey]["selected"].add(y)
-                                                       all_selected.add(y)
+                                               if y not in pkgmap[mykey]["selected"]:
+                                                       pkgmap[mykey]["selected"].append(y)
+                                                       numselected=numselected+len(mymatch)
                        elif unmerge_action == "prune":
                                if len(mymatch) == 1:
                                        continue
@@ -6671,10 +4633,10 @@ def unmerge(settings, myopts, vartree, unmerge_action,
                                                best_version = mypkg
                                                best_slot = myslot
                                                best_counter = mycounter
-                               pkgmap[mykey]["protected"].add(best_version)
-                               pkgmap[mykey]["selected"].update(mypkg for mypkg in mymatch \
-                                       if mypkg != best_version and mypkg not in all_selected)
-                               all_selected.update(pkgmap[mykey]["selected"])
+                               pkgmap[mykey]["protected"].append(best_version)
+                               pkgmap[mykey]["selected"] = [mypkg for mypkg in mymatch \
+                                       if mypkg != best_version]
+                               numselected = numselected + len(pkgmap[mykey]["selected"])
                        else:
                                # unmerge_action == "clean"
                                slotmap={}
@@ -6694,18 +4656,15 @@ def unmerge(settings, myopts, vartree, unmerge_action,
                                        if not counterkeys:
                                                continue
                                        counterkeys.sort()
-                                       pkgmap[mykey]["protected"].add(
+                                       pkgmap[mykey]["protected"].append(
                                                slotmap[myslot][counterkeys[-1]])
                                        del counterkeys[-1]
                                        #be pretty and get them in order of merge:
                                        for ckey in counterkeys:
-                                               mypkg = slotmap[myslot][ckey]
-                                               if mypkg not in all_selected:
-                                                       pkgmap[mykey]["selected"].add(mypkg)
-                                                       all_selected.add(mypkg)
+                                               pkgmap[mykey]["selected"].append(slotmap[myslot][ckey])
+                                               numselected=numselected+1
                                        # ok, now the last-merged package
                                        # is protected, and the rest are selected
-               numselected = len(all_selected)
                if global_unmerge and not numselected:
                        portage.writemsg_stdout("\n>>> No outdated packages were found on your system.\n")
                        return 0
@@ -6717,55 +4676,26 @@ def unmerge(settings, myopts, vartree, unmerge_action,
                        return 0
        finally:
                if vdb_lock:
-                       vartree.dbapi.flush_cache()
                        portage_locks.unlockdir(vdb_lock)
-
-       # Unmerge order only matters in some cases
-       if not ordered:
-               unordered = {}
-               for d in pkgmap:
-                       selected = d["selected"]
-                       if not selected:
-                               continue
-                       cp = portage.cpv_getkey(iter(selected).next())
-                       cp_dict = unordered.get(cp)
-                       if cp_dict is None:
-                               cp_dict = {}
-                               unordered[cp] = cp_dict
-                               for k in d:
-                                       cp_dict[k] = set()
-                       for k, v in d.iteritems():
-                               cp_dict[k].update(v)
-               pkgmap = [unordered[cp] for cp in sorted(unordered)]
-
-       for x in xrange(len(pkgmap)):
-               selected = pkgmap[x]["selected"]
-               if not selected:
-                       continue
-               for mytype, mylist in pkgmap[x].iteritems():
-                       if mytype == "selected":
-                               continue
-                       mylist.difference_update(all_selected)
-               cp = portage.cpv_getkey(iter(selected).next())
-               for y in localtree.dep_match(cp):
+       for x in pkgmap:
+               for y in localtree.dep_match(x):
                        if y not in pkgmap[x]["omitted"] and \
-                               y not in pkgmap[x]["selected"] and \
-                               y not in pkgmap[x]["protected"] and \
-                               y not in all_selected:
-                               pkgmap[x]["omitted"].add(y)
+                          y not in pkgmap[x]["selected"] and \
+                          y not in pkgmap[x]["protected"]:
+                               pkgmap[x]["omitted"].append(y)
                if global_unmerge and not pkgmap[x]["selected"]:
                        #avoid cluttering the preview printout with stuff that isn't getting unmerged
                        continue
-               if not (pkgmap[x]["protected"] or pkgmap[x]["omitted"]) and cp in syslist:
-                       print colorize("BAD","\a\n\n!!! '%s' is part of your system profile." % cp)
+               if not (pkgmap[x]["protected"] or pkgmap[x]["omitted"]) and (x in syslist):
+                       print colorize("BAD","\a\n\n!!! '%s' is part of your system profile." % x)
                        print colorize("WARN","\a!!! Unmerging it may be damaging to your system.\n")
                        if "--pretend" not in myopts and "--ask" not in myopts:
                                countdown(int(settings["EMERGE_WARNING_DELAY"]),
                                        colorize("UNMERGE_WARN", "Press Ctrl-C to Stop"))
                if "--quiet" not in myopts:
-                       print "\n "+bold(cp)
+                       print "\n "+white(x)
                else:
-                       print bold(cp)+": ",
+                       print white(x)+": ",
                for mytype in ["selected","protected","omitted"]:
                        if "--quiet" not in myopts:
                                portage.writemsg_stdout((mytype + ": ").rjust(14), noiselevel=-1)
@@ -6812,7 +4742,7 @@ def unmerge(settings, myopts, vartree, unmerge_action,
        if not autoclean:
                countdown(int(settings["CLEAN_DELAY"]), ">>> Unmerging")
 
-       for x in xrange(len(pkgmap)):
+       for x in pkgmap:
                for y in pkgmap[x]["selected"]:
                        print ">>> Unmerging "+y+"..."
                        emergelog(xterm_titles, "=== Unmerging... ("+y+")")
@@ -6823,12 +4753,9 @@ def unmerge(settings, myopts, vartree, unmerge_action,
                                vartree=vartree, ldpath_mtimes=ldpath_mtimes)
                        if retval != os.EX_OK:
                                emergelog(xterm_titles, " !!! unmerge FAILURE: "+y)
-                               if raise_on_error:
-                                       raise UninstallFailure(retval)
                                sys.exit(retval)
                        else:
-                               if clean_world:
-                                       world_clean_package(vartree.dbapi, y)
+                               clean_world(vartree.dbapi, y)
                                emergelog(xterm_titles, " >>> unmerge success: "+y)
        return 1
 
@@ -6847,9 +4774,9 @@ def chk_updated_info_files(root, infodirs, prev_mtimes, retval):
                                                regen_infodirs.append(inforoot)
 
                if not regen_infodirs:
-                       portage.writemsg_stdout("\n "+green("*")+" GNU info directory index is up-to-date.\n")
+                       portage.writemsg_stdout(" "+green("*")+" GNU info directory index is up-to-date.\n")
                else:
-                       portage.writemsg_stdout("\n "+green("*")+" Regenerating GNU info directory index...\n")
+                       portage.writemsg_stdout(" "+green("*")+" Regenerating GNU info directory index...\n")
 
                        dir_extensions = ("", ".gz", ".bz2")
                        icount=0
@@ -6858,8 +4785,7 @@ def chk_updated_info_files(root, infodirs, prev_mtimes, retval):
                                if inforoot=='':
                                        continue
 
-                               if not os.path.isdir(inforoot) or \
-                                       not os.access(inforoot, os.W_OK):
+                               if not os.path.isdir(inforoot):
                                        continue
                                errmsg = ""
                                file_list = os.listdir(inforoot)
@@ -6970,18 +4896,13 @@ def post_emerge(settings, mtimedb, retval):
 
        vdb_path = os.path.join(target_root, portage.VDB_PATH)
        portage_util.ensure_dirs(vdb_path)
-       vdb_lock = None
-       if os.access(vdb_path, os.W_OK):
-               vdb_lock = portage_locks.lockdir(vdb_path)
-       if vdb_lock:
-               try:
-                       if "noinfo" not in settings.features:
-                               chk_updated_info_files(target_root,
-                                       infodirs, info_mtimes, retval)
-                       mtimedb.commit()
-               finally:
-                       if vdb_lock:
-                               portage_locks.unlockdir(vdb_lock)
+       vdb_lock = portage_locks.lockdir(vdb_path)
+       try:
+               if "noinfo" not in settings.features:
+                       chk_updated_info_files(target_root, infodirs, info_mtimes, retval)
+               mtimedb.commit()
+       finally:
+               portage_locks.unlockdir(vdb_lock)
 
        chk_updated_cfg_files(target_root, config_protect)
 
@@ -7030,7 +4951,7 @@ def chk_updated_cfg_files(target_root, config_protect):
                                        del files[-1]
                                if files:
                                        procount += 1
-                                       print "\n"+colorize("WARN", " * IMPORTANT:"),
+                                       print colorize("WARN", " * IMPORTANT:"),
                                        if stat.S_ISDIR(mymode):
                                                 print "%d config files in '%s' need updating." % \
                                                        (len(files), x)
@@ -7042,15 +4963,6 @@ def chk_updated_cfg_files(target_root, config_protect):
                                " section of the " + bold("emerge")
                        print " "+yellow("*")+" man page to learn how to update config files."
 
-def insert_category_into_atom(atom, category):
-       alphanum = re.search(r'\w', atom)
-       if alphanum:
-               ret = atom[:alphanum.start()] + "%s/" % category + \
-                       atom[alphanum.start():]
-       else:
-               ret = None
-       return ret
-
 def is_valid_package_atom(x):
        if "/" not in x:
                alphanum = re.search(r'\w', x)
@@ -7066,10 +4978,6 @@ def show_blocker_docs_link():
        print "http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?full=1#blocked"
        print
 
-def show_mask_docs():
-       print "For more information, see the MASKED PACKAGES section in the emerge"
-       print "man page or refer to the Gentoo Handbook."
-
 def action_sync(settings, trees, mtimedb, myopts, myaction):
        xterm_titles = "notitles" not in settings.features
        emergelog(xterm_titles, " === sync")
@@ -7548,7 +5456,7 @@ def action_metadata(settings, portdb, myopts):
        ec = portage.eclass_cache.cache(portdb.porttree_root)
        myportdir = os.path.realpath(settings["PORTDIR"])
        cm = settings.load_best_module("portdbapi.metadbmodule")(
-               myportdir, "metadata/cache", portage.auxdbkeys[:], readonly=True)
+               myportdir, "metadata/cache", portage.auxdbkeys[:])
 
        import cache.util
 
@@ -7868,8 +5776,8 @@ def action_info(settings, trees, myopts, myfiles):
                        if portdb.cpv_exists(pkg):
                                mydb = portdb
                        pkgsettings.setcpv(pkg, mydb=mydb)
-                       if valuesmap["IUSE"].intersection(
-                               pkgsettings["PORTAGE_USE"].split()) != valuesmap["USE"]:
+                       if valuesmap["IUSE"].intersection(pkgsettings["USE"].split()) != \
+                               valuesmap["USE"]:
                                diff_values["USE"] = valuesmap["USE"]
                        # If a difference was found, print the info for
                        # this package.
@@ -7892,11 +5800,11 @@ def action_info(settings, trees, myopts, myfiles):
                                mydbapi=trees[settings["ROOT"]]["vartree"].dbapi,
                                tree="vartree")
 
-def action_search(root_config, myopts, myfiles, spinner):
+def action_search(settings, trees, myopts, myfiles, spinner):
        if not myfiles:
                print "emerge: no search terms provided."
        else:
-               searchinstance = search(root_config,
+               searchinstance = search(settings, trees,
                        spinner, "--searchdesc" in myopts,
                        "--quiet" not in myopts, "--usepkg" in myopts,
                        "--usepkgonly" in myopts)
@@ -7913,14 +5821,6 @@ def action_depclean(settings, trees, ldpath_mtimes,
        # Kill packages that aren't explicitly merged or are required as a
        # dependency of another package. World file is explicit.
 
-       # Global depclean or prune operations are not very safe when there are
-       # missing dependencies since it's unknown how badly incomplete
-       # the dependency graph is, and we might accidentally remove packages
-       # that should have been pulled into the graph. On the other hand, it's
-       # relatively safe to ignore missing deps when only asked to remove
-       # specific packages.
-       allow_missing_deps = len(myfiles) > 0
-
        msg = []
        msg.append("Depclean may break link level dependencies.  Thus, it is\n")
        msg.append("recommended to use a tool such as " + good("`revdep-rebuild`") + " (from\n")
@@ -7946,19 +5846,21 @@ def action_depclean(settings, trees, ldpath_mtimes,
        xterm_titles = "notitles" not in settings.features
        myroot = settings["ROOT"]
        portdb = trees[myroot]["porttree"].dbapi
-       pkg_cache = {}
        dep_check_trees = {}
        dep_check_trees[myroot] = {}
        dep_check_trees[myroot]["vartree"] = \
-               FakeVartree(trees[myroot]["root_config"], pkg_cache=pkg_cache)
+               FakeVartree(trees[myroot]["vartree"],
+               trees[myroot]["porttree"].dbapi,
+               depgraph._mydbapi_keys)
        vardb = dep_check_trees[myroot]["vartree"].dbapi
        # Constrain dependency selection to the installed packages.
        dep_check_trees[myroot]["porttree"] = dep_check_trees[myroot]["vartree"]
-       root_config = trees[myroot]["root_config"]
-       setconfig = root_config.setconfig
-       syslist = setconfig.getSetAtoms("system")
-       worldlist = setconfig.getSetAtoms("world")
-       args_set = InternalPackageSet()
+       system_set = SystemSet(settings)
+       syslist = list(system_set)
+       world_set = WorldSet(settings)
+       world_set.load()
+       worldlist = list(world_set)
+       args_set = AtomSet()
        fakedb = portage.fakedbapi(settings=settings)
        myvarlist = vardb.cpv_all()
 
@@ -8007,38 +5909,23 @@ def action_depclean(settings, trees, ldpath_mtimes,
        if "--quiet" not in myopts:
                print "\nCalculating dependencies  ",
 
-       runtime = UnmergeDepPriority(runtime=True)
-       runtime_post = UnmergeDepPriority(runtime_post=True)
-       buildtime = UnmergeDepPriority(buildtime=True)
-
-       priority_map = {
-               "RDEPEND": runtime,
-               "PDEPEND": runtime_post,
-               "DEPEND": buildtime,
-       }
-
+       soft = 0
+       hard = 1
        remaining_atoms = []
        if action == "depclean":
+               for atom in worldlist:
+                       if vardb.match(atom):
+                               remaining_atoms.append((atom, 'world', hard))
                for atom in syslist:
                        if vardb.match(atom):
-                               remaining_atoms.append((atom, 'system', runtime))
-               if myfiles:
-                       # Pull in everything that's installed since we don't want
-                       # to clean any package if something depends on it.
-                       remaining_atoms.extend(
-                               ("="+cpv, 'world', runtime) for cpv in vardb.cpv_all())
-               else:
-                       for atom in worldlist:
-                               if vardb.match(atom):
-                                       remaining_atoms.append((atom, 'world', runtime))
+                               remaining_atoms.append((atom, 'system', hard))
        elif action == "prune":
                for atom in syslist:
                        if vardb.match(atom):
-                               remaining_atoms.append((atom, 'system', runtime))
+                               remaining_atoms.append((atom, 'system', hard))
                # Pull in everything that's installed since we don't want to prune a
                # package if something depends on it.
-               remaining_atoms.extend(
-                       (atom, 'world', runtime) for atom in vardb.cp_all())
+               remaining_atoms.extend((atom, 'world', hard) for atom in vardb.cp_all())
                if not myfiles:
                        # Try to prune everything that's slotted.
                        for cp in vardb.cp_all():
@@ -8047,15 +5934,14 @@ def action_depclean(settings, trees, ldpath_mtimes,
 
        unresolveable = {}
        aux_keys = ["DEPEND", "RDEPEND", "PDEPEND"]
-       metadata_keys = depgraph._mydbapi_keys
+       metadata_keys = ["PROVIDE", "SLOT", "USE"]
        graph = digraph()
-       with_bdeps = myopts.get("--with-bdeps", "y") == "y"
 
        while remaining_atoms:
                atom, parent, priority = remaining_atoms.pop()
                pkgs = vardb.match(atom)
                if not pkgs:
-                       if priority > UnmergeDepPriority.SOFT:
+                       if not atom.startswith("!") and priority == hard:
                                unresolveable.setdefault(atom, []).append(parent)
                        continue
                if action == "depclean" and parent == "world" and myfiles:
@@ -8063,10 +5949,11 @@ def action_depclean(settings, trees, ldpath_mtimes,
                        # to remove those.
                        filtered_pkgs = []
                        for pkg in pkgs:
+                               metadata = dict(izip(metadata_keys,
+                                       vardb.aux_get(pkg, metadata_keys)))
                                arg_atom = None
                                try:
-                                       arg_atom = args_set.findAtomForPackage(
-                                               pkg_cache[("installed", myroot, pkg, "nomerge")])
+                                       arg_atom = args_set.findAtomForPackage(pkg, metadata)
                                except portage_exception.InvalidDependString, e:
                                        file_path = os.path.join(myroot, portage.VDB_PATH, pkg, "PROVIDE")
                                        portage.writemsg("\n\nInvalid PROVIDE: %s\n" % str(e),
@@ -8078,40 +5965,44 @@ def action_depclean(settings, trees, ldpath_mtimes,
                                        filtered_pkgs.append(pkg)
                        pkgs = filtered_pkgs
                if len(pkgs) > 1:
-                       # For consistency with the update algorithm, keep the highest
-                       # visible version and prune any versions that are old or masked.
-                       for cpv in reversed(pkgs):
-                               if visible(settings,
-                                       pkg_cache[("installed", myroot, cpv, "nomerge")]):
-                                       pkgs = [cpv]
-                                       break
-                       if len(pkgs) > 1:
-                               # They're all masked, so just keep the highest version.
-                               pkgs = [pkgs[-1]]
+                       # Prune all but the best matching slot, since that's all that a
+                       # deep world update would pull in.  Don't prune if this atom comes
+                       # directly from world though, since world atoms are greedy when
+                       # they don't specify a slot.
+                       visible_in_portdb = [cpv for cpv in pkgs if portdb.match("="+cpv)]
+                       if visible_in_portdb:
+                               # For consistency with the update algorithm, keep the highest
+                               # visible version and prune any versions that are either masked
+                               # or no longer exist in the portage tree.
+                               pkgs = visible_in_portdb
+                       pkgs = [portage.best(pkgs)]
                for pkg in pkgs:
-                       graph.add(pkg, parent, priority=priority)
+                       graph.add(pkg, parent)
                        if fakedb.cpv_exists(pkg):
                                continue
                        spinner.update()
                        fakedb.cpv_inject(pkg)
-                       myaux = izip(aux_keys, vardb.aux_get(pkg, aux_keys))
+                       myaux = dict(izip(aux_keys, vardb.aux_get(pkg, aux_keys)))
                        mydeps = []
-
+                       if myopts.get("--with-bdeps", "y") == "y":
+                               mydeps.append((myaux["DEPEND"], soft))
+                       del myaux["DEPEND"]
+                       mydeps.append((" ".join(myaux.values()), hard))
                        usedef = vardb.aux_get(pkg, ["USE"])[0].split()
-                       for dep_type, depstr in myaux:
+                       for depstr, priority in mydeps:
 
                                if not depstr:
                                        continue
 
-                               if not with_bdeps and dep_type == "DEPEND":
-                                       continue
-
-                               priority = priority_map[dep_type]
                                if "--debug" in myopts:
                                        print
                                        print "Parent:   ", pkg
                                        print "Depstring:", depstr
-                                       print "Priority:", priority
+                                       print "Priority:",
+                                       if priority == soft:
+                                               print "soft"
+                                       else:
+                                               print "hard"
 
                                try:
                                        portage_dep._dep_check_strict = False
@@ -8129,20 +6020,18 @@ def action_depclean(settings, trees, ldpath_mtimes,
                                        print "Candidates:", atoms
 
                                for atom in atoms:
-                                       if atom.startswith("!"):
-                                               continue
                                        remaining_atoms.append((atom, pkg, priority))
 
        if "--quiet" not in myopts:
                print "\b\b... done!\n"
 
-       if unresolveable and not allow_missing_deps:
+       if unresolveable:
                print "Dependencies could not be completely resolved due to"
                print "the following required packages not being installed:"
                print
                for atom in unresolveable:
                        print atom, "required by", " ".join(unresolveable[atom])
-       if unresolveable and not allow_missing_deps:
+       if unresolveable:
                print
                print "Have you forgotten to run " + good("`emerge --update --newuse --deep world`") + " prior to"
                print "%s?  It may be necessary to manually uninstall packages that no longer" % action
@@ -8174,10 +6063,11 @@ def action_depclean(settings, trees, ldpath_mtimes,
        if action == "depclean":
                if myfiles:
                        for pkg in vardb.cpv_all():
+                               metadata = dict(izip(metadata_keys,
+                                       vardb.aux_get(pkg, metadata_keys)))
                                arg_atom = None
                                try:
-                                       arg_atom = args_set.findAtomForPackage(
-                                               pkg_cache[("installed", myroot, pkg, "nomerge")])
+                                       arg_atom = args_set.findAtomForPackage(pkg, metadata)
                                except portage_exception.InvalidDependString:
                                        # this error has already been displayed by now
                                        continue
@@ -8217,84 +6107,8 @@ def action_depclean(settings, trees, ldpath_mtimes,
                                        good("--nodeps"))
 
        if len(cleanlist):
-               # Use a topological sort to create an unmerge order such that
-               # each package is unmerged before it's dependencies. This is
-               # necessary to avoid breaking things that may need to run
-               # during pkg_prerm or pkg_postrm phases.
-
-               # Create a new graph to account for dependencies between the
-               # packages being unmerged.
-               graph = digraph()
-               clean_set = set(cleanlist)
-               del cleanlist[:]
-               for node in clean_set:
-                       graph.add(node, None)
-                       myaux = izip(aux_keys, vardb.aux_get(node, aux_keys))
-                       mydeps = []
-                       usedef = vardb.aux_get(node, ["USE"])[0].split()
-                       for dep_type, depstr in myaux:
-                               if not depstr:
-                                       continue
-                               try:
-                                       portage_dep._dep_check_strict = False
-                                       success, atoms = portage.dep_check(depstr, None, settings,
-                                               myuse=usedef, trees=dep_check_trees, myroot=myroot)
-                               finally:
-                                       portage_dep._dep_check_strict = True
-                               if not success:
-                                       show_invalid_depstring_notice(
-                                               ("installed", myroot, node, "nomerge"),
-                                               depstr, atoms)
-                                       return
-
-                               priority = priority_map[dep_type]
-                               for atom in atoms:
-                                       if atom.startswith("!"):
-                                               continue
-                                       matches = vardb.match(atom)
-                                       if not matches:
-                                               continue
-                                       for cpv in matches:
-                                               if cpv in clean_set:
-                                                       graph.add(cpv, node, priority=priority)
-
-               ordered = True
-               if len(graph.order) == len(graph.root_nodes()):
-                       # If there are no dependencies between packages
-                       # let unmerge() group them by cat/pn.
-                       ordered = False
-                       cleanlist = graph.all_nodes()
-               else:
-                       # Order nodes from lowest to highest overall reference count for
-                       # optimal root node selection.
-                       node_refcounts = {}
-                       for node in graph.order:
-                               node_refcounts[node] = len(graph.parent_nodes(node))
-                       def cmp_reference_count(node1, node2):
-                               return node_refcounts[node1] - node_refcounts[node2]
-                       graph.order.sort(cmp_reference_count)
-       
-                       ignore_priority_range = [None]
-                       ignore_priority_range.extend(
-                               xrange(UnmergeDepPriority.MIN, UnmergeDepPriority.MAX + 1))
-                       while not graph.empty():
-                               for ignore_priority in ignore_priority_range:
-                                       nodes = graph.root_nodes(ignore_priority=ignore_priority)
-                                       if nodes:
-                                               break
-                               if not nodes:
-                                       raise AssertionError("no root nodes")
-                               if ignore_priority is not None:
-                                       # Some deps have been dropped due to circular dependencies,
-                                       # so only pop one node in order do minimize the number that
-                                       # are dropped.
-                                       del nodes[1:]
-                               for node in nodes:
-                                       graph.remove(node)
-                                       cleanlist.append(node)
-
                unmerge(settings, myopts, trees[settings["ROOT"]]["vartree"],
-                       "unmerge", cleanlist, ldpath_mtimes, ordered=ordered)
+                       "unmerge", cleanlist, ldpath_mtimes)
 
        if action == "prune":
                return
@@ -8314,86 +6128,14 @@ def action_depclean(settings, trees, ldpath_mtimes,
 
 def action_build(settings, trees, mtimedb,
        myopts, myaction, myfiles, spinner):
-
-       # validate the state of the resume data
-       # so that we can make assumptions later.
-       for k in ("resume", "resume_backup"):
-               if k not in mtimedb:
-                       continue
-               resume_data = mtimedb[k]
-               if not isinstance(resume_data, dict):
-                       del mtimedb[k]
-                       continue
-               mergelist = resume_data.get("mergelist")
-               if not isinstance(mergelist, list):
-                       del mtimedb[k]
-                       continue
-               resume_opts = resume_data.get("myopts")
-               if not isinstance(resume_opts, (dict, list)):
-                       del mtimedb[k]
-                       continue
-               favorites = resume_data.get("favorites")
-               if not isinstance(favorites, list):
-                       del mtimedb[k]
-                       continue
-
-       resume = False
-       if "--resume" in myopts and \
-               ("resume" in mtimedb or
-               "resume_backup" in mtimedb):
-               resume = True
-               if "resume" not in mtimedb:
-                       mtimedb["resume"] = mtimedb["resume_backup"]
-                       del mtimedb["resume_backup"]
-                       mtimedb.commit()
-               # "myopts" is a list for backward compatibility.
-               resume_opts = mtimedb["resume"].get("myopts", [])
-               if isinstance(resume_opts, list):
-                       resume_opts = dict((k,True) for k in resume_opts)
-               for opt in ("--skipfirst", "--ask", "--tree"):
-                       resume_opts.pop(opt, None)
-               myopts.update(resume_opts)
-               # Adjust config according to options of the command being resumed.
-               for myroot in trees:
-                       mysettings =  trees[myroot]["vartree"].settings
-                       mysettings.unlock()
-                       adjust_config(myopts, mysettings)
-                       mysettings.lock()
-                       del myroot, mysettings
-
        ldpath_mtimes = mtimedb["ldpath"]
        favorites=[]
        merge_count = 0
-       buildpkgonly = "--buildpkgonly" in myopts
        pretend = "--pretend" in myopts
        fetchonly = "--fetchonly" in myopts or "--fetch-all-uri" in myopts
-       ask = "--ask" in myopts
-       nodeps = "--nodeps" in myopts
-       oneshot = "--oneshot" in myopts or "--onlydeps" in myopts
-       tree = "--tree" in myopts
-       if nodeps and tree:
-               tree = False
-               del myopts["--tree"]
-               portage.writemsg(colorize("WARN", " * ") + \
-                       "--tree is broken with --nodeps. Disabling...\n")
-       debug = "--debug" in myopts
-       verbose = "--verbose" in myopts
-       quiet = "--quiet" in myopts
        if pretend or fetchonly:
                # make the mtimedb readonly
                mtimedb.filename = None
-       if "--digest" in myopts:
-               msg = "The --digest option can prevent corruption from being" + \
-                       " noticed. The `repoman manifest` command is the preferred" + \
-                       " way to generate manifests and it is capable of doing an" + \
-                       " entire repository or category at once."
-               prefix = bad(" * ")
-               writemsg(prefix + "\n")
-               from textwrap import wrap
-               for line in wrap(msg, 72):
-                       writemsg("%s%s\n" % (prefix, line))
-               writemsg(prefix + "\n")
-
        if "--quiet" not in myopts and \
                ("--pretend" in myopts or "--ask" in myopts or \
                "--tree" in myopts or "--verbose" in myopts):
@@ -8413,200 +6155,104 @@ def action_build(settings, trees, mtimedb,
                        print darkgreen("These are the packages that would be %s, in order:") % action
                        print
 
-       show_spinner = "--quiet" not in myopts and "--nodeps" not in myopts
-       if not show_spinner:
-               spinner.update = spinner.update_quiet
+       # validate the state of the resume data
+       # so that we can make assumptions later.
+       for k in ("resume", "resume_backup"):
+               if k in mtimedb:
+                       if "mergelist" in mtimedb[k]:
+                               if not mtimedb[k]["mergelist"]:
+                                       del mtimedb[k]
+                       else:
+                               del mtimedb[k]
+
+       if "--resume" in myopts and \
+               ("resume" in mtimedb or
+               "resume_backup" in mtimedb):
+               if "resume" not in mtimedb:
+                       mtimedb["resume"] = mtimedb["resume_backup"]
+                       del mtimedb["resume_backup"]
+                       mtimedb.commit()
 
-       if resume:
-               favorites = mtimedb["resume"].get("favorites")
-               if not isinstance(favorites, list):
-                       favorites = []
+               # Adjust config according to options of the command being resumed.
+               for myroot in trees:
+                       mysettings =  trees[myroot]["vartree"].settings
+                       mysettings.unlock()
+                       adjust_config(myopts, mysettings)
+                       mysettings.lock()
+                       del myroot, mysettings
 
+               # "myopts" is a list for backward compatibility.
+               resume_opts = mtimedb["resume"].get("myopts", [])
+               if isinstance(resume_opts, list):
+                       resume_opts = dict((k,True) for k in resume_opts)
+               for opt in ("--skipfirst", "--ask", "--tree"):
+                       resume_opts.pop(opt, None)
+               myopts.update(resume_opts)
+               show_spinner = "--quiet" not in myopts and "--nodeps" not in myopts
+               if not show_spinner:
+                       spinner.update = spinner.update_quiet
                if show_spinner:
                        print "Calculating dependencies  ",
                myparams = create_depgraph_params(myopts, myaction)
-
-               resume_data = mtimedb["resume"]
-               mergelist = resume_data["mergelist"]
-               if mergelist and "--skipfirst" in myopts:
-                       for i, task in enumerate(mergelist):
-                               if isinstance(task, list) and \
-                                       task and task[-1] == "merge":
-                                       del mergelist[i]
-                                       break
-
-               dropped_tasks = set()
-
-               success = False
+               mydepgraph = depgraph(settings, trees,
+                       myopts, myparams, spinner)
                try:
-                       while True:
-                               mydepgraph = depgraph(settings, trees,
-                                       myopts, myparams, spinner)
-                               try:
-                                       success = mydepgraph.loadResumeCommand(mtimedb["resume"])
-                               except depgraph.UnsatisfiedResumeDep, e:
-                                       if "--skipfirst" not in myopts:
-                                               raise
-
-                                       graph = mydepgraph.digraph
-                                       unsatisfied_parents = dict((dep.parent, dep.parent) \
-                                               for dep in e.value)
-                                       traversed_nodes = set()
-                                       unsatisfied_stack = list(unsatisfied_parents)
-                                       while unsatisfied_stack:
-                                               pkg = unsatisfied_stack.pop()
-                                               if pkg in traversed_nodes:
-                                                       continue
-                                               traversed_nodes.add(pkg)
-
-                                               # If this package was pulled in by a parent
-                                               # package scheduled for merge, removing this
-                                               # package may cause the the parent package's
-                                               # dependency to become unsatisfied.
-                                               for parent_node in graph.parent_nodes(pkg):
-                                                       if not isinstance(parent_node, Package) \
-                                                               or parent_node.operation != "merge":
-                                                               continue
-                                                       unsatisfied = \
-                                                               graph.child_nodes(parent_node,
-                                                               ignore_priority=DepPriority.SOFT)
-                                                       if pkg in unsatisfied:
-                                                               unsatisfied_parents[parent_node] = parent_node
-                                                               unsatisfied_stack.append(parent_node)
-
-                                       pruned_mergelist = [x for x in mergelist \
-                                               if isinstance(x, list) and \
-                                               tuple(x) not in unsatisfied_parents]
-
-                                       # It shouldn't happen, but if the size of mergelist
-                                       # does not decrease for some reason then the loop
-                                       # will be infinite. Therefore, if that case ever
-                                       # occurs for some reason, raise the exception to
-                                       # break out of the loop.
-                                       if not pruned_mergelist or \
-                                               len(pruned_mergelist) == len(mergelist):
-                                               raise
-                                       mergelist[:] = pruned_mergelist
-                                       dropped_tasks.update(unsatisfied_parents)
-                                       del e, graph, traversed_nodes, \
-                                               unsatisfied_parents, unsatisfied_stack
-                                       continue
-                               else:
-                                       break
-               except (portage_exception.PackageNotFound,
-                       depgraph.UnsatisfiedResumeDep), e:
+                       mydepgraph.loadResumeCommand(mtimedb["resume"])
+               except portage_exception.PackageNotFound:
                        if show_spinner:
                                print
-                       from textwrap import wrap
                        from output import EOutput
                        out = EOutput()
-
-                       resume_data = mtimedb["resume"]
-                       mergelist = resume_data.get("mergelist")
-                       if not isinstance(mergelist, list):
-                               mergelist = []
-                       if mergelist and debug or (verbose and not quiet):
-                               out.eerror("Invalid resume list:")
-                               out.eerror("")
-                               indent = "  "
-                               for task in mergelist:
-                                       if isinstance(task, list):
-                                               out.eerror(indent + str(tuple(task)))
-                               out.eerror("")
-
-                       if isinstance(e, depgraph.UnsatisfiedResumeDep):
-                               out.eerror("One or packages are either masked or " + \
-                                       "have missing dependencies:")
-                               out.eerror("")
-                               indent = "  "
-                               for dep in e.value:
-                                       if dep.atom is None:
-                                               out.eerror(indent + "Masked package:")
-                                               out.eerror(2 * indent + str(dep.parent))
-                                               out.eerror("")
-                                       else:
-                                               out.eerror(indent + str(dep.atom) + " pulled in by:")
-                                               out.eerror(2 * indent + str(dep.parent))
-                                               out.eerror("")
-                               msg = "The resume list contains packages " + \
-                                       "that are either masked or have " + \
-                                       "unsatisfied dependencies. " + \
-                                       "Please restart/continue " + \
-                                       "the operation manually, or use --skipfirst " + \
-                                       "to skip the first package in the list and " + \
-                                       "any other packages that may be " + \
-                                       "masked or have missing dependencies."
-                               for line in wrap(msg, 72):
-                                       out.eerror(line)
-                       elif isinstance(e, portage_exception.PackageNotFound):
-                               out.eerror("An expected package is " + \
-                                       "not available: %s" % str(e))
-                               out.eerror("")
-                               msg = "The resume list contains one or more " + \
-                                       "packages that are no longer " + \
-                                       "available. Please restart/continue " + \
-                                       "the operation manually."
-                               for line in wrap(msg, 72):
-                                       out.eerror(line)
-               else:
-                       if show_spinner:
-                               print "\b\b... done!"
-
-               if success:
-                       if dropped_tasks:
-                               portage.writemsg("!!! One or more packages have been " + \
-                                       "dropped due to\n" + \
-                                       "!!! masking or unsatisfied dependencies:\n\n",
-                                       noiselevel=-1)
-                               for task in dropped_tasks:
-                                       portage.writemsg("  " + str(task) + "\n", noiselevel=-1)
-                               portage.writemsg("\n", noiselevel=-1)
-                       del dropped_tasks
-               else:
-                       mydepgraph.display_problems()
-                       if not (ask or pretend):
-                               # delete the current list and also the backup
-                               # since it's probably stale too.
-                               for k in ("resume", "resume_backup"):
-                                       mtimedb.pop(k, None)
-                               mtimedb.commit()
-
+                       out.eerror("Error: The resume list contains packages that are no longer")
+                       out.eerror("       available to be emerged. Please restart/continue")
+                       out.eerror("       the merge operation manually.")
                        return 1
+               if show_spinner:
+                       print "\b\b... done!"
        else:
                if ("--resume" in myopts):
                        print darkgreen("emerge: It seems we have nothing to resume...")
                        return os.EX_OK
 
                myparams = create_depgraph_params(myopts, myaction)
-               if "--quiet" not in myopts and "--nodeps" not in myopts:
-                       print "Calculating dependencies  ",
-                       sys.stdout.flush()
-               mydepgraph = depgraph(settings, trees, myopts, myparams, spinner)
-               try:
-                       retval, favorites = mydepgraph.select_files(myfiles)
-               except portage_exception.PackageNotFound, e:
-                       portage.writemsg("\n!!! %s\n" % str(e), noiselevel=-1)
-                       return 1
-               if show_spinner:
-                       print "\b\b... done!"
-               if not retval:
-                       mydepgraph.display_problems()
-                       return 1
+               if myaction in ["system","world"]:
+                       if "--quiet" not in myopts and "--nodeps" not in myopts:
+                               print "Calculating",myaction,"dependencies  ",
+                               sys.stdout.flush()
+                       mydepgraph = depgraph(settings, trees, myopts, myparams, spinner)
+                       if not mydepgraph.xcreate(myaction):
+                               print "!!! Depgraph creation failed."
+                               return 1
+                       if "--quiet" not in myopts and "--nodeps" not in myopts:
+                               print "\b\b... done!"
+               else:
+                       if "--quiet" not in myopts and "--nodeps" not in myopts:
+                               print "Calculating dependencies  ",
+                               sys.stdout.flush()
+                       mydepgraph = depgraph(settings, trees, myopts, myparams, spinner)
+                       try:
+                               retval, favorites = mydepgraph.select_files(myfiles)
+                       except portage_exception.PackageNotFound, e:
+                               portage.writemsg("\n!!! %s\n" % str(e), noiselevel=-1)
+                               return 1
+                       if not retval:
+                               return 1
+                       if "--quiet" not in myopts and "--nodeps" not in myopts:
+                               print "\b\b... done!"
 
        if "--pretend" not in myopts and \
                ("--ask" in myopts or "--tree" in myopts or \
                "--verbose" in myopts) and \
                not ("--quiet" in myopts and "--ask" not in myopts):
                if "--resume" in myopts:
-                       mymergelist = mydepgraph.altlist()
+                       mymergelist = mtimedb["resume"]["mergelist"]
+                       if "--skipfirst" in myopts:
+                               mymergelist = mymergelist[1:]
                        if len(mymergelist) == 0:
                                print colorize("INFORM", "emerge: It seems we have nothing to resume...")
                                return os.EX_OK
                        favorites = mtimedb["resume"]["favorites"]
-                       retval = mydepgraph.display(
-                               mydepgraph.altlist(reversed=tree),
-                               favorites=favorites)
-                       mydepgraph.display_problems()
+                       retval = mydepgraph.display(mymergelist, favorites=favorites)
                        if retval != os.EX_OK:
                                return retval
                        prompt="Would you like to resume merging these packages?"
@@ -8614,16 +6260,21 @@ def action_build(settings, trees, mtimedb,
                        retval = mydepgraph.display(
                                mydepgraph.altlist(reversed=("--tree" in myopts)),
                                favorites=favorites)
-                       mydepgraph.display_problems()
                        if retval != os.EX_OK:
                                return retval
                        mergecount=0
                        for x in mydepgraph.altlist():
-                               if isinstance(x, Package) and x.operation == "merge":
-                                       mergecount += 1
-
+                               if x[0] != "blocks" and x[3] != "nomerge":
+                                       mergecount+=1
+                               #check for blocking dependencies
+                               if x[0]=="blocks" and "--fetchonly" not in myopts and "--fetch-all-uri" not in myopts:
+                                       print "\n!!! Error: The above package list contains packages which cannot be installed"
+                                       print   "!!!        at the same time on the same system."
+                                       if "--quiet" not in myopts:
+                                               show_blocker_docs_link()
+                                       return 1
                        if mergecount==0:
-                               if "--noreplace" in myopts and not oneshot and favorites:
+                               if "--noreplace" in myopts and favorites:
                                        print
                                        for x in favorites:
                                                print " %s %s" % (good("*"), x)
@@ -8650,40 +6301,30 @@ def action_build(settings, trees, mtimedb,
 
        if ("--pretend" in myopts) and not ("--fetchonly" in myopts or "--fetch-all-uri" in myopts):
                if ("--resume" in myopts):
-                       mymergelist = mydepgraph.altlist()
+                       mymergelist = mtimedb["resume"]["mergelist"]
+                       if "--skipfirst" in myopts:
+                               mymergelist = mymergelist[1:]
                        if len(mymergelist) == 0:
                                print colorize("INFORM", "emerge: It seems we have nothing to resume...")
                                return os.EX_OK
                        favorites = mtimedb["resume"]["favorites"]
-                       retval = mydepgraph.display(
-                               mydepgraph.altlist(reversed=tree),
-                               favorites=favorites)
-                       mydepgraph.display_problems()
+                       retval = mydepgraph.display(mymergelist, favorites=favorites)
                        if retval != os.EX_OK:
                                return retval
                else:
                        retval = mydepgraph.display(
                                mydepgraph.altlist(reversed=("--tree" in myopts)),
                                favorites=favorites)
-                       mydepgraph.display_problems()
                        if retval != os.EX_OK:
                                return retval
-                       if "--buildpkgonly" in myopts:
-                               graph_copy = mydepgraph.digraph.clone()
-                               for node in list(graph_copy.order):
-                                       if not isinstance(node, Package):
-                                               graph_copy.remove(node)
-                               if not graph_copy.hasallzeros(ignore_priority=DepPriority.MEDIUM):
+                       if "--buildpkgonly" in myopts and \
+                               not mydepgraph.digraph.hasallzeros(ignore_priority=DepPriority.MEDIUM):
                                        print "\n!!! --buildpkgonly requires all dependencies to be merged."
                                        print "!!! You have to merge the dependencies before you can build this package.\n"
                                        return 1
        else:
-               if "--buildpkgonly" in myopts:
-                       graph_copy = mydepgraph.digraph.clone()
-                       for node in list(graph_copy.order):
-                               if not isinstance(node, Package):
-                                       graph_copy.remove(node)
-                       if not graph_copy.hasallzeros(ignore_priority=DepPriority.MEDIUM):
+               if ("--buildpkgonly" in myopts):
+                       if not mydepgraph.digraph.hasallzeros(ignore_priority=DepPriority.MEDIUM):
                                print "\n!!! --buildpkgonly requires all dependencies to be merged."
                                print "!!! Cannot merge requested packages. Merge deps and try again.\n"
                                return 1
@@ -8691,17 +6332,14 @@ def action_build(settings, trees, mtimedb,
                if ("--resume" in myopts):
                        favorites=mtimedb["resume"]["favorites"]
                        mergetask = MergeTask(settings, trees, myopts)
-                       if "PORTAGE_PARALLEL_FETCHONLY" in settings:
+                       if "--fetchonly" in myopts:
                                """ parallel-fetch uses --resume --fetchonly and we don't want
                                it to write the mtimedb"""
                                mtimedb.filename = None
                                time.sleep(3) # allow the parent to have first fetch
-                       mymergelist = mydepgraph.altlist()
-                       mydepgraph.break_refs(mymergelist)
                        del mydepgraph
-                       clear_caches(trees)
-
-                       retval = mergetask.merge(mymergelist, favorites, mtimedb)
+                       retval = mergetask.merge(
+                               mtimedb["resume"]["mergelist"], favorites, mtimedb)
                        merge_count = mergetask.curval
                else:
                        if "resume" in mtimedb and \
@@ -8714,17 +6352,7 @@ def action_build(settings, trees, mtimedb,
                        # XXX: Stored as a list for backward compatibility.
                        mtimedb["resume"]["myopts"] = \
                                [k for k in myopts if myopts[k] is True]
-
-                       # Convert Atom instances to plain str since the mtimedb loader
-                       # sets unpickler.find_global = None which causes unpickler.load()
-                       # to raise the following exception:
-                       #
-                       # cPickle.UnpicklingError: Global and instance pickles are not supported.
-                       #
-                       # TODO: Maybe stop setting find_global = None, or find some other
-                       # way to avoid accidental triggering of the above UnpicklingError.
-                       mtimedb["resume"]["favorites"] = [str(x) for x in favorites]
-
+                       mtimedb["resume"]["favorites"]=favorites
                        if ("--digest" in myopts) and not ("--fetchonly" in myopts or "--fetch-all-uri" in myopts):
                                for pkgline in mydepgraph.altlist():
                                        if pkgline[0]=="ebuild" and pkgline[3]=="merge":
@@ -8740,16 +6368,37 @@ def action_build(settings, trees, mtimedb,
                                                        tree="porttree")
 
                        pkglist = mydepgraph.altlist()
-                       mydepgraph.saveNomergeFavorites()
-                       mydepgraph.break_refs(pkglist)
-                       del mydepgraph
-                       clear_caches(trees)
 
+                       if fetchonly or "--buildpkgonly"  in myopts:
+                               pkglist = [pkg for pkg in pkglist if pkg[0] != "blocks"]
+                       else:
+                               for x in pkglist:
+                                       if x[0] != "blocks":
+                                               continue
+                                       retval = mydepgraph.display(mydepgraph.altlist(
+                                               reversed=("--tree" in myopts)),
+                                               favorites=favorites)
+                                       msg = "Error: The above package list contains " + \
+                                               "packages which cannot be installed " + \
+                                               "at the same time on the same system."
+                                       prefix = bad(" * ")
+                                       from textwrap import wrap
+                                       print
+                                       for line in wrap(msg, 70):
+                                               print prefix + line
+                                       if "--quiet" not in myopts:
+                                               show_blocker_docs_link()
+                                       return 1
+
+                       if favorites:
+                               mydepgraph.saveNomergeFavorites()
+                       del mydepgraph
                        mergetask = MergeTask(settings, trees, myopts)
                        retval = mergetask.merge(pkglist, favorites, mtimedb)
                        merge_count = mergetask.curval
 
-               if retval == os.EX_OK and not (buildpkgonly or fetchonly or pretend):
+               if retval == os.EX_OK and not (pretend or fetchonly):
+                       mtimedb.pop("resume", None)
                        if "yes" == settings.get("AUTOCLEAN"):
                                portage.writemsg_stdout(">>> Auto-cleaning packages...\n")
                                vartree = trees[settings["ROOT"]]["vartree"]
@@ -8760,7 +6409,7 @@ def action_build(settings, trees, mtimedb,
                                        + " AUTOCLEAN is disabled.  This can cause serious"
                                        + " problems due to overlapping packages.\n")
 
-               if merge_count and not (buildpkgonly or fetchonly or pretend):
+               if merge_count and not (pretend or fetchonly):
                        post_emerge(settings, mtimedb, retval)
                return retval
 
@@ -8867,27 +6516,12 @@ def validate_ebuild_environment(trees):
                settings = trees[myroot]["vartree"].settings
                settings.validate()
 
-def clear_caches(trees):
-       for d in trees.itervalues():
-               d["porttree"].dbapi.melt()
-               d["porttree"].dbapi._aux_cache.clear()
-               d["bintree"].dbapi._aux_cache.clear()
-               d["bintree"].dbapi._clear_cache()
-       gc.collect()
-
 def load_emerge_config(trees=None):
        kwargs = {}
        for k, envvar in (("config_root", "PORTAGE_CONFIGROOT"), ("target_root", "ROOT")):
-               v = os.environ.get(envvar, None)
-               if v and v.strip():
-                       kwargs[k] = v
+               kwargs[k] = os.environ.get(envvar, None)
        trees = portage.create_trees(trees=trees, **kwargs)
 
-       for root, root_trees in trees.iteritems():
-               settings = root_trees["vartree"].settings
-               setconfig = SetConfig(settings, root_trees)
-               root_trees["root_config"] = RootConfig(settings, root_trees, setconfig)
-
        settings = trees["/"]["vartree"].settings
 
        for myroot in trees:
@@ -9072,8 +6706,7 @@ def emerge_main():
                msg = "It is best to avoid overridding eclasses from PORTDIR " + \
                "because it will trigger invalidation of cached ebuild metadata " + \
                "that is distributed with the portage tree. If you must " + \
-               "override eclasses from PORTDIR then you are advised to add " + \
-               "FEATURES=\"metadata-transfer\" to /etc/make.conf and to run " + \
+               "override eclasses from PORTDIR then you are advised to run " + \
                "`emerge --regen` after each time that you run `emerge --sync`. " + \
                "Set PORTAGE_ECLASS_WARNING_ENABLE=\"0\" in /etc/make.conf if " + \
                "you would like to disable this warning."
@@ -9097,12 +6730,9 @@ def emerge_main():
 
 """
 
-       if myaction in ("world", "system"):
-               if myfiles:
-                       print "emerge: please specify a package class (\"world\" " + \
-                               "or \"system\") or individual packages, but not both."
-                       return 1
-               myfiles.append(myaction)
+       if (myaction in ["world", "system"]) and myfiles:
+               print "emerge: please specify a package class (\"world\" or \"system\") or individual packages, but not both."
+               sys.exit(1)
 
        for x in myfiles:
                ext = os.path.splitext(x)[1]
@@ -9183,6 +6813,11 @@ def emerge_main():
                        import portage_debug
                        portage_debug.set_trace(True)
 
+       if ("--resume" in myopts):
+               if "--tree" in myopts:
+                       print "* --tree is currently broken with --resume. Disabling..."
+                       del myopts["--tree"]
+
        if not ("--quiet" in myopts):
                if not sys.stdout.isatty() or ("--nospinner" in myopts):
                        spinner.update = spinner.update_basic
@@ -9208,17 +6843,13 @@ def emerge_main():
                emergehelp.help(myaction, myopts, output.havecolor)
                sys.exit(1)
 
-       pretend = "--pretend" in myopts
-       fetchonly = "--fetchonly" in myopts or "--fetch-all-uri" in myopts
-       buildpkgonly = "--buildpkgonly" in myopts
-
        # check if root user is the current user for the actions where emerge needs this
        if portage.secpass < 2:
                # We've already allowed "--version" and "--help" above.
                if "--pretend" not in myopts and myaction not in ("search","info"):
                        need_superuser = not \
-                               (fetchonly or \
-                               (buildpkgonly and secpass >= 1) or \
+                               ("--fetchonly" in myopts or \
+                               "--fetch-all-uri" in myopts or \
                                myaction in ("metadata", "regen") or \
                                (myaction == "sync" and os.access(settings["PORTDIR"], os.W_OK)))
                        if portage.secpass < 1 or \
@@ -9266,9 +6897,7 @@ def emerge_main():
                myelogstr=""
                if myopts:
                        myelogstr=" ".join(myopts)
-               if myaction and myaction not in ("system", "world"):
-                       # Exclude "world" and "system" here because myfiles
-                       # contains a duplicate.
+               if myaction:
                        myelogstr+=" "+myaction
                if myfiles:
                        myelogstr+=" "+" ".join(myfiles)
@@ -9314,25 +6943,22 @@ def emerge_main():
        # SEARCH action
        elif "search"==myaction:
                validate_ebuild_environment(trees)
-               action_search(trees[settings["ROOT"]]["root_config"],
+               action_search(settings, trees[settings["ROOT"]],
                        myopts, myfiles, spinner)
        elif myaction in ("clean", "unmerge") or \
                (myaction == "prune" and "--nodeps" in myopts):
                validate_ebuild_environment(trees)
                vartree = trees[settings["ROOT"]]["vartree"]
-               # When given a list of atoms, unmerge
-               # them in the order given.
-               ordered = myaction == "unmerge"
                if 1 == unmerge(settings, myopts, vartree, myaction, myfiles,
-                       mtimedb["ldpath"], ordered=ordered):
-                       if not (buildpkgonly or fetchonly or pretend):
+                       mtimedb["ldpath"]):
+                       if "--pretend" not in myopts:
                                post_emerge(settings, mtimedb, 0)
 
        elif myaction in ("depclean", "prune"):
                validate_ebuild_environment(trees)
                action_depclean(settings, trees, mtimedb["ldpath"],
                        myopts, myaction, myfiles, spinner)
-               if not (buildpkgonly or fetchonly or pretend):
+               if "--pretend" not in myopts:
                        post_emerge(settings, mtimedb, 0)
        # "update", "system", or just process files:
        else: