X-Git-Url: https://git.saurik.com/apt.git/blobdiff_plain/e4b16ac68196eab5e58abf715459fe70c199cff3..1d51f78e9d128191ff8b2d48e42d90ebdbff2588:/apt-pkg/depcache.cc

diff --git a/apt-pkg/depcache.cc b/apt-pkg/depcache.cc
index ec7a5de64..580056687 100644
--- a/apt-pkg/depcache.cc
+++ b/apt-pkg/depcache.cc
@@ -10,6 +10,7 @@
 // Include Files							/*{{{*/
 #include <apt-pkg/depcache.h>
 #include <apt-pkg/version.h>
+#include <apt-pkg/versionmatch.h>
 #include <apt-pkg/error.h>
 #include <apt-pkg/sptr.h>
 #include <apt-pkg/algorithms.h>
@@ -17,6 +18,7 @@
 #include <apt-pkg/fileutl.h>
 #include <apt-pkg/strutl.h>
 #include <apt-pkg/configuration.h>
+#include <apt-pkg/aptconfiguration.h>
 #include <apt-pkg/pkgsystem.h>
 #include <apt-pkg/tagfile.h>
 
@@ -68,7 +70,7 @@ void pkgDepCache::ActionGroup::release()
 	    cache.MarkAndSweep();
 	}
 
-      released = false;
+      released = true;
     }
 }
 
@@ -127,7 +129,7 @@ bool pkgDepCache::Init(OpProgress *Prog)
    /* Set the current state of everything. In this state all of the
       packages are kept exactly as is. See AllUpgrade */
    int Done = 0;
-   for (PkgIterator I = PkgBegin(); I.end() != true; I++,Done++)
+   for (PkgIterator I = PkgBegin(); I.end() != true; ++I, ++Done)
    {
       if (Prog != 0 && Done%20 == 0)
 	 Prog->Progress(Done);
@@ -164,38 +166,50 @@ bool pkgDepCache::Init(OpProgress *Prog)
 bool pkgDepCache::readStateFile(OpProgress *Prog)			/*{{{*/
 {
    FileFd state_file;
-   string state = _config->FindDir("Dir::State") + "extended_states";
-   if(FileExists(state)) {
+   string const state = _config->FindFile("Dir::State::extended_states");
+   if(RealFileExists(state)) {
       state_file.Open(state, FileFd::ReadOnly);
-      int file_size = state_file.Size();
+      int const file_size = state_file.Size();
       if(Prog != NULL)
 	 Prog->OverallProgress(0, file_size, 1, 
 			       _("Reading state information"));
 
       pkgTagFile tagfile(&state_file);
       pkgTagSection section;
-      int amt=0;
-      bool debug_autoremove=_config->FindB("Debug::pkgAutoRemove",false);
+      int amt = 0;
+      bool const debug_autoremove = _config->FindB("Debug::pkgAutoRemove",false);
       while(tagfile.Step(section)) {
-	 string pkgname = section.FindS("Package");
-	 pkgCache::PkgIterator pkg=Cache->FindPkg(pkgname);
-	 // Silently ignore unknown packages and packages with no actual
-	 // version.
-	 if(!pkg.end() && !pkg.VersionList().end()) {
-	    short reason = section.FindI("Auto-Installed", 0);
-	    if(reason > 0)
-	       PkgState[pkg->ID].Flags  |= Flag::Auto;
-	    if(debug_autoremove)
-	       std::cout << "Auto-Installed : " << pkgname << std::endl;
-	    amt+=section.size();
-	    if(Prog != NULL)
-	       Prog->OverallProgress(amt, file_size, 1, 
-				     _("Reading state information"));
+	 string const pkgname = section.FindS("Package");
+	 string pkgarch = section.FindS("Architecture");
+	 if (pkgarch.empty() == true)
+	    pkgarch = "any";
+	 pkgCache::PkgIterator pkg = Cache->FindPkg(pkgname, pkgarch);
+	 // Silently ignore unknown packages and packages with no actual version.
+	 if(pkg.end() == true || pkg->VersionList == 0)
+	    continue;
+
+	 short const reason = section.FindI("Auto-Installed", 0);
+	 if(reason > 0)
+	 {
+	    PkgState[pkg->ID].Flags |= Flag::Auto;
+	    if (unlikely(debug_autoremove))
+	       std::clog << "Auto-Installed : " << pkg.FullName() << std::endl;
+	    if (pkgarch == "any")
+	    {
+	       pkgCache::GrpIterator G = pkg.Group();
+	       for (pkg = G.NextPkg(pkg); pkg.end() != true; pkg = G.NextPkg(pkg))
+		  if (pkg->VersionList != 0)
+		     PkgState[pkg->ID].Flags |= Flag::Auto;
+	    }
 	 }
+	 amt += section.size();
 	 if(Prog != NULL)
-	    Prog->OverallProgress(file_size, file_size, 1, 
+	    Prog->OverallProgress(amt, file_size, 1, 
 				  _("Reading state information"));
       }
+      if(Prog != NULL)
+	 Prog->OverallProgress(file_size, file_size, 1,
+			       _("Reading state information"));
    }
 
    return true;
@@ -203,18 +217,18 @@ bool pkgDepCache::readStateFile(OpProgress *Prog)			/*{{{*/
 									/*}}}*/
 bool pkgDepCache::writeStateFile(OpProgress *prog, bool InstalledOnly)	/*{{{*/
 {
-   bool debug_autoremove = _config->FindB("Debug::pkgAutoRemove",false);
+   bool const debug_autoremove = _config->FindB("Debug::pkgAutoRemove",false);
    
    if(debug_autoremove)
       std::clog << "pkgDepCache::writeStateFile()" << std::endl;
 
    FileFd StateFile;
-   string state = _config->FindDir("Dir::State") + "extended_states";
+   string const state = _config->FindFile("Dir::State::extended_states");
 
    // if it does not exist, create a empty one
-   if(!FileExists(state)) 
+   if(!RealFileExists(state)) 
    {
-      StateFile.Open(state, FileFd::WriteEmpty);
+      StateFile.Open(state, FileFd::WriteAtomic);
       StateFile.Close();
    }
 
@@ -224,7 +238,7 @@ bool pkgDepCache::writeStateFile(OpProgress *prog, bool InstalledOnly)	/*{{{*/
 			   state.c_str());
 
    FILE *OutFile;
-   string outfile = state + ".tmp";
+   string const outfile = state + ".tmp";
    if((OutFile = fopen(outfile.c_str(),"w")) == NULL)
       return _error->Error(_("Failed to write temporary StateFile %s"),
 			   outfile.c_str());
@@ -235,46 +249,72 @@ bool pkgDepCache::writeStateFile(OpProgress *prog, bool InstalledOnly)	/*{{{*/
    std::set<string> pkgs_seen;
    const char *nullreorderlist[] = {0};
    while(tagfile.Step(section)) {
-	 string pkgname = section.FindS("Package");
+	 string const pkgname = section.FindS("Package");
+	 string pkgarch = section.FindS("Architecture");
+	 if (pkgarch.empty() == true)
+	    pkgarch = "native";
 	 // Silently ignore unknown packages and packages with no actual
 	 // version.
-	 pkgCache::PkgIterator pkg=Cache->FindPkg(pkgname);
+	 pkgCache::PkgIterator pkg = Cache->FindPkg(pkgname, pkgarch);
 	 if(pkg.end() || pkg.VersionList().end()) 
 	    continue;
-	 bool newAuto = (PkgState[pkg->ID].Flags & Flag::Auto);
+	 StateCache const &P = PkgState[pkg->ID];
+	 bool newAuto = (P.Flags & Flag::Auto);
+	 // skip not installed or now-removed ones if requested
+	 if (InstalledOnly && (
+	     (pkg->CurrentVer == 0 && P.Mode != ModeInstall) ||
+	     (pkg->CurrentVer != 0 && P.Mode == ModeDelete)))
+	 {
+	    // The section is obsolete if it contains no other tag
+	    unsigned int const count = section.Count();
+	    if (count < 2 ||
+		(count == 2 && section.Exists("Auto-Installed")) ||
+		(count == 3 && section.Exists("Auto-Installed") && section.Exists("Architecture")))
+	       continue;
+	    else
+	       newAuto = false;
+	 }
 	 if(_config->FindB("Debug::pkgAutoRemove",false))
 	    std::clog << "Update existing AutoInstall info: " 
-		      << pkg.Name() << std::endl;
-	 TFRewriteData rewrite[2];
-	 rewrite[0].Tag = "Auto-Installed";
-	 rewrite[0].Rewrite = newAuto ? "1" : "0";
+		      << pkg.FullName() << std::endl;
+	 TFRewriteData rewrite[3];
+	 rewrite[0].Tag = "Architecture";
+	 rewrite[0].Rewrite = pkg.Arch();
 	 rewrite[0].NewTag = 0;
-	 rewrite[1].Tag = 0;
+	 rewrite[1].Tag = "Auto-Installed";
+	 rewrite[1].Rewrite = newAuto ? "1" : "0";
+	 rewrite[1].NewTag = 0;
+	 rewrite[2].Tag = 0;
 	 TFRewrite(OutFile, section, nullreorderlist, rewrite);
 	 fprintf(OutFile,"\n");
-	 pkgs_seen.insert(pkgname);
+	 pkgs_seen.insert(pkg.FullName());
    }
    
    // then write the ones we have not seen yet
    std::ostringstream ostr;
-   for(pkgCache::PkgIterator pkg=Cache->PkgBegin(); !pkg.end(); pkg++) {
-      if(PkgState[pkg->ID].Flags & Flag::Auto) {
-	 if (pkgs_seen.find(pkg.Name()) != pkgs_seen.end()) {
+   for(pkgCache::PkgIterator pkg=Cache->PkgBegin(); !pkg.end(); ++pkg) {
+      StateCache const &P = PkgState[pkg->ID];
+      if(P.Flags & Flag::Auto) {
+	 if (pkgs_seen.find(pkg.FullName()) != pkgs_seen.end()) {
 	    if(debug_autoremove)
-	       std::clog << "Skipping already written " << pkg.Name() << std::endl;
+	       std::clog << "Skipping already written " << pkg.FullName() << std::endl;
 	    continue;
 	 }
-         // skip not installed ones if requested
-         if(InstalledOnly && pkg->CurrentVer == 0)
-            continue;
+	 // skip not installed ones if requested
+	 if (InstalledOnly && (
+	     (pkg->CurrentVer == 0 && P.Mode != ModeInstall) ||
+	     (pkg->CurrentVer != 0 && P.Mode == ModeDelete)))
+	    continue;
+	 const char* const pkgarch = pkg.Arch();
+	 if (strcmp(pkgarch, "all") == 0)
+	    continue;
 	 if(debug_autoremove)
-	    std::clog << "Writing new AutoInstall: " 
-		      << pkg.Name() << std::endl;
+	    std::clog << "Writing new AutoInstall: " << pkg.FullName() << std::endl;
 	 ostr.str(string(""));
-	 ostr << "Package: " << pkg.Name() 
+	 ostr << "Package: " << pkg.Name()
+	      << "\nArchitecture: " << pkgarch
 	      << "\nAuto-Installed: 1\n\n";
 	 fprintf(OutFile,"%s",ostr.str().c_str());
-	 fprintf(OutFile,"\n");
       }
    }
    fclose(OutFile);
@@ -299,8 +339,7 @@ bool pkgDepCache::CheckDep(DepIterator Dep,int Type,PkgIterator &Res)
    /* Check simple depends. A depends -should- never self match but 
       we allow it anyhow because dpkg does. Technically it is a packaging
       bug. Conflicts may never self match */
-   if (Dep.TargetPkg() != Dep.ParentPkg() || 
-       (Dep->Type != Dep::Conflicts && Dep->Type != Dep::DpkgBreaks && Dep->Type != Dep::Obsoletes))
+   if (Dep.TargetPkg() != Dep.ParentPkg() || Dep.IsNegative() == false)
    {
       PkgIterator Pkg = Dep.TargetPkg();
       // Check the base package
@@ -326,12 +365,11 @@ bool pkgDepCache::CheckDep(DepIterator Dep,int Type,PkgIterator &Res)
    // Check the providing packages
    PrvIterator P = Dep.TargetPkg().ProvidesList();
    PkgIterator Pkg = Dep.ParentPkg();
-   for (; P.end() != true; P++)
+   for (; P.end() != true; ++P)
    {
-      /* Provides may never be applied against the same package if it is
-         a conflicts. See the comment above. */
-      if (P.OwnerPkg() == Pkg &&
-	  (Dep->Type == Dep::Conflicts || Dep->Type == Dep::DpkgBreaks))
+      /* Provides may never be applied against the same package (or group)
+         if it is a conflicts. See the comment above. */
+      if (P.OwnerPkg()->Group == Pkg->Group && Dep.IsNegative() == true)
 	 continue;
       
       // Check if the provides is a hit
@@ -368,8 +406,60 @@ bool pkgDepCache::CheckDep(DepIterator Dep,int Type,PkgIterator &Res)
 									/*}}}*/
 // DepCache::AddSizes - Add the packages sizes to the counters		/*{{{*/
 // ---------------------------------------------------------------------
-/* Call with Mult = -1 to preform the inverse opration */
-void pkgDepCache::AddSizes(const PkgIterator &Pkg,signed long Mult)
+/* Call with Mult = -1 to preform the inverse opration
+   The Mult increases the complexity of the calulations here and is unused -
+   or do we really have a usecase for removing the size of a package two
+   times? So let us replace it with a simple bool and be done with it… */
+__deprecated void pkgDepCache::AddSizes(const PkgIterator &Pkg,signed long Mult)
+{
+   StateCache &P = PkgState[Pkg->ID];
+   
+   if (Pkg->VersionList == 0)
+      return;
+   
+   if (Pkg.State() == pkgCache::PkgIterator::NeedsConfigure && 
+       P.Keep() == true)
+      return;
+   
+   // Compute the size data
+   if (P.NewInstall() == true)
+   {
+      iUsrSize += (signed long long)(Mult*P.InstVerIter(*this)->InstalledSize);
+      iDownloadSize += (signed long long)(Mult*P.InstVerIter(*this)->Size);
+      return;
+   }
+   
+   // Upgrading
+   if (Pkg->CurrentVer != 0 && 
+       (P.InstallVer != (Version *)Pkg.CurrentVer() || 
+	(P.iFlags & ReInstall) == ReInstall) && P.InstallVer != 0)
+   {
+      iUsrSize += (signed long long)(Mult*((signed long long)P.InstVerIter(*this)->InstalledSize - 
+			(signed long long)Pkg.CurrentVer()->InstalledSize));
+      iDownloadSize += (signed long long)(Mult*P.InstVerIter(*this)->Size);
+      return;
+   }
+   
+   // Reinstall
+   if (Pkg.State() == pkgCache::PkgIterator::NeedsUnpack &&
+       P.Delete() == false)
+   {
+      iDownloadSize += (signed long long)(Mult*P.InstVerIter(*this)->Size);
+      return;
+   }
+   
+   // Removing
+   if (Pkg->CurrentVer != 0 && P.InstallVer == 0)
+   {
+      iUsrSize -= (signed long long)(Mult*Pkg.CurrentVer()->InstalledSize);
+      return;
+   }   
+}
+									/*}}}*/
+// DepCache::AddSizes - Add the packages sizes to the counters		/*{{{*/
+// ---------------------------------------------------------------------
+/* Call with Inverse = true to preform the inverse opration */
+void pkgDepCache::AddSizes(const PkgIterator &Pkg, bool const &Inverse)
 {
    StateCache &P = PkgState[Pkg->ID];
    
@@ -383,8 +473,13 @@ void pkgDepCache::AddSizes(const PkgIterator &Pkg,signed long Mult)
    // Compute the size data
    if (P.NewInstall() == true)
    {
-      iUsrSize += (signed)(Mult*P.InstVerIter(*this)->InstalledSize);
-      iDownloadSize += (signed)(Mult*P.InstVerIter(*this)->Size);
+      if (Inverse == false) {
+	 iUsrSize += P.InstVerIter(*this)->InstalledSize;
+	 iDownloadSize += P.InstVerIter(*this)->Size;
+      } else {
+	 iUsrSize -= P.InstVerIter(*this)->InstalledSize;
+	 iDownloadSize -= P.InstVerIter(*this)->Size;
+      }
       return;
    }
    
@@ -393,9 +488,15 @@ void pkgDepCache::AddSizes(const PkgIterator &Pkg,signed long Mult)
        (P.InstallVer != (Version *)Pkg.CurrentVer() || 
 	(P.iFlags & ReInstall) == ReInstall) && P.InstallVer != 0)
    {
-      iUsrSize += (signed)(Mult*((signed)P.InstVerIter(*this)->InstalledSize - 
-			(signed)Pkg.CurrentVer()->InstalledSize));
-      iDownloadSize += (signed)(Mult*P.InstVerIter(*this)->Size);
+      if (Inverse == false) {
+	 iUsrSize -= Pkg.CurrentVer()->InstalledSize;
+	 iUsrSize += P.InstVerIter(*this)->InstalledSize;
+	 iDownloadSize += P.InstVerIter(*this)->Size;
+      } else {
+	 iUsrSize -= P.InstVerIter(*this)->InstalledSize;
+	 iUsrSize += Pkg.CurrentVer()->InstalledSize;
+	 iDownloadSize -= P.InstVerIter(*this)->Size;
+      }
       return;
    }
    
@@ -403,14 +504,20 @@ void pkgDepCache::AddSizes(const PkgIterator &Pkg,signed long Mult)
    if (Pkg.State() == pkgCache::PkgIterator::NeedsUnpack &&
        P.Delete() == false)
    {
-      iDownloadSize += (signed)(Mult*P.InstVerIter(*this)->Size);
+      if (Inverse == false)
+	 iDownloadSize += P.InstVerIter(*this)->Size;
+      else
+	 iDownloadSize -= P.InstVerIter(*this)->Size;
       return;
    }
    
    // Removing
    if (Pkg->CurrentVer != 0 && P.InstallVer == 0)
    {
-      iUsrSize -= (signed)(Mult*Pkg.CurrentVer()->InstalledSize);
+      if (Inverse == false)
+	 iUsrSize -= Pkg.CurrentVer()->InstalledSize;
+      else
+	 iUsrSize += Pkg.CurrentVer()->InstalledSize;
       return;
    }   
 }
@@ -440,8 +547,8 @@ void pkgDepCache::AddStates(const PkgIterator &Pkg,int Add)
    // Not installed
    if (Pkg->CurrentVer == 0)
    {
-      if (State.Mode == ModeDelete && 
-	  (State.iFlags | Purge) == Purge && Pkg.Purge() == false)
+      if (State.Mode == ModeDelete &&
+	  (State.iFlags & Purge) == Purge && Pkg.Purge() == false)
 	 iDelCount += Add;
       
       if (State.Mode == ModeInstall)
@@ -478,16 +585,14 @@ void pkgDepCache::BuildGroupOrs(VerIterator const &V)
 {
    unsigned char Group = 0;
    
-   for (DepIterator D = V.DependsList(); D.end() != true; D++)
+   for (DepIterator D = V.DependsList(); D.end() != true; ++D)
    {
       // Build the dependency state.
       unsigned char &State = DepState[D->ID];
 
       /* Invert for Conflicts. We have to do this twice to get the
          right sense for a conflicts group */
-      if (D->Type == Dep::Conflicts ||
-	  D->Type == Dep::DpkgBreaks ||
-	  D->Type == Dep::Obsoletes)
+      if (D.IsNegative() == true)
 	 State = ~State;
       
       // Add to the group if we are within an or..
@@ -498,9 +603,7 @@ void pkgDepCache::BuildGroupOrs(VerIterator const &V)
 	 Group = 0;
       
       // Invert for Conflicts
-      if (D->Type == Dep::Conflicts ||
-	  D->Type == Dep::DpkgBreaks ||
-	  D->Type == Dep::Obsoletes)
+      if (D.IsNegative() == true)
 	 State = ~State;
    }	 
 }
@@ -522,7 +625,7 @@ unsigned char pkgDepCache::VersionState(DepIterator D,unsigned char Check,
       // Compute a single dependency element (glob or)
       DepIterator Start = D;
       unsigned char State = 0;
-      for (bool LastOR = true; D.end() == false && LastOR == true; D++)
+      for (bool LastOR = true; D.end() == false && LastOR == true; ++D)
       {
 	 State |= DepState[D->ID];
 	 LastOR = (D->CompareOp & Dep::Or) == Dep::Or;
@@ -609,18 +712,18 @@ void pkgDepCache::Update(OpProgress *Prog)
    iKeepCount = 0;
    iBrokenCount = 0;
    iBadCount = 0;
-   
+
    // Perform the depends pass
    int Done = 0;
-   for (PkgIterator I = PkgBegin(); I.end() != true; I++,Done++)
+   for (PkgIterator I = PkgBegin(); I.end() != true; ++I, ++Done)
    {
       if (Prog != 0 && Done%20 == 0)
 	 Prog->Progress(Done);
-      for (VerIterator V = I.VersionList(); V.end() != true; V++)
+      for (VerIterator V = I.VersionList(); V.end() != true; ++V)
       {
 	 unsigned char Group = 0;
-	 
-	 for (DepIterator D = V.DependsList(); D.end() != true; D++)
+
+	 for (DepIterator D = V.DependsList(); D.end() != true; ++D)
 	 {
 	    // Build the dependency state.
 	    unsigned char &State = DepState[D->ID];
@@ -633,20 +736,18 @@ void pkgDepCache::Update(OpProgress *Prog)
 	       Group = 0;
 
 	    // Invert for Conflicts
-	    if (D->Type == Dep::Conflicts ||
-		D->Type == Dep::DpkgBreaks ||
-		D->Type == Dep::Obsoletes)
+	    if (D.IsNegative() == true)
 	       State = ~State;
-	 }	 
+	 }
       }
 
-      // Compute the pacakge dependency state and size additions
+      // Compute the package dependency state and size additions
       AddSizes(I);
       UpdateVerState(I);
       AddStates(I);
    }
 
-   if (Prog != 0)      
+   if (Prog != 0)
       Prog->Progress(Done);
 
    readStateFile(Prog);
@@ -659,15 +760,13 @@ void pkgDepCache::Update(OpProgress *Prog)
 void pkgDepCache::Update(DepIterator D)
 {
    // Update the reverse deps
-   for (;D.end() != true; D++)
+   for (;D.end() != true; ++D)
    {      
       unsigned char &State = DepState[D->ID];
       State = DependencyState(D);
     
       // Invert for Conflicts
-      if (D->Type == Dep::Conflicts ||
-	  D->Type == Dep::DpkgBreaks ||
-	  D->Type == Dep::Obsoletes)
+      if (D.IsNegative() == true)
 	 State = ~State;
 
       RemoveStates(D.ParentPkg());
@@ -694,13 +793,13 @@ void pkgDepCache::Update(PkgIterator const &Pkg)
    // Update the provides map for the current ver
    if (Pkg->CurrentVer != 0)
       for (PrvIterator P = Pkg.CurrentVer().ProvidesList(); 
-	   P.end() != true; P++)
+	   P.end() != true; ++P)
 	 Update(P.ParentPkg().RevDependsList());
 
    // Update the provides map for the candidate ver
    if (PkgState[Pkg->ID].CandidateVer != 0)
       for (PrvIterator P = PkgState[Pkg->ID].CandidateVerIter(*this).ProvidesList();
-	   P.end() != true; P++)
+	   P.end() != true; ++P)
 	 Update(P.ParentPkg().RevDependsList());
 }
 									/*}}}*/
@@ -710,8 +809,7 @@ void pkgDepCache::Update(PkgIterator const &Pkg)
 void pkgDepCache::MarkKeep(PkgIterator const &Pkg, bool Soft, bool FromUser,
                            unsigned long Depth)
 {
-   // Simplifies other routines.
-   if (Pkg.end() == true)
+   if (IsModeChangeOk(ModeKeep, Pkg, Depth, FromUser) == false)
       return;
 
    /* Reject an attempt to keep a non-source broken installed package, those
@@ -719,25 +817,22 @@ void pkgDepCache::MarkKeep(PkgIterator const &Pkg, bool Soft, bool FromUser,
    if (Pkg.State() == PkgIterator::NeedsUnpack && 
        Pkg.CurrentVer().Downloadable() == false)
       return;
-   
-   /** \todo Can this be moved later in the method? */
-   ActionGroup group(*this);
 
    /* We changed the soft state all the time so the UI is a bit nicer
       to use */
    StateCache &P = PkgState[Pkg->ID];
+
+   // Check that it is not already kept
+   if (P.Mode == ModeKeep)
+      return;
+
    if (Soft == true)
       P.iFlags |= AutoKept;
    else
       P.iFlags &= ~AutoKept;
-   
-   // Check that it is not already kept
-   if (P.Mode == ModeKeep)
-      return;
 
-   // We dont even try to keep virtual packages..
-   if (Pkg->VersionList == 0)
-      return;
+   ActionGroup group(*this);
+
 #if 0 // reseting the autoflag here means we lose the 
       // auto-mark information if a user selects a package for removal
       // but changes  his mind then and sets it for keep again
@@ -774,32 +869,28 @@ void pkgDepCache::MarkKeep(PkgIterator const &Pkg, bool Soft, bool FromUser,
 void pkgDepCache::MarkDelete(PkgIterator const &Pkg, bool rPurge,
                              unsigned long Depth, bool FromUser)
 {
-   // Simplifies other routines.
-   if (Pkg.end() == true)
+   if (IsModeChangeOk(ModeDelete, Pkg, Depth, FromUser) == false)
       return;
 
-   ActionGroup group(*this);
+   StateCache &P = PkgState[Pkg->ID];
 
    // Check that it is not already marked for delete
-   StateCache &P = PkgState[Pkg->ID];
-   P.iFlags &= ~(AutoKept | Purge);
-   if (rPurge == true)
-      P.iFlags |= Purge;
-   
    if ((P.Mode == ModeDelete || P.InstallVer == 0) && 
        (Pkg.Purge() == true || rPurge == false))
       return;
-   
-   // We dont even try to delete virtual packages..
-   if (Pkg->VersionList == 0)
-      return;
 
-   // check if we are allowed to install the package
+   // check if we are allowed to remove the package
    if (IsDeleteOk(Pkg,rPurge,Depth,FromUser) == false)
       return;
 
+   P.iFlags &= ~(AutoKept | Purge);
+   if (rPurge == true)
+      P.iFlags |= Purge;
+
+   ActionGroup group(*this);
+
    if (DebugMarker == true)
-      std::clog << OutputInDepth(Depth) << "MarkDelete " << Pkg << " FU=" << FromUser << std::endl;
+      std::clog << OutputInDepth(Depth) << (rPurge ? "MarkPurge " : "MarkDelete ") << Pkg << " FU=" << FromUser << std::endl;
 
    RemoveSizes(Pkg);
    RemoveStates(Pkg);
@@ -813,22 +904,81 @@ void pkgDepCache::MarkDelete(PkgIterator const &Pkg, bool rPurge,
    AddStates(Pkg);   
    Update(Pkg);
    AddSizes(Pkg);
+
 }
 									/*}}}*/
 // DepCache::IsDeleteOk - check if it is ok to remove this package	/*{{{*/
 // ---------------------------------------------------------------------
-/* The default implementation just honors dpkg hold
-   But an application using this library can override this method
-   to control the MarkDelete behaviour */
+/* The default implementation tries to prevent deletion of install requests.
+   dpkg holds are enforced by the private IsModeChangeOk */
 bool pkgDepCache::IsDeleteOk(PkgIterator const &Pkg,bool rPurge,
 			      unsigned long Depth, bool FromUser)
 {
-   if (FromUser == false && Pkg->SelectedState == pkgCache::State::Hold && _config->FindB("APT::Ignore-Hold",false) == false)
+   if (FromUser == false && Pkg->CurrentVer == 0)
    {
-      if (DebugMarker == true)
-	 std::clog << OutputInDepth(Depth) << "Hold prevents MarkDelete of " << Pkg << " FU=" << FromUser << std::endl;
+      StateCache &P = PkgState[Pkg->ID];
+      if (P.InstallVer != 0 && P.Status == 2 && (P.Flags & Flag::Auto) != Flag::Auto)
+      {
+	 if (DebugMarker == true)
+	    std::clog << OutputInDepth(Depth) << "Manual install request prevents MarkDelete of " << Pkg << std::endl;
+	 return false;
+      }
+   }
+   return true;
+}
+									/*}}}*/
+// DepCache::IsModeChangeOk - check if it is ok to change the mode	/*{{{*/
+// ---------------------------------------------------------------------
+/* this is used by all Mark methods on the very first line to check sanity
+   and prevents mode changes for packages on hold for example.
+   If you want to check Mode specific stuff you can use the virtual public
+   Is<Mode>Ok methods instead */
+char const* PrintMode(char const mode)
+{
+	 switch (mode)
+	 {
+	 case pkgDepCache::ModeInstall: return "Install";
+	 case pkgDepCache::ModeKeep: return "Keep";
+	 case pkgDepCache::ModeDelete: return "Delete";
+	 default: return "UNKNOWN";
+	 }
+}
+bool pkgDepCache::IsModeChangeOk(ModeList const mode, PkgIterator const &Pkg,
+				 unsigned long const Depth, bool const FromUser)
+{
+   // we are not trying to hard…
+   if (unlikely(Depth > 100))
+      return false;
+
+   // general sanity
+   if (unlikely(Pkg.end() == true || Pkg->VersionList == 0))
+      return false;
+
+   // the user is always right
+   if (FromUser == true)
+      return true;
+
+   StateCache &P = PkgState[Pkg->ID];
+
+   // if previous state was set by user only user can reset it
+   if ((P.iFlags & Protected) == Protected)
+   {
+      if (unlikely(DebugMarker == true) && P.Mode != mode)
+	 std::clog << OutputInDepth(Depth) << "Ignore Mark" << PrintMode(mode)
+		   << " of " << Pkg << " as its mode (" << PrintMode(P.Mode)
+		   << ") is protected" << std::endl;
       return false;
    }
+   // enforce dpkg holds
+   else if (mode != ModeKeep && Pkg->SelectedState == pkgCache::State::Hold &&
+	    _config->FindB("APT::Ignore-Hold",false) == false)
+   {
+      if (unlikely(DebugMarker == true) && P.Mode != mode)
+	 std::clog << OutputInDepth(Depth) << "Hold prevents Mark" << PrintMode(mode)
+		   << " of " << Pkg << std::endl;
+      return false;
+   }
+
    return true;
 }
 									/*}}}*/
@@ -839,19 +989,17 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
 			      unsigned long Depth, bool FromUser,
 			      bool ForceImportantDeps)
 {
-   if (Depth > 100)
+   if (IsModeChangeOk(ModeInstall, Pkg, Depth, FromUser) == false)
       return;
-   
-   // Simplifies other routines.
-   if (Pkg.end() == true)
+
+   StateCache &P = PkgState[Pkg->ID];
+
+   // See if there is even any possible instalation candidate
+   if (P.CandidateVer == 0)
       return;
-   
-   ActionGroup group(*this);
 
    /* Check that it is not already marked for install and that it can be 
       installed */
-   StateCache &P = PkgState[Pkg->ID];
-   P.iFlags &= ~AutoKept;
    if ((P.InstPolicyBroken() == false && P.InstBroken() == false) && 
        (P.Mode == ModeInstall ||
 	P.CandidateVer == (Version *)Pkg.CurrentVer()))
@@ -861,17 +1009,13 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
       return;
    }
 
-   // See if there is even any possible instalation candidate
-   if (P.CandidateVer == 0)
-      return;
-   // We dont even try to install virtual packages..
-   if (Pkg->VersionList == 0)
-      return;
-
    // check if we are allowed to install the package
    if (IsInstallOk(Pkg,AutoInst,Depth,FromUser) == false)
       return;
 
+   ActionGroup group(*this);
+   P.iFlags &= ~AutoKept;
+
    /* Target the candidate version and remove the autoflag. We reset the
       autoflag below if this was called recursively. Otherwise the user
       should have the ability to de-auto a package by changing its state */
@@ -883,9 +1027,10 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
 
    if(FromUser)
      {
-       // Set it to manual if it's a new install or cancelling the
-       // removal of a garbage package.
-       if(P.Status == 2 || (!Pkg.CurrentVer().end() && !P.Marked))
+       // Set it to manual if it's a new install or already installed,
+       // but only if its not marked by the autoremover (aptitude depend on this behavior)
+       // or if we do automatic installation (aptitude never does it)
+       if(P.Status == 2 || (Pkg->CurrentVer != 0 && (AutoInst == true || P.Marked == false)))
 	 P.Flags &= ~Flag::Auto;
      }
    else
@@ -914,7 +1059,7 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
       DepIterator Start = Dep;
       bool Result = true;
       unsigned Ors = 0;
-      for (bool LastOR = true; Dep.end() == false && LastOR == true; Dep++,Ors++)
+      for (bool LastOR = true; Dep.end() == false && LastOR == true; ++Dep, ++Ors)
       {
 	 LastOR = (Dep->CompareOp & Dep::Or) == Dep::Or;
 
@@ -933,7 +1078,22 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
       */
       if (IsImportantDep(Start) == false)
 	 continue;
-      
+
+      /* If we are in an or group locate the first or that can 
+         succeed. We have already cached this.. */
+      for (; Ors > 1 && (DepState[Start->ID] & DepCVer) != DepCVer; --Ors)
+	 ++Start;
+      if (Ors == 1 && (DepState[Start->ID] &DepCVer) != DepCVer && Start.IsNegative() == false)
+      {
+	 if(DebugAutoInstall == true)
+	    std::clog << OutputInDepth(Depth) << Start << " can't be satisfied!" << std::endl;
+	 if (Start.IsCritical() == false)
+	    continue;
+	 // if the dependency was critical, we can't install it, so remove it again
+	 MarkDelete(Pkg,false,Depth + 1, false);
+	 return;
+      }
+
       /* Check if any ImportantDep() (but not Critical) were added
        * since we installed the package.  Also check for deps that
        * were satisfied in the past: for instance, if a version
@@ -941,59 +1101,49 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
        * package should follow that Recommends rather than causing the
        * dependency to be removed. (bug #470115)
        */
-      bool isNewImportantDep = false;
-      bool isPreviouslySatisfiedImportantDep = false;
-      if(!ForceImportantDeps && !Start.IsCritical())
+      if (Pkg->CurrentVer != 0 && ForceImportantDeps == false && Start.IsCritical() == false)
       {
-	 bool found=false;
-	 VerIterator instVer = Pkg.CurrentVer();
-	 if(!instVer.end())
+	 bool isNewImportantDep = true;
+	 bool isPreviouslySatisfiedImportantDep = false;
+	 for (DepIterator D = Pkg.CurrentVer().DependsList(); D.end() != true; ++D)
 	 {
-	   for (DepIterator D = instVer.DependsList(); D.end() != true; D++)
-	     {
-	       //FIXME: deal better with or-groups(?)
-	       DepIterator LocalStart = D;
-
-	       if(IsImportantDep(D) && !D.IsCritical() &&
-		  Start.TargetPkg() == D.TargetPkg())
-		 {
-		   if(!isPreviouslySatisfiedImportantDep)
-		     {
-		       DepIterator D2 = D;
-		       while((D2->CompareOp & Dep::Or) != 0)
-			 ++D2;
-
-		       isPreviouslySatisfiedImportantDep =
-			 (((*this)[D2] & DepGNow) != 0);
-		     }
-
-		   found=true;
-		 }
-	     }
-	    // this is a new dep if it was not found to be already
-	    // a important dep of the installed pacakge
-	    isNewImportantDep = !found;
+	    //FIXME: Should we handle or-group better here?
+	    // We do not check if the package we look for is part of the same or-group
+	    // we might find while searching, but could that really be a problem?
+	    if (D.IsCritical() == true || IsImportantDep(D) == false ||
+		Start.TargetPkg() != D.TargetPkg())
+	       continue;
+
+	    isNewImportantDep = false;
+
+	    while ((D->CompareOp & Dep::Or) != 0)
+	       ++D;
+
+	    isPreviouslySatisfiedImportantDep = (((*this)[D] & DepGNow) != 0);
+	    if (isPreviouslySatisfiedImportantDep == true)
+	       break;
+	 }
+
+	 if(isNewImportantDep == true)
+	 {
+	    if (DebugAutoInstall == true)
+	       std::clog << OutputInDepth(Depth) << "new important dependency: "
+			 << Start.TargetPkg().FullName() << std::endl;
+	 }
+	 else if(isPreviouslySatisfiedImportantDep == true)
+	 {
+	    if (DebugAutoInstall == true)
+	       std::clog << OutputInDepth(Depth) << "previously satisfied important dependency on "
+			 << Start.TargetPkg().FullName() << std::endl;
+	 }
+	 else
+	 {
+	    if (DebugAutoInstall == true)
+	       std::clog << OutputInDepth(Depth) << "ignore old unsatisfied important dependency on "
+			 << Start.TargetPkg().FullName() << std::endl;
+	    continue;
 	 }
       }
-      if(isNewImportantDep)
-	 if(DebugAutoInstall == true)
-	    std::clog << OutputInDepth(Depth) << "new important dependency: "
-		      << Start.TargetPkg().Name() << std::endl;
-      if(isPreviouslySatisfiedImportantDep)
-	if(DebugAutoInstall == true)
-	  std::clog << OutputInDepth(Depth) << "previously satisfied important dependency on "
-		    << Start.TargetPkg().Name() << std::endl;
-
-      // skip important deps if the package is already installed
-      if (Pkg->CurrentVer != 0 && Start.IsCritical() == false 
-	  && !isNewImportantDep && !isPreviouslySatisfiedImportantDep
-	  && !ForceImportantDeps)
-	 continue;
-      
-      /* If we are in an or group locate the first or that can 
-         succeed. We have already cached this.. */
-      for (; Ors > 1 && (DepState[Start->ID] & DepCVer) != DepCVer; Ors--)
-	 Start++;
 
       /* This bit is for processing the possibilty of an install/upgrade
          fixing the problem */
@@ -1059,18 +1209,23 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
       /* For conflicts we just de-install the package and mark as auto,
          Conflicts may not have or groups.  For dpkg's Breaks we try to
          upgrade the package. */
-      if (Start->Type == Dep::Conflicts || Start->Type == Dep::Obsoletes ||
-	  Start->Type == Dep::DpkgBreaks)
+      if (Start.IsNegative() == true)
       {
 	 for (Version **I = List; *I != 0; I++)
 	 {
 	    VerIterator Ver(*this,*I);
 	    PkgIterator Pkg = Ver.ParentPkg();
 
-	    if (Start->Type != Dep::DpkgBreaks)
-	       MarkDelete(Pkg,false,Depth + 1, false);
-	    else if (PkgState[Pkg->ID].CandidateVer != *I)
+	    /* The List includes all packages providing this dependency,
+	       even providers which are not installed, so skip them. */
+	    if (PkgState[Pkg->ID].InstallVer == 0)
+	       continue;
+
+	    if (PkgState[Pkg->ID].CandidateVer != *I &&
+	        Start->Type == Dep::DpkgBreaks)
 	       MarkInstall(Pkg,true,Depth + 1, false, ForceImportantDeps);
+	    else
+	       MarkDelete(Pkg,false,Depth + 1, false);
 	 }
 	 continue;
       }      
@@ -1079,18 +1234,11 @@ void pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
 									/*}}}*/
 // DepCache::IsInstallOk - check if it is ok to install this package	/*{{{*/
 // ---------------------------------------------------------------------
-/* The default implementation just honors dpkg hold
-   But an application using this library can override this method
-   to control the MarkInstall behaviour */
+/* The default implementation does nothing.
+   dpkg holds are enforced by the private IsModeChangeOk */
 bool pkgDepCache::IsInstallOk(PkgIterator const &Pkg,bool AutoInst,
 			      unsigned long Depth, bool FromUser)
 {
-   if (FromUser == false && Pkg->SelectedState == pkgCache::State::Hold && _config->FindB("APT::Ignore-Hold",false) == false)
-   {
-      if (DebugMarker == true)
-	 std::clog << OutputInDepth(Depth) << "Hold prevents MarkInstall of " << Pkg << " FU=" << FromUser << std::endl;
-      return false;
-   }
    return true;
 }
 									/*}}}*/
@@ -1099,6 +1247,9 @@ bool pkgDepCache::IsInstallOk(PkgIterator const &Pkg,bool AutoInst,
 /* */
 void pkgDepCache::SetReInstall(PkgIterator const &Pkg,bool To)
 {
+   if (unlikely(Pkg.end() == true))
+      return;
+
    ActionGroup group(*this);
 
    RemoveSizes(Pkg);
@@ -1117,17 +1268,20 @@ void pkgDepCache::SetReInstall(PkgIterator const &Pkg,bool To)
 // DepCache::SetCandidateVersion - Change the candidate version		/*{{{*/
 // ---------------------------------------------------------------------
 /* */
-void pkgDepCache::SetCandidateVersion(VerIterator TargetVer)
+void pkgDepCache::SetCandidateVersion(VerIterator TargetVer, bool const &Pseudo)
 {
-   ActionGroup group(*this);
-
    pkgCache::PkgIterator Pkg = TargetVer.ParentPkg();
    StateCache &P = PkgState[Pkg->ID];
 
+   if (P.CandidateVer == TargetVer)
+      return;
+
+   ActionGroup group(*this);
+
    RemoveSizes(Pkg);
    RemoveStates(Pkg);
 
-   if (P.CandidateVer == P.InstallVer)
+   if (P.CandidateVer == P.InstallVer && P.Install() == true)
       P.InstallVer = (Version *)TargetVer;
    P.CandidateVer = (Version *)TargetVer;
    P.Update(Pkg,*this);
@@ -1135,8 +1289,173 @@ void pkgDepCache::SetCandidateVersion(VerIterator TargetVer)
    AddStates(Pkg);
    Update(Pkg);
    AddSizes(Pkg);
+
 }
+									/*}}}*/
+// DepCache::SetCandidateRelease - Change the candidate version		/*{{{*/
+// ---------------------------------------------------------------------
+/* changes the candidate of a package and walks over all its dependencies
+   to check if it needs to change the candidate of the dependency, too,
+   to reach a installable versionstate */
+bool pkgDepCache::SetCandidateRelease(pkgCache::VerIterator TargetVer,
+					std::string const &TargetRel)
+{
+   std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> > Changed;
+   return SetCandidateRelease(TargetVer, TargetRel, Changed);
+}
+bool pkgDepCache::SetCandidateRelease(pkgCache::VerIterator TargetVer,
+					std::string const &TargetRel,
+					std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> > &Changed)
+{
+   ActionGroup group(*this);
+   SetCandidateVersion(TargetVer);
+
+   if (TargetRel == "installed" || TargetRel == "candidate") // both doesn't make sense in this context
+      return true;
+
+   pkgVersionMatch Match(TargetRel, pkgVersionMatch::Release);
+   // save the position of the last element we will not undo - if we have to
+   std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> >::iterator newChanged = --(Changed.end());
+
+   for (pkgCache::DepIterator D = TargetVer.DependsList(); D.end() == false; ++D)
+   {
+      if (D->Type != pkgCache::Dep::PreDepends && D->Type != pkgCache::Dep::Depends &&
+	  ((D->Type != pkgCache::Dep::Recommends && D->Type != pkgCache::Dep::Suggests) ||
+	   IsImportantDep(D) == false))
+	 continue;
+
+      // walk over an or-group and check if we need to do anything
+      // for simpilicity no or-group is handled as a or-group including one dependency
+      pkgCache::DepIterator Start = D;
+      bool itsFine = false;
+      for (bool stillOr = true; stillOr == true; ++Start)
+      {
+	 stillOr = (Start->CompareOp & Dep::Or) == Dep::Or;
+	 pkgCache::PkgIterator const P = Start.TargetPkg();
+	 // virtual packages can't be a solution
+	 if (P.end() == true || (P->ProvidesList == 0 && P->VersionList == 0))
+	    continue;
+	 pkgCache::VerIterator const Cand = PkgState[P->ID].CandidateVerIter(*this);
+	 // no versioned dependency - but is it installable?
+	 if (Start.TargetVer() == 0 || Start.TargetVer()[0] == '\0')
+	 {
+	    // Check if one of the providers is installable
+	    if (P->ProvidesList != 0)
+	    {
+	       pkgCache::PrvIterator Prv = P.ProvidesList();
+	       for (; Prv.end() == false; ++Prv)
+	       {
+		  pkgCache::VerIterator const C = PkgState[Prv.OwnerPkg()->ID].CandidateVerIter(*this);
+		  if (C.end() == true || C != Prv.OwnerVer() ||
+		      (VersionState(C.DependsList(), DepInstall, DepCandMin, DepCandPolicy) & DepCandMin) != DepCandMin)
+		     continue;
+		  break;
+	       }
+	       if (Prv.end() == true)
+		  continue;
+	    }
+	    // no providers, so check if we have an installable candidate version
+	    else if (Cand.end() == true ||
+		(VersionState(Cand.DependsList(), DepInstall, DepCandMin, DepCandPolicy) & DepCandMin) != DepCandMin)
+	       continue;
+	    itsFine = true;
+	    break;
+	 }
+	 if (Cand.end() == true)
+	    continue;
+	 // check if the current candidate is enough for the versioned dependency - and installable?
+	 if (VS().CheckDep(P.CandVersion(), Start->CompareOp, Start.TargetVer()) == true &&
+	     (VersionState(Cand.DependsList(), DepInstall, DepCandMin, DepCandPolicy) & DepCandMin) == DepCandMin)
+	 {
+	    itsFine = true;
+	    break;
+	 }
+      }
+
+      if (itsFine == true) {
+	 // something in the or-group was fine, skip all other members
+	 for (; (D->CompareOp & Dep::Or) == Dep::Or; ++D);
+	 continue;
+      }
+
+      // walk again over the or-group and check each if a candidate switch would help
+      itsFine = false;
+      for (bool stillOr = true; stillOr == true; ++D)
+      {
+	 stillOr = (D->CompareOp & Dep::Or) == Dep::Or;
+	 // changing candidate will not help if the dependency is not versioned
+	 if (D.TargetVer() == 0 || D.TargetVer()[0] == '\0')
+	 {
+	    if (stillOr == true)
+	       continue;
+	    break;
+	 }
+
+	 pkgCache::VerIterator V;
+	 if (TargetRel == "newest")
+	    V = D.TargetPkg().VersionList();
+	 else
+	    V = Match.Find(D.TargetPkg());
+
+	 // check if the version from this release could satisfy the dependency
+	 if (V.end() == true || VS().CheckDep(V.VerStr(), D->CompareOp, D.TargetVer()) == false)
+	 {
+	    if (stillOr == true)
+	       continue;
+	    break;
+	 }
 
+	 pkgCache::VerIterator oldCand = PkgState[D.TargetPkg()->ID].CandidateVerIter(*this);
+	 if (V == oldCand)
+	 {
+	    // Do we already touched this Version? If so, their versioned dependencies are okay, no need to check again
+	    for (std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> >::const_iterator c = Changed.begin();
+		 c != Changed.end(); ++c)
+	    {
+	       if (c->first->ParentPkg != V->ParentPkg)
+		  continue;
+	       itsFine = true;
+	       break;
+	    }
+	 }
+
+	 if (itsFine == false)
+	 {
+	    // change the candidate
+	    Changed.push_back(make_pair(oldCand, TargetVer));
+	    if (SetCandidateRelease(V, TargetRel, Changed) == false)
+	    {
+	       if (stillOr == false)
+		  break;
+	       // undo the candidate changing
+	       SetCandidateVersion(oldCand);
+	       Changed.pop_back();
+	       continue;
+	    }
+	    itsFine = true;
+	 }
+
+	 // something in the or-group was fine, skip all other members
+	 for (; (D->CompareOp & Dep::Or) == Dep::Or; ++D);
+	 break;
+      }
+
+      if (itsFine == false && (D->Type == pkgCache::Dep::PreDepends || D->Type == pkgCache::Dep::Depends))
+      {
+	 // undo all changes which aren't lead to a solution
+	 for (std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> >::const_iterator c = ++newChanged;
+	      c != Changed.end(); ++c)
+	    SetCandidateVersion(c->first);
+	 Changed.erase(newChanged, Changed.end());
+	 return false;
+      }
+   }
+   return true;
+}
+									/*}}}*/
+// DepCache::MarkAuto - set the Auto flag for a package			/*{{{*/
+// ---------------------------------------------------------------------
+/* */
 void pkgDepCache::MarkAuto(const PkgIterator &Pkg, bool Auto)
 {
   StateCache &state = PkgState[Pkg->ID];
@@ -1197,25 +1516,26 @@ const char *pkgDepCache::StateCache::StripEpoch(const char *Ver)
 // ---------------------------------------------------------------------
 /* The default just returns the highest available version that is not
    a source and automatic. */
-pkgCache::VerIterator pkgDepCache::Policy::GetCandidateVer(PkgIterator Pkg)
+pkgCache::VerIterator pkgDepCache::Policy::GetCandidateVer(PkgIterator const &Pkg)
 {
    /* Not source/not automatic versions cannot be a candidate version 
       unless they are already installed */
    VerIterator Last(*(pkgCache *)this,0);
    
-   for (VerIterator I = Pkg.VersionList(); I.end() == false; I++)
+   for (VerIterator I = Pkg.VersionList(); I.end() == false; ++I)
    {
       if (Pkg.CurrentVer() == I)
 	 return I;
       
-      for (VerFileIterator J = I.FileList(); J.end() == false; J++)
+      for (VerFileIterator J = I.FileList(); J.end() == false; ++J)
       {
 	 if ((J.File()->Flags & Flag::NotSource) != 0)
 	    continue;
 
 	 /* Stash the highest version of a not-automatic source, we use it
 	    if there is nothing better */
-	 if ((J.File()->Flags & Flag::NotAutomatic) != 0)
+	 if ((J.File()->Flags & Flag::NotAutomatic) != 0 ||
+	     (J.File()->Flags & Flag::ButAutomaticUpgrades) != 0)
 	 {
 	    if (Last.end() == true)
 	       Last = I;
@@ -1232,7 +1552,7 @@ pkgCache::VerIterator pkgDepCache::Policy::GetCandidateVer(PkgIterator Pkg)
 // Policy::IsImportantDep - True if the dependency is important		/*{{{*/
 // ---------------------------------------------------------------------
 /* */
-bool pkgDepCache::Policy::IsImportantDep(DepIterator Dep)
+bool pkgDepCache::Policy::IsImportantDep(DepIterator const &Dep)
 {
    if(Dep.IsCritical())
       return true;
@@ -1251,54 +1571,6 @@ bool pkgDepCache::Policy::IsImportantDep(DepIterator Dep)
    else if(Dep->Type == pkgCache::Dep::Suggests)
      return _config->FindB("APT::Install-Suggests", false);
 
-   return false;
-}
-									/*}}}*/
-pkgDepCache::DefaultRootSetFunc::DefaultRootSetFunc()			/*{{{*/
-  : constructedSuccessfully(false)
-{
-  Configuration::Item const *Opts;
-  Opts = _config->Tree("APT::NeverAutoRemove");
-  if (Opts != 0 && Opts->Child != 0)
-    {
-      Opts = Opts->Child;
-      for (; Opts != 0; Opts = Opts->Next)
-	{
-	  if (Opts->Value.empty() == true)
-	    continue;
-
-	  regex_t *p = new regex_t;
-	  if(regcomp(p,Opts->Value.c_str(),
-		     REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0)
-	    {
-	      regfree(p);
-	      delete p;
-	      _error->Error("Regex compilation error for APT::NeverAutoRemove");
-	      return;
-	    }
-
-	  rootSetRegexp.push_back(p);
-	}
-    }
-
-  constructedSuccessfully = true;
-}
-									/*}}}*/
-pkgDepCache::DefaultRootSetFunc::~DefaultRootSetFunc()			/*{{{*/
-{
-  for(unsigned int i = 0; i < rootSetRegexp.size(); i++)
-    {
-      regfree(rootSetRegexp[i]);
-      delete rootSetRegexp[i];
-    }
-}
-									/*}}}*/
-bool pkgDepCache::DefaultRootSetFunc::InRootSet(const pkgCache::PkgIterator &pkg) /*{{{*/
-{
-   for(unsigned int i = 0; i < rootSetRegexp.size(); i++)
-      if (regexec(rootSetRegexp[i], pkg.Name(), 0, 0, 0) == 0)
-	 return true;
-
    return false;
 }
 									/*}}}*/
@@ -1321,7 +1593,7 @@ bool pkgDepCache::MarkFollowsRecommends()
 
 bool pkgDepCache::MarkFollowsSuggests()
 {
-  return _config->FindB("APT::AutoRemove::SuggestsImportant", false);
+  return _config->FindB("APT::AutoRemove::SuggestsImportant", true);
 }
 
 // pkgDepCache::MarkRequired - the main mark algorithm			/*{{{*/
@@ -1339,7 +1611,7 @@ bool pkgDepCache::MarkRequired(InRootSetFunc &userFunc)
 
       // debug output
       if(debug_autoremove && PkgState[p->ID].Flags & Flag::Auto)
-  	 std::clog << "AutoDep: " << p.Name() << std::endl;
+  	 std::clog << "AutoDep: " << p.FullName() << std::endl;
    }
 
    // init vars
@@ -1353,8 +1625,11 @@ bool pkgDepCache::MarkRequired(InRootSetFunc &userFunc)
    {
       if(!(PkgState[p->ID].Flags & Flag::Auto) ||
 	  (p->Flags & Flag::Essential) ||
-	  userFunc.InRootSet(p))
-          
+	  userFunc.InRootSet(p) ||
+	  // be nice even then a required package violates the policy (#583517)
+	  // and do the full mark process also for required packages
+	  (p.CurrentVer().end() != true &&
+	   p.CurrentVer()->Priority == pkgCache::State::Required))
       {
 	 // the package is installed (and set to keep)
 	 if(PkgState[p->ID].Keep() && !p.CurrentVer().end())
@@ -1373,15 +1648,21 @@ bool pkgDepCache::MarkRequired(InRootSetFunc &userFunc)
 // MarkPackage - mark a single package in Mark-and-Sweep		/*{{{*/
 void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
 			      const pkgCache::VerIterator &ver,
-			      bool follow_recommends,
-			      bool follow_suggests)
+			      bool const &follow_recommends,
+			      bool const &follow_suggests)
 {
    pkgDepCache::StateCache &state = PkgState[pkg->ID];
-   VerIterator currver            = pkg.CurrentVer();
-   VerIterator candver            = state.CandidateVerIter(*this);
-   VerIterator instver            = state.InstVerIter(*this);
+
+   // if we are marked already we are done
+   if(state.Marked)
+      return;
+
+   VerIterator const currver = pkg.CurrentVer();
+   VerIterator const instver = state.InstVerIter(*this);
 
 #if 0
+   VerIterator const candver = state.CandidateVerIter(*this);
+
    // If a package was garbage-collected but is now being marked, we
    // should re-select it 
    // For cases when a pkg is set to upgrade and this trigger the
@@ -1405,15 +1686,11 @@ void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
       !(ver == currver && instver.end() && !ver.end()))
       return;
 
-   // if we are marked already we are done
-   if(state.Marked)
-      return;
+   bool const debug_autoremove = _config->FindB("Debug::pkgAutoRemove", false);
 
-   bool debug_autoremove = _config->FindB("Debug::pkgAutoRemove", false);
-   
    if(debug_autoremove)
      {
-       std::clog << "Marking: " << pkg.Name();
+       std::clog << "Marking: " << pkg.FullName();
        if(!ver.end())
 	 std::clog << " " << ver.VerStr();
        if(!currver.end())
@@ -1425,8 +1702,9 @@ void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
 
    state.Marked=true;
 
-   if(!ver.end())
-   {
+   if(ver.end() == true)
+      return;
+
      for(DepIterator d = ver.DependsList(); !d.end(); ++d)
      {
 	if(d->Type == Dep::Depends ||
@@ -1444,10 +1722,9 @@ void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
 	      {
 		if(debug_autoremove)
 		  {
-		    std::clog << "Following dep: " << d.ParentPkg().Name()
+		    std::clog << "Following dep: " << d.ParentPkg().FullName()
 			      << " " << d.ParentVer().VerStr() << " "
-			      << d.DepType() << " "
-			      << d.TargetPkg().Name();
+			      << d.DepType() << " " << d.TargetPkg().FullName();
 		    if((d->CompareOp & ~pkgCache::Dep::Or) != pkgCache::Dep::NoOp)
 		      {
 			std::clog << " (" << d.CompType() << " "
@@ -1455,7 +1732,7 @@ void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
 		      }
 		    std::clog << std::endl;
 		  }
-		 MarkPackage(V.ParentPkg(), V, 
+		 MarkPackage(V.ParentPkg(), V,
 			     follow_recommends, follow_suggests);
 	      }
 	   }
@@ -1468,17 +1745,16 @@ void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
 	      {
 		if(debug_autoremove)
 		  {
-		    std::clog << "Following dep: " << d.ParentPkg().Name()
-			      << " " << d.ParentVer().VerStr() << " "
-			      << d.DepType() << " "
-			      << d.TargetPkg().Name();
+		    std::clog << "Following dep: " << d.ParentPkg().FullName() << " "
+			      << d.ParentVer().VerStr() << " "
+			      << d.DepType() << " " << d.TargetPkg().FullName() << " ";
 		    if((d->CompareOp & ~pkgCache::Dep::Or) != pkgCache::Dep::NoOp)
 		      {
 			std::clog << " (" << d.CompType() << " "
 				  << d.TargetVer() << ")";
 		      }
 		    std::clog << ", provided by "
-			      << prv.OwnerPkg().Name() << " "
+			      << prv.OwnerPkg().FullName() << " "
 			      << prv.OwnerVer().VerStr()
 			      << std::endl;
 		  }
@@ -1489,7 +1765,6 @@ void pkgDepCache::MarkPackage(const pkgCache::PkgIterator &pkg,
 	   }
 	}
      }
-   }
 }
 									/*}}}*/
 bool pkgDepCache::Sweep()						/*{{{*/
@@ -1511,7 +1786,7 @@ bool pkgDepCache::Sweep()						/*{{{*/
      {
 	state.Garbage=true;
 	if(debug_autoremove)
-	   std::cout << "Garbage: " << p.Name() << std::endl;
+	   std::clog << "Garbage: " << p.FullName() << std::endl;
      }
   }