--- /usr/lib/portage/bin/emerge.orig	2006-04-28 22:03:18.000000000 -0700
+++ /usr/lib/portage/bin/emerge	2006-04-29 17:06:22.000000000 -0700
@@ -22,26 +22,6 @@
 import portage_exception
 
 
-spinner_msgs = ["Gentoo Rocks ("+os.uname()[0]+")",
-                "Thank you for using Gentoo. :)",
-                "Are you actually trying to read this?",
-                "How many times have you stared at this?",
-                "We are generating the cache right now",
-                "You are paying too much attention.",
-                "A theory is better than its explanation.",
-                "Phasers locked on target, Captain.",
-                "Thrashing is just virtual crashing.",
-                "To be is to program.",
-                "Real Users hate Real Programmers.",
-                "When all else fails, read the instructions.",
-                "Functionality breeds Contempt.",
-                "The future lies ahead.",
-                "3.1415926535897932384626433832795028841971694",
-                "Sometimes insanity is the only alternative.",
-                "Inaccuracy saves a world of explanation.",
-               ]
-
-
 def update_basic_spinner():
 	global spinner, spinpos
 	spinpos = (spinpos+1) % 500
@@ -70,18 +50,6 @@
 def update_quiet_spinner():
 	return
 
-spinpos = 0
-spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
-update_spinner = update_twirl_spinner
-if "candy" in portage.settings.features:
-	spinner = spinner_msgs[int(time.time()*100)%len(spinner_msgs)]
-	update_spinner = update_scroll_spinner
-
-if (not sys.stdout.isatty()) or (portage.settings["NOCOLOR"] in ["yes","true"]):
-	nocolor()
-
-
-
 def normpath(mystr):
 	""" 
 		os.path.normpath("//foo") returns "//foo" instead of "/foo"
@@ -152,283 +120,6 @@
 		ret.insert(x, ver)
 	return ret
 
-if portage.settings.has_key("PORTAGE_NICENESS"):
-	try:
-		os.nice(int(portage.settings["PORTAGE_NICENESS"]))
-	except (OSError,ValueError), e:
-		print "!!! Failed to change nice value to '"+str(portage.settings["PORTAGE_NICENESS"])+"'"
-		print "!!!",e
-
-#Freeze the portdbapi for enhanced performance:
-portage.portdb.freeze()
-
-# Kill noauto as it will break merges otherwise.
-while 'noauto' in portage.features:
-	del portage.features[portage.features.index('noauto')]
-
-#number of ebuilds merged
-merged=0
-params=["selective", "deep", "self", "recurse", "empty"]
-actions=[
-"clean", "config", "depclean",
-"info", "metadata",
-"prune", "regen",  "search",
-"sync",  "system", "unmerge",  "world",
-]
-options=[
-"--ask",          "--alphabetical",
-"--buildpkg",     "--buildpkgonly",
-"--changelog",    "--columns", "--cols",
-"--debug",        "--deep",
-"--digest",
-"--emptytree",
-"--fetchonly",    "--fetch-all-uri",
-"--getbinpkg",    "--getbinpkgonly",
-"--help",         "--ignore-default-opts",
-"--noconfmem",
-"--newuse",       "--nocolor",
-"--nodeps",       "--noreplace",
-"--nospinner",    "--oneshot",
-"--onlydeps",     "--pretend",
-"--quiet",        "--resume",
-"--searchdesc",   "--selective",
-"--skipfirst",    "--skip-first",
-"--tree",
-"--update",       
-"--usepkg",       "--usepkgonly",
-"--verbose",      "--version"
-]
-
-shortmapping={
-"1":"--oneshot",
-"a":"--ask",
-"b":"--buildpkg",  "B":"--buildpkgonly",
-"c":"--clean",     "C":"--unmerge",
-"d":"--debug",     "D":"--deep",
-"e":"--emptytree",
-"f":"--fetchonly", "F":"--fetch-all-uri",
-"g":"--getbinpkg", "G":"--getbinpkgonly",
-"h":"--help",
-"k":"--usepkg",    "K":"--usepkgonly",
-"l":"--changelog",
-"n":"--noreplace", "N":"--newuse",
-"o":"--onlydeps",  "O":"--nodeps",
-"p":"--pretend",   "P":"--prune",
-"q":"--quiet",
-"s":"--search",    "S":"--searchdesc",
-'t':"--tree",
-"u":"--update",
-"v":"--verbose",   "V":"--version"
-}
-
-myaction=None
-myopts=[]
-myfiles=[]
-edebug=0
-
-# process short actions
-tmpcmdline=sys.argv[1:]
-if "--ignore-default-opts" not in tmpcmdline:
-	tmpcmdline.extend(portage.settings["EMERGE_DEFAULT_OPTS"].split())
-cmdline=[]
-for x in tmpcmdline:
-	if x[0:1]=="-" and x[1:2]!="-":
-		for y in x[1:]:
-			if shortmapping.has_key(y):
-				if shortmapping[y] in cmdline:
-					print
-					print "*** Warning: Redundant use of",shortmapping[y]
-				else:
-					cmdline.append(shortmapping[y])
-			else:
-				print "!!! Error: -"+y+" is an invalid short action or option."
-				sys.exit(1)
-	else:
-		cmdline.append(x)
-
-# process the options and command arguments
-for x in cmdline:
-	if not x:
-		continue
-	if len(x)>=2 and x[0:2]=="--":
-		if x == "--cols":
-			x = "--columns"
-		elif x == "--skip-first":
-			x = "--skipfirst"
-		if x in options:
-			if x not in myopts:
-				myopts.append(x)
-		elif x[2:] in actions:
-			if myaction:
-				if myaction not in ["system", "world"]:
-					myaction="--"+myaction
-				print
-				print red("!!!")+green(" Multiple actions requested... Please choose one only.")
-				print red("!!!")+" '"+darkgreen(myaction)+"' "+red("or")+" '"+darkgreen(x)+"'"
-				print
-				sys.exit(1)
-			myaction=x[2:]
-		else:
-			print "!!! Error:",x,"is an invalid option."
-			sys.exit(1)
-	elif (not myaction) and (x in actions):
-		if x not in ["system", "world"]:
-			print red("*** Deprecated use of action '%s', use '--%s' instead" % (x,x))
-		if myaction:
-			print
-			print red("!!!")+green(" Multiple actions requested... Please choose one only.")
-			print red("!!! '")+darkgreen(myaction)+"' "+red("or")+" '"+darkgreen(x)+"'"
-			print
-			sys.exit(1)
-		myaction=x
-	elif x[-1]=="/":
-		# this little conditional helps tab completion
-		myfiles.append(x[:-1])
-	else:
-		myfiles.append(x)
-
-
-if "moo" in myfiles:
-	print """
-
-  Larry loves Gentoo (""" + os.uname()[0] + """)
-
- _______________________
-< Have you mooed today? >
- -----------------------
-        \   ^__^
-         \  (oo)\_______
-            (__)\       )\/\ 
-                ||----w |
-                ||     ||
-
-"""
-
-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]
-	if (ext == ".ebuild" or ext == ".tbz2") and os.path.exists(os.path.abspath(x)):
-		print "emerging by path implies --oneshot... adding --oneshot to options."
-		print red("\n*** emerging by path is broken and may not always work!!!\n")
-		break
-
-if ("--tree" in myopts) and ("--columns" in myopts):
-	print "emerge: can't specify both of \"--tree\" and \"--columns\"."
-	sys.exit(1)
-
-if ("--quiet" in myopts):
-	update_spinner = update_quiet_spinner
-	portage_util.noiselimit = -1
-	portage.settings.unlock()
-	portage.settings["PORTAGE_QUIET"]="1"
-	portage.settings.backup_changes("PORTAGE_QUIET")
-	portage.settings.lock()
-
-# Always create packages if FEATURES=buildpkg
-# Imply --buildpkg if --buildpkgonly
-if ("buildpkg" in portage.features) or ("--buildpkgonly" in myopts):
-	if "--buildpkg" not in myopts:
-		myopts.append("--buildpkg")
-
-# --tree only makes sense with --pretend
-if "--tree" in myopts and not (("--pretend" in myopts) or ("--ask" in myopts)):
-	print ">>> --tree implies --pretend... adding --pretend to options."
-	myopts.append("--pretend")
-
-# Also allow -S to invoke search action (-sS)
-if ("--searchdesc" in myopts):
-	if myaction and myaction != "search":
-		myfiles.append(myaction)
-	if "--search" not in myopts:
-		myopts.append("--search")
-	myaction = "search"
-
-# Always try and fetch binary packages if FEATURES=getbinpkg
-if ("getbinpkg" in portage.features):
-	myopts.append("--getbinpkg")
-
-if "--skipfirst" in myopts and "--resume" not in myopts:
-	myopts.append("--resume")
-
-if ("--getbinpkgonly" in myopts) and not ("--usepkgonly" in myopts):
-	myopts.append("--usepkgonly")
-
-if ("--getbinpkgonly" in myopts) and not ("--getbinpkg" in myopts):
-	myopts.append("--getbinpkg")
-
-if ("--getbinpkg" in myopts) and not ("--usepkg" in myopts):
-	myopts.append("--usepkg")
-
-# Also allow -K to apply --usepkg/-k
-if ("--usepkgonly" in myopts) and not ("--usepkg" in myopts):
-	myopts.append("--usepkg")
-
-if ("--newuse" in myopts) and not ("--update" in myopts):
-	print ">>> --newuse implies --update... adding --update to options."
-	myopts.append("--update")
-
-# Also allow -l to apply --pretend/-p, but if already in --ask mode
-if ("--changelog" in myopts) and not (("--pretend" in myopts) or ("--ask" in myopts)):
-	print ">>> --changelog implies --pretend... adding --pretend to options."
-	myopts.append("--pretend")
-
-# Allow -p to remove --ask
-if ("--pretend" in myopts) and ("--ask" in myopts):
-	print ">>> --pretend disables --ask... removing --ask from options."
-	myopts.remove("--ask")
-
-# forbid --ask when not in a terminal
-# note: this breaks `emerge --ask | tee logfile`, but that doesn't work anyway.
-if ("--ask" in myopts) and (not sys.stdin.isatty()):
-	portage.writemsg("!!! \"--ask\" should only be used in a terminal. Exiting.\n")
-	sys.exit(1)
-
-# Set so that configs will be merged regardless of remembered status
-if ("--noconfmem" in myopts):
-	portage.settings.unlock()
-	portage.settings["NOCONFMEM"]="1"
-	portage.settings.backup_changes("NOCONFMEM")
-	portage.settings.lock()
-
-# Set various debug markers... They should be merged somehow.
-if ("--debug" in myopts):
-	portage.settings.unlock()
-	portage.settings["PORTAGE_DEBUG"]="1"
-	portage.settings.backup_changes("PORTAGE_DEBUG")
-	portage.debug=1
-	portage.settings.lock()
-	if "python-trace" in portage.features:
-		import portage_debug
-		portage_debug.set_trace(True)
-
-if ("--resume" in myopts):
-	if "--tree" in myopts:
-		print "* --tree is currently broken with --resume. Disabling..."
-		myopts.remove("--tree")
-
-# Set color output
-if "--nocolor" in myopts or \
-portage.settings["NOCOLOR"] in ("yes","true"):
-	nocolor()
-	if "NOCOLOR" not in portage.settings:
-		portage.settings.unlock()
-		portage.settings["NOCOLOR"] = "true"
-		portage.settings.backup_changes("NOCOLOR")
-		portage.settings.lock()
-
-if not ("--quiet" in myopts):
-	if not sys.stdout.isatty() or ("--nospinner" in myopts):
-		update_spinner = update_basic_spinner
-
-CLEAN_DELAY = 5
-EMERGE_WARNING_DELAY = 10
-if portage.settings["CLEAN_DELAY"]:
-	CLEAN_DELAY = string.atoi("0"+portage.settings["CLEAN_DELAY"])
-if portage.settings["EMERGE_WARNING_DELAY"]:
-	EMERGE_WARNING_DELAY = string.atoi("0"+portage.settings["EMERGE_WARNING_DELAY"])
 
 def emergelog(mystr,short_msg=None):
 	if "notitles" not in portage.features:
@@ -464,14 +155,14 @@
 		emergelog(" *** terminating.")
 	if "notitles" not in portage.features:
 		xtermTitleReset()
-portage.atexit_register(emergeexit)
+
 
 def emergeexitsig(signum, frame):
 	signal.signal(signal.SIGINT, signal.SIG_IGN)
 	portage.portageexit()
 	portage_util.writemsg("\n\nExiting on signal %(signal)s\n" % {"signal":signum})
 	sys.exit(100+signum)
-signal.signal(signal.SIGINT, emergeexitsig)
+
 
 def countdown(secs=5, doing="Starting"):
 	if secs:
@@ -597,83 +288,6 @@
 	# Move all the help stuff out of this file.
 	emergehelp.help(myaction,myopts,havecolor)
 
-if "--version" in myopts:
-	print getportageversion()
-	sys.exit(0)
-elif "--help" in myopts:
-	help()
-	sys.exit(0)
-
-if portage.wheelgid == portage.portage_gid:
-	print "emerge: wheel group use is being deprecated. Please update group and passwd to"
-	print "        include the portage user as noted above, and then use group portage."
-
-if "--debug" in myopts:
-	print "myaction", myaction
-	print "myopts", myopts
-
-if not myaction and not myfiles and "--resume" not in myopts:
-	help()
-	sys.exit(1)
-
-# 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"):
-		if portage.secpass >= 1:
-			if "--fetchonly" not in myopts and \
-			"--fetch-all-uri" not in myopts:
-				print "emerge: root access required."
-				sys.exit(1)
-		else:
-			print "emerge: root access required."
-			sys.exit(1)
-
-if not "--pretend" in myopts:
-	emergelog("Started emerge on: "+time.strftime("%b %d, %Y %H:%M:%S", time.localtime()))
-	myelogstr=""
-	if myopts:
-		myelogstr=string.join(myopts, " ")
-	if myaction:
-		myelogstr+=" "+myaction
-	if myfiles:
-		myelogstr+=" "+string.join(myfiles, " ")
-	emergelog(" *** emerge "+myelogstr)
-
-#configure emerge engine parameters
-#
-# self:      include _this_ package regardless of if it is merged.
-# selective: exclude the package if it is merged
-# recurse:   go into the dependencies
-# empty:     pretend nothing is merged
-myparams=["self","recurse"]
-add=[]
-sub=[]
-if "--update" in myopts or myaction in ("system", "world"):
-	add.extend(["selective","empty"])
-if "--emptytree" in myopts:
-	add.extend(["empty"])
-	sub.extend(["selective"])
-if "--nodeps" in myopts:
-	sub.extend(["recurse"])
-if "--noreplace" in myopts:
-	add.extend(["selective"])
-if "--deep" in myopts:
-	add.extend(["deep"])
-if "--selective" in myopts:
-	add.extend(["selective"])
-if myaction in ["world","system"]:
-	add.extend(["selective"])
-elif myaction in ["depclean"]:
-	add.extend(["empty"])
-	sub.extend(["selective"])
-for x in add:
-	if (x not in myparams) and (x not in sub):
-		myparams.append(x)
-for x in sub:
-	if x in myparams:
-		myparams.remove(x)
 
 # search functionality
 class search:
@@ -693,9 +307,8 @@
 		This makes successive searches faster."""
 		self.installcache = portage.db["/"]["vartree"]
 
-	def execute(self,searchkey):
+	def execute(self,searchkey, myopts):
 		"""Performs the search for the supplied search key"""
-		global myopts
 		match_category = 0
 		self.searchkey=searchkey
 		self.packagematches = []
@@ -883,11 +496,9 @@
 		mynewdict[portage.dep_getkey(x)]=x
 	return mynewdict
 
-olddbapi=None
 class depgraph:
 
 	def __init__(self,myaction,myopts):
-		global olddbapi
 		self.pkgsettings = portage.config(clone=portage.settings)
 		if not self.pkgsettings["ARCH"]:
 			portage.writemsg(red("\a!!! ARCH is not set... Are you missing the /etc/make.profile symlink?\n"))
@@ -1360,8 +971,7 @@
 				retlist.append(y)
 		return retlist
 
-	def xcreate(self,mode="system"):
-		global syslist
+	def xcreate(self,syslist,mode="system"):
 		world_problems = False
 		if mode=="system":
 			mylist=syslist
@@ -1388,7 +998,7 @@
 			else:
 				newlist.append(atom)
 		mylist = newlist
-		
+
 		missing_atoms = []
 		for mydep in mylist:
 			try:
@@ -1441,7 +1051,7 @@
 
 		return myk
 
-	def display(self,mylist,verbosity=("--quiet" in myopts and 1 or "--verbose" in myopts and 3 or 2)):
+	def display(self,mylist,verbosity=2):
 		changelogs=[]
 		p=[]
 		totalsize=0
@@ -1831,7 +1441,7 @@
 	def outdated(self):
 		return self.outdatedpackages
 
-	def merge(self,mylist):
+	def merge(self,mylist,syslist,favorites):
 		returnme=0
 		mymergelist=[]
 
@@ -2066,7 +1676,7 @@
 					if self.pkgsettings["AUTOCLEAN"]=="yes":
 						xsplit=portage.pkgsplit(x[2])
 						emergelog(" >>> AUTOCLEAN: "+xsplit[0])
-						retval=unmerge("clean", [xsplit[0]])
+						retval=unmerge("clean", [xsplit[0]],myopts)
 						if not retval:
 							emergelog(" --- AUTOCLEAN: Nothing unmerged.")
 
@@ -2126,7 +1736,7 @@
 			else:
 				sys.exit(0)
 
-def unmerge(unmerge_action, unmerge_files):
+def unmerge(unmerge_action, unmerge_files, myopts):
 	candidate_catpkgs=[]
 	global_unmerge=0
 
@@ -2144,7 +1754,6 @@
 		else:
 			syslist.append(mycp)
 
-	global myopts
 	mysettings = portage.config(clone=portage.settings)
 
 	if not unmerge_files or "world" in unmerge_files or "system" in unmerge_files:
@@ -2444,8 +2053,7 @@
 				print " "+green("*")+" Processed",icount,"info files."
 
 
-def post_emerge(retval=0):
-	global myopts
+def post_emerge(myopts, retval=0):
 	os.chdir("/")
 	if "--pretend" in myopts:
 		sys.exit(retval)
@@ -2488,11 +2096,10 @@
 		testatom = x
 	return portage.isvalidatom(testatom)
 
-# general options that should be taken into account before any action
-if "--debug" in myopts:
-	edebug=1
 
-if myaction in ["sync","metadata"] and (not "--help" in myopts):
+
+
+def do_sync_or_metadata():
 	if "--pretend" in myopts:
 		print "emerge: \"sync\" actions do not support \"--pretend.\""
 		sys.exit(1)
@@ -2944,7 +2551,8 @@
 		print red(" * ")+"configuration files."
 		print red(" * ")+"To update portage, run 'emerge portage'."
 		print
-elif myaction=="regen":
+		
+def do_regen():
 	emergelog(" === regen")
 	#regenerate cache entries
 	print "Regenerating cache entries... "
@@ -2969,8 +2577,8 @@
 			except Exception, e:
 				print "\n  error processing %(cpv)s, continuing... (%(e)s)" % {"cpv":y,"e":str(e)}
 	print "done!"
-# HELP action
-elif "config"==myaction:
+	
+def do_config():
 	if len(myfiles) != 1 or "system" in myfiles or "world" in myfiles:
 		print red("!!! config can only take a single package atom at this time\n")
 		sys.exit(1)
@@ -3021,7 +2629,7 @@
 	print
 
 # INFO action
-elif "info"==myaction:
+def do_info():
 	unameout=commands.getstatusoutput("uname -mrp")[1]
 	print getportageversion()
 	print "================================================================="
@@ -3102,23 +2710,24 @@
 				print "%s: %s" % (str(x), str(module.cvs_id_string))
 
 # SEARCH action
-elif "search"==myaction:
+def do_search(myopts):
 	if not myfiles:
 		print "emerge: no search terms provided."
 	else:
 		searchinstance = search()
 		for mysearch in myfiles:
 			try:
-				searchinstance.execute(mysearch)
+				searchinstance.execute(mysearch, myopts)
 			except re.error, comment:
 				print "\n!!! Regular expression error in \"%s\": %s" % ( mysearch, comment )
 				sys.exit(1)
 			searchinstance.output()
-elif "unmerge"==myaction or "prune"==myaction or "clean"==myaction:
-	if 1==unmerge(myaction, myfiles):
-		post_emerge()
+			
+def do_unmerge(myopts):
+	if 1==unmerge(myaction, myfiles, myopts):
+		post_emerge(myopts)
 
-elif "depclean"==myaction:
+def do_depclean():
 	# Kill packages that aren't explicitly merged or are required as a
 	# dependency of another package. World file is explicit.
 
@@ -3157,7 +2766,7 @@
 
 	if not ("--quiet" in myopts):
 		print "\nCalculating dependencies  ",
-	if not mydepgraph.xcreate("world"):
+	if not mydepgraph.xcreate(syslist, "world"):
 		print "\n!!! Failed to create deptree."
 		sys.exit(1)
 	if not ("--quiet" in myopts):
@@ -3218,7 +2827,7 @@
 	#print
 
 	if len(cleanlist):
-		unmerge("unmerge", cleanlist)
+		unmerge("unmerge", cleanlist, myopts)
 
 	print
 	print "Packages installed:   "+str(len(myvarlist))
@@ -3230,10 +2839,10 @@
 		print "Number to remove:     "+str(len(cleanlist))
 	else:
 		print "Number removed:       "+str(len(cleanlist))
-		post_emerge()
+		post_emerge(myopts)
 
 # "update", "system", or just process files:
-else:
+def do_update_or_system(myopts):
 	favorites=[]
 	syslist=getlist("system")
 	if ("--ask" in myopts or "--pretend" in myopts) and not "--quiet" in myopts:
@@ -3282,7 +2891,7 @@
 			if not ("--quiet" in myopts):
 				print "Calculating",myaction,"dependencies  ",
 				sys.stdout.flush()
-			if not mydepgraph.xcreate(myaction):
+			if not mydepgraph.xcreate(syslist, myaction):
 				print "!!! Depgraph creation failed."
 				sys.exit(1)
 			if not ("--quiet" in myopts):
@@ -3308,10 +2917,12 @@
 
 	if "--ask" in myopts:
 		if "--resume" in myopts:
-			mydepgraph.display(portage.mtimedb["resume"]["mergelist"])
+			mydepgraph.display(portage.mtimedb["resume"]["mergelist"],
+							   verbosity=_verbosity(myopts))
 			prompt="Do you want me to resume merging these packages?"
 		else:
-			mydepgraph.display(mydepgraph.altlist())
+			mydepgraph.display(mydepgraph.altlist(),
+							   verbosity=_verbosity(myopts))
 			mergecount=0
 			for x in mydepgraph.altlist():
 				if x[3]!="nomerge":
@@ -3345,9 +2956,11 @@
 
 	if ("--pretend" in myopts) and not ("--fetchonly" in myopts or "--fetch-all-uri" in myopts):
 		if ("--resume" in myopts):
-			mydepgraph.display(portage.mtimedb["resume"]["mergelist"])
+			mydepgraph.display(portage.mtimedb["resume"]["mergelist"],
+							   verbosity=_verbosity(myopts))
 		else:
-			mydepgraph.display(mydepgraph.altlist())
+			mydepgraph.display(mydepgraph.altlist(),
+							   verbosity=_verbosity(myopts))
 	else:
 		if ("--buildpkgonly" in myopts):
 			if not mydepgraph.digraph.hasallzeros():
@@ -3357,7 +2970,7 @@
 
 		if ("--resume" in myopts):
 			favorites=portage.mtimedb["resume"]["favorites"]
-			mydepgraph.merge(portage.mtimedb["resume"]["mergelist"])
+			mydepgraph.merge(portage.mtimedb["resume"]["mergelist"], syslist, favorites)
 		else:
 			if "resume" in portage.mtimedb and \
 			"mergelist" in portage.mtimedb["resume"] and \
@@ -3381,11 +2994,427 @@
 						pkglist.append(pkg)
 			else:
 				pkglist = mydepgraph.altlist()
-			mydepgraph.merge(pkglist)
+			mydepgraph.merge(pkglist, syslist, favorites)
 
 		if portage.mtimedb.has_key("resume"):
 			del portage.mtimedb["resume"]
 		if portage.settings["AUTOCLEAN"] and "yes"==portage.settings["AUTOCLEAN"]:
 			print ">>> Auto-cleaning packages..."
-			unmerge("clean", ["world"])
-	post_emerge()
+			unmerge("clean", ["world"], myopts)
+	post_emerge(myopts)
+
+def _verbosity(myopts):
+	return ("--quiet" in myopts and 1 or "--verbose" in myopts and 3 or 2)
+
+if __name__ == "__main__":
+	spinpos = 0
+	spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
+	update_spinner = update_twirl_spinner
+	if "candy" in portage.settings.features:
+		spinner_msgs = ["Gentoo Rocks ("+os.uname()[0]+")",
+                "Thank you for using Gentoo. :)",
+                "Are you actually trying to read this?",
+                "How many times have you stared at this?",
+                "We are generating the cache right now",
+                "You are paying too much attention.",
+                "A theory is better than its explanation.",
+                "Phasers locked on target, Captain.",
+                "Thrashing is just virtual crashing.",
+                "To be is to program.",
+                "Real Users hate Real Programmers.",
+                "When all else fails, read the instructions.",
+                "Functionality breeds Contempt.",
+                "The future lies ahead.",
+                "3.1415926535897932384626433832795028841971694",
+                "Sometimes insanity is the only alternative.",
+                "Inaccuracy saves a world of explanation.",
+               ]
+			
+		spinner = spinner_msgs[int(time.time()*100)%len(spinner_msgs)]
+		update_spinner = update_scroll_spinner
+	
+	if (not sys.stdout.isatty()) or (portage.settings["NOCOLOR"] in ["yes","true"]):
+		nocolor()	
+	if portage.settings.has_key("PORTAGE_NICENESS"):
+		try:
+			os.nice(int(portage.settings["PORTAGE_NICENESS"]))
+		except (OSError,ValueError), e:
+			print "!!! Failed to change nice value to '"+str(portage.settings["PORTAGE_NICENESS"])+"'"
+			print "!!!",e
+	
+	#Freeze the portdbapi for enhanced performance:
+	portage.portdb.freeze()
+	
+	# Kill noauto as it will break merges otherwise.
+	while 'noauto' in portage.features:
+		del portage.features[portage.features.index('noauto')]
+	
+	#number of ebuilds merged
+	merged=0
+	params=["selective", "deep", "self", "recurse", "empty"]
+	actions=[
+	"clean", "config", "depclean",
+	"info", "metadata",
+	"prune", "regen",  "search",
+	"sync",  "system", "unmerge",  "world",
+	]
+	options=[
+	"--ask",          "--alphabetical",
+	"--buildpkg",     "--buildpkgonly",
+	"--changelog",    "--columns", "--cols",
+	"--debug",        "--deep",
+	"--digest",
+	"--emptytree",
+	"--fetchonly",    "--fetch-all-uri",
+	"--getbinpkg",    "--getbinpkgonly",
+	"--help",         "--ignore-default-opts",
+	"--noconfmem",
+	"--newuse",       "--nocolor",
+	"--nodeps",       "--noreplace",
+	"--nospinner",    "--oneshot",
+	"--onlydeps",     "--pretend",
+	"--quiet",        "--resume",
+	"--searchdesc",   "--selective",
+	"--skipfirst",    "--skip-first",
+	"--tree",
+	"--update",       
+	"--usepkg",       "--usepkgonly",
+	"--verbose",      "--version"
+	]
+	
+	shortmapping={
+	"1":"--oneshot",
+	"a":"--ask",
+	"b":"--buildpkg",  "B":"--buildpkgonly",
+	"c":"--clean",     "C":"--unmerge",
+	"d":"--debug",     "D":"--deep",
+	"e":"--emptytree",
+	"f":"--fetchonly", "F":"--fetch-all-uri",
+	"g":"--getbinpkg", "G":"--getbinpkgonly",
+	"h":"--help",
+	"k":"--usepkg",    "K":"--usepkgonly",
+	"l":"--changelog",
+	"n":"--noreplace", "N":"--newuse",
+	"o":"--onlydeps",  "O":"--nodeps",
+	"p":"--pretend",   "P":"--prune",
+	"q":"--quiet",
+	"s":"--search",    "S":"--searchdesc",
+	't':"--tree",
+	"u":"--update",
+	"v":"--verbose",   "V":"--version"
+	}
+	
+	myaction=None
+	myopts=[]
+	myfiles=[]
+	edebug=0
+	
+	# process short actions
+	tmpcmdline=sys.argv[1:]
+	if "--ignore-default-opts" not in tmpcmdline:
+		tmpcmdline.extend(portage.settings["EMERGE_DEFAULT_OPTS"].split())
+	cmdline=[]
+	for x in tmpcmdline:
+		if x[0:1]=="-" and x[1:2]!="-":
+			for y in x[1:]:
+				if shortmapping.has_key(y):
+					if shortmapping[y] in cmdline:
+						print
+						print "*** Warning: Redundant use of",shortmapping[y]
+					else:
+						cmdline.append(shortmapping[y])
+				else:
+					print "!!! Error: -"+y+" is an invalid short action or option."
+					sys.exit(1)
+		else:
+			cmdline.append(x)
+	
+	# process the options and command arguments
+	for x in cmdline:
+		if not x:
+			continue
+		if len(x)>=2 and x[0:2]=="--":
+			if x == "--cols":
+				x = "--columns"
+			elif x == "--skip-first":
+				x = "--skipfirst"
+			if x in options:
+				if x not in myopts:
+					myopts.append(x)
+			elif x[2:] in actions:
+				if myaction:
+					if myaction not in ["system", "world"]:
+						myaction="--"+myaction
+					print
+					print red("!!!")+green(" Multiple actions requested... Please choose one only.")
+					print red("!!!")+" '"+darkgreen(myaction)+"' "+red("or")+" '"+darkgreen(x)+"'"
+					print
+					sys.exit(1)
+				myaction=x[2:]
+			else:
+				print "!!! Error:",x,"is an invalid option."
+				sys.exit(1)
+		elif (not myaction) and (x in actions):
+			if x not in ["system", "world"]:
+				print red("*** Deprecated use of action '%s', use '--%s' instead" % (x,x))
+			if myaction:
+				print
+				print red("!!!")+green(" Multiple actions requested... Please choose one only.")
+				print red("!!! '")+darkgreen(myaction)+"' "+red("or")+" '"+darkgreen(x)+"'"
+				print
+				sys.exit(1)
+			myaction=x
+		elif x[-1]=="/":
+			# this little conditional helps tab completion
+			myfiles.append(x[:-1])
+		else:
+			myfiles.append(x)
+	
+	
+	if "moo" in myfiles:
+		print """
+	
+	Larry loves Gentoo (""" + os.uname()[0] + """)
+	
+	_______________________
+	< Have you mooed today? >
+	-----------------------
+			\   ^__^
+			\  (oo)\_______
+				(__)\       )\/\ 
+					||----w |
+					||     ||
+	
+	"""
+	
+	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]
+		if (ext == ".ebuild" or ext == ".tbz2") and os.path.exists(os.path.abspath(x)):
+			print "emerging by path implies --oneshot... adding --oneshot to options."
+			print red("\n*** emerging by path is broken and may not always work!!!\n")
+			break
+	
+	if ("--tree" in myopts) and ("--columns" in myopts):
+		print "emerge: can't specify both of \"--tree\" and \"--columns\"."
+		sys.exit(1)
+	
+	if ("--quiet" in myopts):
+		update_spinner = update_quiet_spinner
+		portage_util.noiselimit = -1
+		portage.settings.unlock()
+		portage.settings["PORTAGE_QUIET"]="1"
+		portage.settings.backup_changes("PORTAGE_QUIET")
+		portage.settings.lock()
+	
+	# Always create packages if FEATURES=buildpkg
+	# Imply --buildpkg if --buildpkgonly
+	if ("buildpkg" in portage.features) or ("--buildpkgonly" in myopts):
+		if "--buildpkg" not in myopts:
+			myopts.append("--buildpkg")
+	
+	# --tree only makes sense with --pretend
+	if "--tree" in myopts and not (("--pretend" in myopts) or ("--ask" in myopts)):
+		print ">>> --tree implies --pretend... adding --pretend to options."
+		myopts.append("--pretend")
+	
+	# Also allow -S to invoke search action (-sS)
+	if ("--searchdesc" in myopts):
+		if myaction and myaction != "search":
+			myfiles.append(myaction)
+		if "--search" not in myopts:
+			myopts.append("--search")
+		myaction = "search"
+	
+	# Always try and fetch binary packages if FEATURES=getbinpkg
+	if ("getbinpkg" in portage.features):
+		myopts.append("--getbinpkg")
+	
+	if "--skipfirst" in myopts and "--resume" not in myopts:
+		myopts.append("--resume")
+	
+	if ("--getbinpkgonly" in myopts) and not ("--usepkgonly" in myopts):
+		myopts.append("--usepkgonly")
+	
+	if ("--getbinpkgonly" in myopts) and not ("--getbinpkg" in myopts):
+		myopts.append("--getbinpkg")
+	
+	if ("--getbinpkg" in myopts) and not ("--usepkg" in myopts):
+		myopts.append("--usepkg")
+	
+	# Also allow -K to apply --usepkg/-k
+	if ("--usepkgonly" in myopts) and not ("--usepkg" in myopts):
+		myopts.append("--usepkg")
+	
+	if ("--newuse" in myopts) and not ("--update" in myopts):
+		print ">>> --newuse implies --update... adding --update to options."
+		myopts.append("--update")
+	
+	# Also allow -l to apply --pretend/-p, but if already in --ask mode
+	if ("--changelog" in myopts) and not (("--pretend" in myopts) or ("--ask" in myopts)):
+		print ">>> --changelog implies --pretend... adding --pretend to options."
+		myopts.append("--pretend")
+	
+	# Allow -p to remove --ask
+	if ("--pretend" in myopts) and ("--ask" in myopts):
+		print ">>> --pretend disables --ask... removing --ask from options."
+		myopts.remove("--ask")
+	
+	# forbid --ask when not in a terminal
+	# note: this breaks `emerge --ask | tee logfile`, but that doesn't work anyway.
+	if ("--ask" in myopts) and (not sys.stdin.isatty()):
+		portage.writemsg("!!! \"--ask\" should only be used in a terminal. Exiting.\n")
+		sys.exit(1)
+	
+	# Set so that configs will be merged regardless of remembered status
+	if ("--noconfmem" in myopts):
+		portage.settings.unlock()
+		portage.settings["NOCONFMEM"]="1"
+		portage.settings.backup_changes("NOCONFMEM")
+		portage.settings.lock()
+	
+	# Set various debug markers... They should be merged somehow.
+	if ("--debug" in myopts):
+		portage.settings.unlock()
+		portage.settings["PORTAGE_DEBUG"]="1"
+		portage.settings.backup_changes("PORTAGE_DEBUG")
+		portage.debug=1
+		portage.settings.lock()
+		if "python-trace" in portage.features:
+			import portage_debug
+			portage_debug.set_trace(True)
+	
+	if ("--resume" in myopts):
+		if "--tree" in myopts:
+			print "* --tree is currently broken with --resume. Disabling..."
+			myopts.remove("--tree")
+	
+	# Set color output
+	if "--nocolor" in myopts or \
+	portage.settings["NOCOLOR"] in ("yes","true"):
+		nocolor()
+		if "NOCOLOR" not in portage.settings:
+			portage.settings.unlock()
+			portage.settings["NOCOLOR"] = "true"
+			portage.settings.backup_changes("NOCOLOR")
+			portage.settings.lock()
+	
+	if not ("--quiet" in myopts):
+		if not sys.stdout.isatty() or ("--nospinner" in myopts):
+			update_spinner = update_basic_spinner
+	
+	CLEAN_DELAY = 5
+	EMERGE_WARNING_DELAY = 10
+	if portage.settings["CLEAN_DELAY"]:
+		CLEAN_DELAY = string.atoi("0"+portage.settings["CLEAN_DELAY"])
+	if portage.settings["EMERGE_WARNING_DELAY"]:
+		EMERGE_WARNING_DELAY = string.atoi("0"+portage.settings["EMERGE_WARNING_DELAY"])
+
+
+	portage.atexit_register(emergeexit)
+	
+	signal.signal(signal.SIGINT, emergeexitsig)
+		
+	
+	if "--version" in myopts:
+		print getportageversion()
+		sys.exit(0)
+	elif "--help" in myopts:
+		help()
+		sys.exit(0)
+	
+	if portage.wheelgid == portage.portage_gid:
+		print "emerge: wheel group use is being deprecated. Please update group and passwd to"
+		print "        include the portage user as noted above, and then use group portage."
+	
+	if "--debug" in myopts:
+		print "myaction", myaction
+		print "myopts", myopts
+	
+	if not myaction and not myfiles and "--resume" not in myopts:
+		help()
+		sys.exit(1)
+	
+	# 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"):
+			if portage.secpass >= 1:
+				if "--fetchonly" not in myopts and \
+				"--fetch-all-uri" not in myopts:
+					print "emerge: root access required."
+					sys.exit(1)
+			else:
+				print "emerge: root access required."
+				sys.exit(1)
+	
+	if not "--pretend" in myopts:
+		emergelog("Started emerge on: "+time.strftime("%b %d, %Y %H:%M:%S", time.localtime()))
+		myelogstr=""
+		if myopts:
+			myelogstr=string.join(myopts, " ")
+		if myaction:
+			myelogstr+=" "+myaction
+		if myfiles:
+			myelogstr+=" "+string.join(myfiles, " ")
+		emergelog(" *** emerge "+myelogstr)
+	
+	#configure emerge engine parameters
+	#
+	# self:      include _this_ package regardless of if it is merged.
+	# selective: exclude the package if it is merged
+	# recurse:   go into the dependencies
+	# empty:     pretend nothing is merged
+	myparams=["self","recurse"]
+	add=[]
+	sub=[]
+	if "--update" in myopts or myaction in ("system", "world"):
+		add.extend(["selective","empty"])
+	if "--emptytree" in myopts:
+		add.extend(["empty"])
+		sub.extend(["selective"])
+	if "--nodeps" in myopts:
+		sub.extend(["recurse"])
+	if "--noreplace" in myopts:
+		add.extend(["selective"])
+	if "--deep" in myopts:
+		add.extend(["deep"])
+	if "--selective" in myopts:
+		add.extend(["selective"])
+	if myaction in ["world","system"]:
+		add.extend(["selective"])
+	elif myaction in ["depclean"]:
+		add.extend(["empty"])
+		sub.extend(["selective"])
+	for x in add:
+		if (x not in myparams) and (x not in sub):
+			myparams.append(x)
+	for x in sub:
+		if x in myparams:
+			myparams.remove(x)
+			
+	
+	# general options that should be taken into account before any action
+	if "--debug" in myopts:
+		edebug=1
+		
+	if myaction in ["sync","metadata"] and (not "--help" in myopts):
+		do_sync_or_metadata()
+	elif myaction=="regen":
+		do_regen()	
+	elif "config"==myaction:
+		do_config()
+	elif "info"==myaction:
+		do_info()
+	elif "search"==myaction:
+		do_search(myopts)
+	elif "unmerge"==myaction or "prune"==myaction or "clean"==myaction:
+		do_unmerge(myopts)
+	elif "depclean"==myaction:
+		do_depclean()
+	else:
+		do_update_or_system(myopts)
