]> git.saurik.com Git - cydia.git/blobdiff - MobileCydia.mm
Remove firmware (>= 3.2) dependency from control file.
[cydia.git] / MobileCydia.mm
index 60edfa0feb5b2207f3f6300c0be7821a8babf787..f113a80c84cc488c3cac89412492615cb71fb67f 100644 (file)
@@ -118,9 +118,10 @@ extern "C" {
 #include <errno.h>
 #include <pcre.h>
 
 #include <errno.h>
 #include <pcre.h>
 
-#include <ext/hash_map>
+#include <Cytore.hpp>
 
 #include "UICaboodle/BrowserView.h"
 
 #include "UICaboodle/BrowserView.h"
+#include "SDURLCache/SDURLCache.h"
 
 #include "substrate.h"
 /* }}} */
 
 #include "substrate.h"
 /* }}} */
@@ -197,6 +198,22 @@ void PrintTimes() {
 
 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
 
 
 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
 
+#define CYPoolStart() \
+    NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
+    do
+#define CYPoolEnd() \
+    while (false); \
+    [_pool release];
+
+// Hash Functions/Structures {{{
+extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
+
+union SplitHash {
+    uint32_t u32;
+    uint16_t u16[2];
+};
+// }}}
+
 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
 
 void NSLogPoint(const char *fix, const CGPoint &point) {
 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
 
 void NSLogPoint(const char *fix, const CGPoint &point) {
@@ -260,8 +277,6 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) {
 }
 
 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
 }
 
 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
-    /*return [self performSelector:selector withObject:object];*/
-
     volatile bool stopped(false);
 
     NSMutableArray *context([NSMutableArray arrayWithObjects:
     volatile bool stopped(false);
 
     NSMutableArray *context([NSMutableArray arrayWithObjects:
@@ -293,6 +308,7 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) {
 @end
 /* }}} */
 
 @end
 /* }}} */
 
+/* Cydia Action Sheet {{{ */
 @interface CYActionSheet : UIAlertView {
     unsigned button_;
 }
 @interface CYActionSheet : UIAlertView {
     unsigned button_;
 }
@@ -339,6 +355,7 @@ static _finline void UpdateExternalStatus(uint64_t newStatus) {
 }
 
 @end
 }
 
 @end
+/* }}} */
 
 /* NSForcedOrderingSearch doesn't work on the iPhone */
 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
 
 /* NSForcedOrderingSearch doesn't work on the iPhone */
 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
@@ -375,17 +392,15 @@ static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive |
 
 #define ForRelease 1
 #define TraceLogging (1 && !ForRelease)
 
 #define ForRelease 1
 #define TraceLogging (1 && !ForRelease)
-#define HistogramInsertionSort (0 && !ForRelease)
+#define HistogramInsertionSort (!ForRelease ? 0 : 0)
 #define ProfileTimes (0 && !ForRelease)
 #define ForSaurik (0 && !ForRelease)
 #define LogBrowser (0 && !ForRelease)
 #define TrackResize (0 && !ForRelease)
 #define ProfileTimes (0 && !ForRelease)
 #define ForSaurik (0 && !ForRelease)
 #define LogBrowser (0 && !ForRelease)
 #define TrackResize (0 && !ForRelease)
-#define ManualRefresh (0 && !ForRelease)
+#define ManualRefresh (1 && !ForRelease)
 #define ShowInternals (0 && !ForRelease)
 #define IgnoreInstall (0 && !ForRelease)
 #define ShowInternals (0 && !ForRelease)
 #define IgnoreInstall (0 && !ForRelease)
-#define RecycleWebViews 0
-#define RecyclePackageViews (0 && ForRelease)
-#define AlwaysReload (1 && !ForRelease)
+#define AlwaysReload (0 && !ForRelease)
 
 #if !TraceLogging
 #undef _trace
 
 #if !TraceLogging
 #undef _trace
@@ -404,7 +419,6 @@ static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive |
 typedef uint32_t (*SKRadixFunction)(id, void *);
 
 @interface NSMutableArray (Radix)
 typedef uint32_t (*SKRadixFunction)(id, void *);
 
 @interface NSMutableArray (Radix)
-- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
 @end
 
 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
 @end
 
@@ -413,7 +427,20 @@ struct RadixItem_ {
     uint32_t key;
 };
 
     uint32_t key;
 };
 
-static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
+@implementation NSMutableArray (Radix)
+
+- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
+    size_t count([self count]);
+    struct RadixItem_ *swap(new RadixItem_[count * 2]);
+
+    for (size_t i(0); i != count; ++i) {
+        RadixItem_ &item(swap[i]);
+        item.index = i;
+
+        id object([self objectAtIndex:i]);
+        item.key = function(object, argument);
+    }
+
     struct RadixItem_ *lhs(swap), *rhs(swap + count);
 
     static const size_t width = 32;
     struct RadixItem_ *lhs(swap), *rhs(swap + count);
 
     static const size_t width = 32;
@@ -454,68 +481,15 @@ static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *sw
 
     delete [] hist;
 
 
     delete [] hist;
 
-    NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
+    const void **values(new const void *[count]);
     for (size_t i(0); i != count; ++i)
     for (size_t i(0); i != count; ++i)
-        [values addObject:[self objectAtIndex:lhs[i].index]];
-    [self setArray:values];
+        values[i] = [self objectAtIndex:lhs[i].index];
+    CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
+    delete [] values;
 
     delete [] swap;
 }
 
 
     delete [] swap;
 }
 
-@implementation NSMutableArray (Radix)
-
-- (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
-    size_t count([self count]);
-    if (count == 0)
-        return;
-
-#if 0
-    NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
-    [invocation setSelector:selector];
-    [invocation setArgument:&object atIndex:2];
-#else
-    /* XXX: this is an unsafe optimization of doomy hell */
-    Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
-    _assert(method != NULL);
-    uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
-    _assert(imp != NULL);
-#endif
-
-    struct RadixItem_ *swap(new RadixItem_[count * 2]);
-
-    for (size_t i(0); i != count; ++i) {
-        RadixItem_ &item(swap[i]);
-        item.index = i;
-
-        id object([self objectAtIndex:i]);
-
-#if 0
-        [invocation setTarget:object];
-        [invocation invoke];
-        [invocation getReturnValue:&item.key];
-#else
-        item.key = imp(object, selector, object);
-#endif
-    }
-
-    RadixSort_(self, count, swap);
-}
-
-- (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
-    size_t count([self count]);
-    struct RadixItem_ *swap(new RadixItem_[count * 2]);
-
-    for (size_t i(0); i != count; ++i) {
-        RadixItem_ &item(swap[i]);
-        item.index = i;
-
-        id object([self objectAtIndex:i]);
-        item.key = function(object, argument);
-    }
-
-    RadixSort_(self, count, swap);
-}
-
 @end
 /* }}} */
 /* Insertion Sort {{{ */
 @end
 /* }}} */
 /* Insertion Sort {{{ */
@@ -552,7 +526,7 @@ void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFCompar
     const void **values(new const void *[range.length]);
     CFArrayGetValues(array, range, values);
 
     const void **values(new const void *[range.length]);
     CFArrayGetValues(array, range, values);
 
-#if HistogramInsertionSort
+#if HistogramInsertionSort > 0
     uint32_t total(0), *offsets(new uint32_t[range.length]);
 #endif
 
     uint32_t total(0), *offsets(new uint32_t[range.length]);
 #endif
 
@@ -560,9 +534,13 @@ void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFCompar
         const void *value(values[index]);
         //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
         CFIndex correct(index);
         const void *value(values[index]);
         //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
         CFIndex correct(index);
-        while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
+        while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
+#if HistogramInsertionSort > 1
+            NSLog(@"%@ < %@", value, values[correct - 1]);
+#endif
             if (--correct == 0)
                 break;
             if (--correct == 0)
                 break;
+        }
         if (correct != index) {
             size_t offset(index - correct);
 #if HistogramInsertionSort
         if (correct != index) {
             size_t offset(index - correct);
 #if HistogramInsertionSort
@@ -579,7 +557,7 @@ void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFCompar
     CFArrayReplaceValues(array, range, values, range.length);
     delete [] values;
 
     CFArrayReplaceValues(array, range, values, range.length);
     delete [] values;
 
-#if HistogramInsertionSort
+#if HistogramInsertionSort > 0
     for (CFIndex index(0); index != range.length; ++index)
         if (offsets[index] != 0)
             NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
     for (CFIndex index(0); index != range.length; ++index)
         if (offsets[index] != 0)
             NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
@@ -725,6 +703,16 @@ NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *s
 /* }}} */
 
 /* C++ NSString Wrapper Cache {{{ */
 /* }}} */
 
 /* C++ NSString Wrapper Cache {{{ */
+static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
+    return size == 0 ? NULL :
+        CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
+        CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
+}
+
+static _finline CFStringRef CYStringCreate(const char *data) {
+    return CYStringCreate(data, strlen(data));
+}
+
 class CYString {
   private:
     char *data_;
 class CYString {
   private:
     char *data_;
@@ -777,17 +765,24 @@ class CYString {
             cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
     }
 
             cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
     }
 
+    void copy(apr_pool_t *pool) {
+        char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
+        memcpy(temp, data_, size_);
+        temp[size_] = '\0';
+        data_ = temp;
+    }
+
     void set(apr_pool_t *pool, const char *data, size_t size) {
         if (size == 0)
             clear();
         else {
             clear_();
 
     void set(apr_pool_t *pool, const char *data, size_t size) {
         if (size == 0)
             clear();
         else {
             clear_();
 
-            char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
-            memcpy(temp, data, size);
-            temp[size] = '\0';
-            data_ = temp;
+            data_ = const_cast<char *>(data);
             size_ = size;
             size_ = size;
+
+            if (pool != NULL)
+                copy(pool);
         }
     }
 
         }
     }
 
@@ -803,19 +798,19 @@ class CYString {
         return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
     }
 
         return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
     }
 
-    operator CFStringRef() {
-        if (cache_ == NULL) {
-            if (size_ == 0)
-                return nil;
-            cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
-            if (cache_ == NULL)
-                cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
-        } return cache_;
+    _finline operator CFStringRef() {
+        if (cache_ == NULL)
+            cache_ = CYStringCreate(data_, size_);
+        return cache_;
     }
 
     _finline operator id() {
         return (NSString *) static_cast<CFStringRef>(*this);
     }
     }
 
     _finline operator id() {
         return (NSString *) static_cast<CFStringRef>(*this);
     }
+
+    _finline operator const char *() {
+        return reinterpret_cast<const char *>(data_);
+    }
 };
 /* }}} */
 /* C++ NSString Algorithm Adapters {{{ */
 };
 /* }}} */
 /* C++ NSString Algorithm Adapters {{{ */
@@ -977,6 +972,11 @@ class CYColor {
   private:
     CGColorRef color_;
 
   private:
     CGColorRef color_;
 
+    static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
+        CGFloat color[] = {red, green, blue, alpha};
+        return CGColorCreate(space, color);
+    }
+
   public:
     CYColor() :
         color_(NULL)
   public:
     CYColor() :
         color_(NULL)
@@ -984,7 +984,7 @@ class CYColor {
     }
 
     CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
     }
 
     CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
-        color_(NULL)
+        color_(Create_(space, red, green, blue, alpha))
     {
         Set(space, red, green, blue, alpha);
     }
     {
         Set(space, red, green, blue, alpha);
     }
@@ -1000,8 +1000,7 @@ class CYColor {
 
     void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
         Clear();
 
     void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
         Clear();
-        float color[] = {red, green, blue, alpha};
-        color_ = CGColorCreate(space, (CGFloat *) color);
+        color_ = Create_(space, red, green, blue, alpha);
     }
 
     operator CGColorRef() {
     }
 
     operator CGColorRef() {
@@ -1055,6 +1054,7 @@ static NSString *SerialNumber_ = nil;
 static NSString *ChipID_ = nil;
 static NSString *Token_ = nil;
 static NSString *UniqueID_ = nil;
 static NSString *ChipID_ = nil;
 static NSString *Token_ = nil;
 static NSString *UniqueID_ = nil;
+static NSString *PLMN_ = nil;
 static NSString *Build_ = nil;
 static NSString *Product_ = nil;
 static NSString *Safari_ = nil;
 static NSString *Build_ = nil;
 static NSString *Product_ = nil;
 static NSString *Safari_ = nil;
@@ -1071,13 +1071,9 @@ static _transient NSMutableDictionary *Packages_;
 static _transient NSMutableDictionary *Sections_;
 static _transient NSMutableDictionary *Sources_;
 static bool Changed_;
 static _transient NSMutableDictionary *Sections_;
 static _transient NSMutableDictionary *Sources_;
 static bool Changed_;
-static NSDate *now_;
+static time_t now_;
 
 static bool IsWildcat_;
 
 static bool IsWildcat_;
-
-#if RecycleWebViews
-static NSMutableArray *Documents_;
-#endif
 /* }}} */
 
 /* Display Helpers {{{ */
 /* }}} */
 
 /* Display Helpers {{{ */
@@ -1102,24 +1098,9 @@ NSString *SizeString(double size) {
     return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
 }
 
     return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
 }
 
-static _finline CFStringRef CFCString(const char *value) {
-    return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
-}
-
-const char *StripVersion_(const char *version) {
-    const char *colon(strchr(version, ':'));
-    if (colon != NULL)
-        version = colon + 1;
-    return version;
-}
-
-CFStringRef StripVersion(const char *version) {
+static _finline const char *StripVersion_(const char *version) {
     const char *colon(strchr(version, ':'));
     const char *colon(strchr(version, ':'));
-    if (colon != NULL)
-        version = colon + 1;
-    return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
-    // XXX: performance
-    return CFCString(version);
+    return colon == NULL ? version : colon + 1;
 }
 
 NSString *LocalizeSection(NSString *section) {
 }
 
 NSString *LocalizeSection(NSString *section) {
@@ -1363,7 +1344,7 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
     pkgSourceList *list_;
 
     SourceMap sources_;
     pkgSourceList *list_;
 
     SourceMap sources_;
-    NSMutableArray *packages_;
+    CFMutableArrayRef packages_;
 
     _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
     Status status_;
 
     _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
     Status status_;
@@ -1401,8 +1382,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (bool) upgrade;
 - (void) update;
 
 - (bool) upgrade;
 - (void) update;
 
-- (void) setVisible;
-
 - (void) updateWithStatus:(Status &)status;
 
 - (void) setDelegate:(id)delegate;
 - (void) updateWithStatus:(Status &)status;
 
 - (void) setDelegate:(id)delegate;
@@ -1445,6 +1424,109 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 @end
 /* }}} */
 
 @end
 /* }}} */
 
+// Cytore Definitions {{{
+struct PackageValue :
+    Cytore::Block
+{
+    Cytore::Offset<PackageValue> next_;
+
+    uint32_t index_ : 23;
+    uint32_t subscribed_ : 1;
+    uint32_t : 8;
+
+    int32_t first_;
+    int32_t last_;
+
+    uint16_t vhash_;
+    uint16_t nhash_;
+
+    char version_[8];
+    char name_[];
+};
+
+struct MetaValue :
+    Cytore::Block
+{
+    uint32_t active_;
+    Cytore::Offset<PackageValue> packages_[1 << 16];
+};
+
+static Cytore::File<MetaValue> MetaFile_;
+// }}}
+// Cytore Helper Functions {{{
+static PackageValue *PackageFind(const char *name, size_t length) {
+    SplitHash nhash = { hashlittle(name, length) };
+
+    PackageValue *metadata;
+
+    Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
+    offset: if (offset->IsNull()) {
+        *offset = MetaFile_.New<PackageValue>(length + 1);
+        metadata = &MetaFile_.Get(*offset);
+
+        memcpy(metadata->name_, name, length + 1);
+        metadata->nhash_ = nhash.u16[1];
+    } else {
+        metadata = &MetaFile_.Get(*offset);
+
+        if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
+            offset = &metadata->next_;
+            goto offset;
+        }
+    }
+
+    return metadata;
+}
+
+static void PackageImport(const void *key, const void *value, void *context) {
+    char buffer[1024];
+    if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
+        NSLog(@"failed to import package %@", key);
+        return;
+    }
+
+    PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
+    NSDictionary *package((NSDictionary *) value);
+
+    if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
+        if ([subscribed boolValue])
+            metadata->subscribed_ = true;
+
+    if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
+        time_t time([date timeIntervalSince1970]);
+        if (metadata->first_ > time || metadata->first_ == 0)
+            metadata->first_ = time;
+    }
+
+    bool versioned(false);
+
+    if (NSDate *date = [package objectForKey:@"LastSeen"]) {
+        time_t time([date timeIntervalSince1970]);
+        if (metadata->last_ < time || metadata->last_ == 0) {
+            metadata->last_ = time;
+            versioned = true;
+        }
+    } else if (metadata->last_ == 0) {
+        metadata->last_ = metadata->first_;
+        if (metadata->version_[0] == '\0')
+            versioned = true;
+    }
+
+    if (versioned)
+        if (NSString *version = [package objectForKey:@"LastVersion"])
+            if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
+                size_t length(strlen(buffer));
+                uint16_t vhash(hashlittle(buffer, length));
+
+                size_t capped(std::min<size_t>(8, length));
+                char *latest(buffer + length - capped);
+
+                strncpy(metadata->version_, latest, sizeof(metadata->version_));
+                metadata->vhash_ = vhash;
+            }
+}
+// }}}
+
 /* Source Class {{{ */
 @interface Source : NSObject {
     CYString depiction_;
 /* Source Class {{{ */
 @interface Source : NSObject {
     CYString depiction_;
@@ -1525,6 +1607,7 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 }
 
 - (void) dealloc {
 }
 
 - (void) dealloc {
+    // XXX: this is a very inefficient way to call these deconstructors
     [self _clear];
     [super dealloc];
 }
     [self _clear];
     [super dealloc];
 }
@@ -1731,53 +1814,51 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 @end
 /* }}} */
 /* Package Class {{{ */
 @end
 /* }}} */
 /* Package Class {{{ */
+struct ParsedPackage {
+    CYString tagline_;
+
+    CYString icon_;
+
+    CYString depiction_;
+    CYString homepage_;
+
+    CYString sponsor_;
+    CYString author_;
+
+    CYString bugs_;
+    CYString support_;
+};
+
 @interface Package : NSObject {
 @interface Package : NSObject {
-    unsigned era_;
+    uint32_t era_ : 29;
+    uint32_t essential_ : 1;
+    uint32_t obsolete_ : 1;
+    uint32_t ignored_ : 1;
+
     apr_pool_t *pool_;
 
     apr_pool_t *pool_;
 
+    _transient Database *database_;
+
     pkgCache::VerIterator version_;
     pkgCache::PkgIterator iterator_;
     pkgCache::VerIterator version_;
     pkgCache::PkgIterator iterator_;
-    _transient Database *database_;
     pkgCache::VerFileIterator file_;
 
     pkgCache::VerFileIterator file_;
 
-    Source *source_;
-    bool cached_;
-    bool parsed_;
-
-    CYString section_;
-    NSString *section$_;
-    bool essential_;
-    bool required_;
-    bool visible_;
-    bool obsolete_;
+    CYString id_;
+    CYString name_;
 
 
-    NSString *latest_;
+    CYString latest_;
     CYString installed_;
 
     CYString installed_;
 
-    CYString id_;
-    CYString name_;
-    CYString tagline_;
-    CYString icon_;
-    CYString depiction_;
-    CYString homepage_;
+    CYString section_;
+    _transient NSString *section$_;
 
 
-    CYString sponsor_;
-    Address *sponsor$_;
+    Source *source_;
 
 
-    CYString author_;
-    Address *author$_;
+    PackageValue *metadata_;
+    ParsedPackage *parsed_;
 
 
-    CYString bugs_;
-    CYString support_;
     NSMutableArray *tags_;
     NSString *role_;
     NSMutableArray *tags_;
     NSString *role_;
-
-    NSArray *relationships_;
-
-    NSMutableDictionary *metadata_;
-    _transient NSDate *firstSeen_;
-    _transient NSDate *lastSeen_;
-    bool subscribed_;
 }
 
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
 }
 
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
@@ -1800,9 +1881,12 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSString *) shortDescription;
 - (unichar) index;
 
 - (NSString *) shortDescription;
 - (unichar) index;
 
-- (NSMutableDictionary *) metadata;
-- (NSDate *) seen;
-- (BOOL) subscribed;
+- (PackageValue *) metadata;
+- (time_t) seen;
+
+- (bool) subscribed;
+- (bool) setSubscribed:(bool)subscribed;
+
 - (BOOL) ignored;
 
 - (NSString *) latest;
 - (BOOL) ignored;
 
 - (NSString *) latest;
@@ -1822,8 +1906,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (BOOL) hasMode;
 - (NSString *) mode;
 
 - (BOOL) hasMode;
 - (NSString *) mode;
 
-- (void) setVisible;
-
 - (NSString *) id;
 - (NSString *) name;
 - (UIImage *) icon;
 - (NSString *) id;
 - (NSString *) name;
 - (UIImage *) icon;
@@ -1834,7 +1916,6 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSString *) support;
 
 - (NSArray *) files;
 - (NSString *) support;
 
 - (NSArray *) files;
-- (NSArray *) relationships;
 - (NSArray *) warnings;
 - (NSArray *) applications;
 
 - (NSArray *) warnings;
 - (NSArray *) applications;
 
@@ -1849,18 +1930,18 @@ typedef std::map< unsigned long, _H<Source> > SourceMap;
 - (NSArray *) purposes;
 - (bool) isCommercial;
 
 - (NSArray *) purposes;
 - (bool) isCommercial;
 
+- (void) setIndex:(size_t)index;
+
 - (CYString &) cyname;
 
 - (uint32_t) compareBySection:(NSArray *)sections;
 
 - (CYString &) cyname;
 
 - (uint32_t) compareBySection:(NSArray *)sections;
 
-- (uint32_t) compareForChanges;
-
 - (void) install;
 - (void) remove;
 
 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
 - (void) install;
 - (void) remove;
 
 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
-- (bool) isInstalledAndVisible:(NSNumber *)number;
+- (bool) isInstalledAndUnfiltered:(NSNumber *)number;
 - (bool) isVisibleInSection:(NSString *)section;
 - (bool) isVisibleInSource:(Source *)source;
 
 - (bool) isVisibleInSection:(NSString *)section;
 - (bool) isVisibleInSource:(Source *)source;
 
@@ -1885,7 +1966,7 @@ uint32_t PackageChangesRadix(Package *self, void *) {
         value.bits.ignored = [self ignored] ? 0 : 1;
         value.bits.upgradable = 1;
     } else {
         value.bits.ignored = [self ignored] ? 0 : 1;
         value.bits.upgradable = 1;
     } else {
-        value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
+        value.bits.timestamp = [self seen] >> 2;
         value.bits.ignored = 0;
         value.bits.upgradable = 0;
     }
         value.bits.ignored = 0;
         value.bits.upgradable = 0;
     }
@@ -1893,9 +1974,6 @@ uint32_t PackageChangesRadix(Package *self, void *) {
     return _not(uint32_t) - value.key;
 }
 
     return _not(uint32_t) - value.key;
 }
 
-_finline static void Stifle(uint8_t &value) {
-}
-
 uint32_t PackagePrefixRadix(Package *self, void *context) {
     size_t offset(reinterpret_cast<size_t>(context));
     CYString &name([self cyname]);
 uint32_t PackagePrefixRadix(Package *self, void *context) {
     size_t offset(reinterpret_cast<size_t>(context));
     CYString &name([self cyname]);
@@ -1918,8 +1996,6 @@ uint32_t PackagePrefixRadix(Package *self, void *context) {
 
     uint8_t data[4];
 
 
     uint8_t data[4];
 
-    // 0.607997
-
     if (offset == 0 && zeros != 0) {
         memset(data, '0', zeros);
         memcpy(data + zeros, text, 4 - zeros);
     if (offset == 0 && zeros != 0) {
         memset(data, '0', zeros);
         memcpy(data + zeros, text, 4 - zeros);
@@ -1940,11 +2016,14 @@ uint32_t PackagePrefixRadix(Package *self, void *context) {
 
         for (size_t i(0); i != 4; ++i)
             if (isalpha(data[i]))
 
         for (size_t i(0); i != 4; ++i)
             if (isalpha(data[i]))
-                data[i] &= 0xdf;
+                data[i] |= 0x20;
     }
 
     if (offset == 0)
     }
 
     if (offset == 0)
-        data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
+        if (data[0] == '@')
+            data[0] = 0x7f;
+        else
+            data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
 
     /* XXX: ntohl may be more honest */
     return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
 
     /* XXX: ntohl may be more honest */
     return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
@@ -2000,28 +2079,17 @@ struct PackageNameOrdering :
 }
 
 - (void) dealloc {
 }
 
 - (void) dealloc {
+    if (parsed_ != NULL)
+        delete parsed_;
+
     if (source_ != nil)
         [source_ release];
     if (source_ != nil)
         [source_ release];
-    if (section$_ != nil)
-        [section$_ release];
 
 
-    if (latest_ != nil)
-        [latest_ release];
-
-    if (sponsor$_ != nil)
-        [sponsor$_ release];
-    if (author$_ != nil)
-        [author$_ release];
     if (tags_ != nil)
         [tags_ release];
     if (role_ != nil)
         [role_ release];
 
     if (tags_ != nil)
         [tags_ release];
     if (role_ != nil)
         [role_ release];
 
-    if (relationships_ != nil)
-        [relationships_ release];
-    if (metadata_ != nil)
-        [metadata_ release];
-
     [super dealloc];
 }
 
     [super dealloc];
 }
 
@@ -2049,12 +2117,15 @@ struct PackageNameOrdering :
 }
 
 - (void) parse {
 }
 
 - (void) parse {
-    if (parsed_)
+    if (parsed_ != NULL)
         return;
         return;
-    parsed_ = true;
-    if (file_.end())
+@synchronized (database_) {
+    if ([database_ era] != era_ || file_.end())
         return;
 
         return;
 
+    ParsedPackage *parsed(new ParsedPackage);
+    parsed_ = parsed;
+
     _profile(Package$parse)
         pkgRecords::Parser *parser;
 
     _profile(Package$parse)
         pkgRecords::Parser *parser;
 
@@ -2069,14 +2140,14 @@ struct PackageNameOrdering :
                 const char *name_;
                 CYString *value_;
             } names[] = {
                 const char *name_;
                 CYString *value_;
             } names[] = {
-                {"icon", &icon_},
-                {"depiction", &depiction_},
-                {"homepage", &homepage_},
+                {"icon", &parsed->icon_},
+                {"depiction", &parsed->depiction_},
+                {"homepage", &parsed->homepage_},
                 {"website", &website},
                 {"website", &website},
-                {"bugs", &bugs_},
-                {"support", &support_},
-                {"sponsor", &sponsor_},
-                {"author", &author_},
+                {"bugs", &parsed->bugs_},
+                {"support", &parsed->support_},
+                {"sponsor", &parsed->sponsor_},
+                {"author", &parsed->author_},
             };
 
             for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
             };
 
             for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
@@ -2099,44 +2170,33 @@ struct PackageNameOrdering :
                     stop = end;
                 while (stop != start && stop[-1] == '\r')
                     --stop;
                     stop = end;
                 while (stop != start && stop[-1] == '\r')
                     --stop;
-                tagline_.set(pool_, start, stop - start);
+                parsed->tagline_.set(pool_, start, stop - start);
             }
         _end
 
         _profile(Package$parse$Retain)
             }
         _end
 
         _profile(Package$parse$Retain)
-            if (homepage_.empty())
-                homepage_ = website;
-            if (homepage_ == depiction_)
-                homepage_.clear();
+            if (parsed->homepage_.empty())
+                parsed->homepage_ = website;
+            if (parsed->homepage_ == parsed->depiction_)
+                parsed->homepage_.clear();
         _end
     _end
         _end
     _end
-}
-
-- (void) setVisible {
-    visible_ = required_ && [self unfiltered];
-}
+} }
 
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
     if ((self = [super init]) != nil) {
     _profile(Package$initWithVersion)
 
 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
     if ((self = [super init]) != nil) {
     _profile(Package$initWithVersion)
-    @synchronized (database) {
-        era_ = [database era];
         pool_ = pool;
 
         pool_ = pool;
 
-        version_ = version;
-        iterator_ = version.ParentPkg();
         database_ = database;
         database_ = database;
+        era_ = [database era];
 
 
-        _profile(Package$initWithVersion$Latest)
-            latest_ = (NSString *) StripVersion(version_.VerStr());
-        _end
+        version_ = version;
 
 
-        pkgCache::VerIterator current;
-        _profile(Package$initWithVersion$Versions)
-            current = iterator_.CurrentVer();
-            if (!current.end())
-                installed_.set(pool_, StripVersion_(current.VerStr()));
+        pkgCache::PkgIterator iterator(version.ParentPkg());
+        iterator_ = iterator;
 
 
+        _profile(Package$initWithVersion$Version)
             if (!version_.end())
                 file_ = version_.FileList();
             else {
             if (!version_.end())
                 file_ = version_.FileList();
             else {
@@ -2145,101 +2205,87 @@ struct PackageNameOrdering :
             }
         _end
 
             }
         _end
 
-        _profile(Package$initWithVersion$Name)
-            id_.set(pool_, iterator_.Name());
-            name_.set(pool, iterator_.Display());
-        _end
+        _profile(Package$initWithVersion$Cache)
+            name_.set(NULL, iterator.Display());
 
 
-        if (!file_.end()) {
-            _profile(Package$initWithVersion$Source)
-                source_ = [database_ getSource:file_.File()];
-                if (source_ != nil)
-                    [source_ retain];
-                cached_ = true;
-            _end
-        }
+            latest_.set(NULL, StripVersion_(version_.VerStr()));
 
 
-        required_ = true;
+            pkgCache::VerIterator current(iterator.CurrentVer());
+            if (!current.end())
+                installed_.set(NULL, StripVersion_(current.VerStr()));
+        _end
 
         _profile(Package$initWithVersion$Tags)
 
         _profile(Package$initWithVersion$Tags)
-            pkgCache::TagIterator tag(iterator_.TagList());
+            pkgCache::TagIterator tag(iterator.TagList());
             if (!tag.end()) {
                 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
                 do {
                     const char *name(tag.Name());
             if (!tag.end()) {
                 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
                 do {
                     const char *name(tag.Name());
-                    [tags_ addObject:(NSString *)CFCString(name)];
+                    [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
+
                     if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
                     if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
-                        role_ = (NSString *) CFCString(name + 6);
-                    if (required_ && strncmp(name, "require::", 9) == 0 && (
-                        true
-                    ))
-                        required_ = false;
+                        role_ = (NSString *) CYStringCreate(name + 6);
+
+                    if (strncmp(name, "cydia::", 7) == 0) {
+                        if (strcmp(name + 7, "essential") == 0)
+                            essential_ = true;
+                        else if (strcmp(name + 7, "obsolete") == 0)
+                            obsolete_ = true;
+                    }
+
                     ++tag;
                 } while (!tag.end());
             }
         _end
 
                     ++tag;
                 } while (!tag.end());
             }
         _end
 
-        bool changed(false);
-        NSString *key([static_cast<id>(id_) lowercaseString]);
-
         _profile(Package$initWithVersion$Metadata)
         _profile(Package$initWithVersion$Metadata)
-            metadata_ = [Packages_ objectForKey:key];
+            const char *mixed(iterator.Name());
+            size_t size(strlen(mixed));
+            char lower[size + 1];
 
 
-            if (metadata_ == nil) {
-                firstSeen_ = now_;
+            for (size_t i(0); i != size; ++i)
+                lower[i] = mixed[i] | 0x20;
+            lower[size] = '\0';
 
 
-                metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
-                    firstSeen_, @"FirstSeen",
-                    latest_, @"LastVersion",
-                nil] mutableCopy];
+            PackageValue *metadata(PackageFind(lower, size));
+            metadata_ = metadata;
 
 
-                changed = true;
-            } else {
-                firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
-                lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
+            id_.set(NULL, metadata->name_, size);
 
 
-                if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
-                    subscribed_ = [subscribed boolValue];
+            const char *latest(version_.VerStr());
+            size_t length(strlen(latest));
 
 
-                NSString *version([metadata_ objectForKey:@"LastVersion"]);
+            uint16_t vhash(hashlittle(latest, length));
 
 
-                if (firstSeen_ == nil) {
-                    firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
-                    [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
-                    changed = true;
-                }
+            size_t capped(std::min<size_t>(8, length));
+            latest = latest + length - capped;
 
 
-                if (version == nil) {
-                    [metadata_ setObject:latest_ forKey:@"LastVersion"];
-                    changed = true;
-                } else if (![version isEqualToString:latest_]) {
-                    [metadata_ setObject:latest_ forKey:@"LastVersion"];
-                    lastSeen_ = now_;
-                    [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
-                    changed = true;
-                }
-            }
+            if (metadata->first_ == 0)
+                metadata->first_ = now_;
 
 
-            metadata_ = [metadata_ retain];
+            if (metadata->last_ == 0)
+                metadata->last_ = metadata->first_;
 
 
-            if (changed) {
-                [Packages_ setObject:metadata_ forKey:key];
-                Changed_ = true;
+            if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
+                if (metadata->version_[0] != '\0')
+                    metadata->last_ = now_;
+                strncpy(metadata->version_, latest, sizeof(metadata->version_));
+                metadata->vhash_ = vhash;
             }
         _end
 
         _profile(Package$initWithVersion$Section)
             }
         _end
 
         _profile(Package$initWithVersion$Section)
-            section_.set(pool_, iterator_.Section());
+            section_.set(NULL, iterator.Section());
         _end
 
         _end
 
-        obsolete_ = [self hasTag:@"cydia::obsolete"];
-        essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
-        [self setVisible];
-    } _end } return self;
+        _profile(Package$initWithVersion$Flags)
+            essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
+            ignored_ = iterator->SelectedState == pkgCache::State::Hold;
+        _end
+    _end } return self;
 }
 
 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
 }
 
 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
-@synchronized ([Database class]) {
     pkgCache::VerIterator version;
 
     _profile(Package$packageWithIterator$GetCandidateVer)
     pkgCache::VerIterator version;
 
     _profile(Package$packageWithIterator$GetCandidateVer)
@@ -2249,13 +2295,27 @@ struct PackageNameOrdering :
     if (version.end())
         return nil;
 
     if (version.end())
         return nil;
 
-    return [[[Package alloc]
-        initWithVersion:version
-        withZone:zone
-        inPool:pool
-        database:database
-    ] autorelease];
-} }
+    Package *package;
+
+    _profile(Package$packageWithIterator$Allocate)
+        package = [Package allocWithZone:zone];
+    _end
+
+    _profile(Package$packageWithIterator$Initialize)
+        package = [package
+            initWithVersion:version
+            withZone:zone
+            inPool:pool
+            database:database
+        ];
+    _end
+
+    _profile(Package$packageWithIterator$Autorelease)
+        package = [package autorelease];
+    _end
+
+    return package;
+}
 
 - (pkgCache::PkgIterator) iterator {
     return iterator_;
 
 - (pkgCache::PkgIterator) iterator {
     return iterator_;
@@ -2266,17 +2326,11 @@ struct PackageNameOrdering :
         if (section_.empty())
             return nil;
 
         if (section_.empty())
             return nil;
 
-        std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
-        NSString *name(section_);
-
-      lookup:
-        if (NSDictionary *value = [SectionMap_ objectForKey:name])
-            if (NSString *rename = [value objectForKey:@"Rename"]) {
-                name = rename;
-                goto lookup;
-            }
-
-        section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
+        _profile(Package$section)
+            std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
+            NSString *name(section_);
+            section$_ = [SectionMap_ objectForKey:name] ?: name;
+        _end
     } return section$_;
 }
 
     } return section$_;
 }
 
@@ -2309,20 +2363,28 @@ struct PackageNameOrdering :
 }
 
 - (Address *) maintainer {
 }
 
 - (Address *) maintainer {
-    if (file_.end())
+@synchronized (database_) {
+    if ([database_ era] != era_ || file_.end())
         return nil;
         return nil;
+
     pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
     const std::string &maintainer(parser->Maintainer());
     return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
     pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
     const std::string &maintainer(parser->Maintainer());
     return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
-}
+} }
 
 - (size_t) size {
 
 - (size_t) size {
-    return version_.end() ? 0 : version_->InstalledSize;
-}
+@synchronized (database_) {
+    if ([database_ era] != era_ || version_.end())
+        return 0;
+
+    return version_->InstalledSize;
+} }
 
 - (NSString *) longDescription {
 
 - (NSString *) longDescription {
-    if (file_.end())
+@synchronized (database_) {
+    if ([database_ era] != era_ || file_.end())
         return nil;
         return nil;
+
     pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
     NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
 
     pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
     NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
 
@@ -2338,10 +2400,10 @@ struct PackageNameOrdering :
     }
 
     return [trimmed componentsJoinedByString:@"\n"];
     }
 
     return [trimmed componentsJoinedByString:@"\n"];
-}
+} }
 
 - (NSString *) shortDescription {
 
 - (NSString *) shortDescription {
-    return tagline_;
+    return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
 }
 
 - (unichar) index {
 }
 
 - (unichar) index {
@@ -2356,26 +2418,29 @@ struct PackageNameOrdering :
     _end
 }
 
     _end
 }
 
-- (NSMutableDictionary *) metadata {
+- (PackageValue *) metadata {
     return metadata_;
 }
 
     return metadata_;
 }
 
-- (NSDate *) seen {
-    if (subscribed_ && lastSeen_ != nil)
-        return lastSeen_;
-    return firstSeen_;
+- (time_t) seen {
+    PackageValue *metadata([self metadata]);
+    return metadata->subscribed_ ? metadata->last_ : metadata->first_;
 }
 
 }
 
-- (BOOL) subscribed {
-    return subscribed_;
+- (bool) subscribed {
+    return [self metadata]->subscribed_;
 }
 
 }
 
-- (BOOL) ignored {
-    NSDictionary *metadata([self metadata]);
-    if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
-        return [ignored boolValue];
-    else
+- (bool) setSubscribed:(bool)subscribed {
+    PackageValue *metadata([self metadata]);
+    if (metadata->subscribed_ == subscribed)
         return false;
         return false;
+    metadata->subscribed_ = subscribed;
+    return true;
+}
+
+- (BOOL) ignored {
+    return ignored_;
 }
 
 - (NSString *) latest {
 }
 
 - (NSString *) latest {
@@ -2398,9 +2463,9 @@ struct PackageNameOrdering :
     _profile(Package$upgradableAndEssential)
         pkgCache::VerIterator current(iterator_.CurrentVer());
         if (current.end())
     _profile(Package$upgradableAndEssential)
         pkgCache::VerIterator current(iterator_.CurrentVer());
         if (current.end())
-            return essential && essential_ && visible_;
+            return essential && essential_;
         else
         else
-            return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
+            return !version_.end() && version_ != current;
     _end
 }
 
     _end
 }
 
@@ -2413,12 +2478,31 @@ struct PackageNameOrdering :
 }
 
 - (BOOL) unfiltered {
 }
 
 - (BOOL) unfiltered {
-    NSString *section([self section]);
-    return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
+    _profile(Package$unfiltered$obsolete)
+        if (obsolete_)
+            return false;
+    _end
+
+    _profile(Package$unfiltered$hasSupportingRole)
+        if (![self hasSupportingRole])
+            return false;
+    _end
+
+    return true;
 }
 
 - (BOOL) visible {
 }
 
 - (BOOL) visible {
-    return visible_;
+    if (![self unfiltered])
+        return false;
+
+    NSString *section([self section]);
+
+    _profile(Package$visible$isSectionVisible)
+        if (section != nil && !isSectionVisible(section))
+            return false;
+    _end
+
+    return true;
 }
 
 - (BOOL) half {
 }
 
 - (BOOL) half {
@@ -2485,13 +2569,14 @@ struct PackageNameOrdering :
     NSString *section = [self simpleSection];
 
     UIImage *icon(nil);
     NSString *section = [self simpleSection];
 
     UIImage *icon(nil);
-    if (!icon_.empty())
-        if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
-            // XXX: correct escaping
-            icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
+    if (parsed_ != NULL)
+        if (NSString *href = parsed_->icon_)
+            if ([href hasPrefix:@"file:///"])
+                // XXX: correct escaping
+                icon = [UIImage imageAtPath:[href substringFromIndex:7]];
     if (icon == nil) if (section != nil)
         icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
     if (icon == nil) if (section != nil)
         icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
-    if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
+    if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
         if ([dicon hasPrefix:@"file:///"])
             // XXX: correct escaping
             icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
         if ([dicon hasPrefix:@"file:///"])
             // XXX: correct escaping
             icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
@@ -2501,31 +2586,23 @@ struct PackageNameOrdering :
 }
 
 - (NSString *) homepage {
 }
 
 - (NSString *) homepage {
-    return homepage_;
+    return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
 }
 
 - (NSString *) depiction {
 }
 
 - (NSString *) depiction {
-    return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
+    return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
 }
 
 - (Address *) sponsor {
 }
 
 - (Address *) sponsor {
-    if (sponsor$_ == nil) {
-        if (sponsor_.empty())
-            return nil;
-        sponsor$_ = [[Address addressWithString:sponsor_] retain];
-    } return sponsor$_;
+    return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
 }
 
 - (Address *) author {
 }
 
 - (Address *) author {
-    if (author$_ == nil) {
-        if (author_.empty())
-            return nil;
-        author$_ = [[Address addressWithString:author_] retain];
-    } return author$_;
+    return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
 }
 
 - (NSString *) support {
 }
 
 - (NSString *) support {
-    return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
+    return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
 }
 
 - (NSArray *) files {
 }
 
 - (NSArray *) files {
@@ -2544,10 +2621,6 @@ struct PackageNameOrdering :
     return files;
 }
 
     return files;
 }
 
-- (NSArray *) relationships {
-    return relationships_;
-}
-
 - (NSArray *) warnings {
     NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
     const char *name(iterator_.Name());
 - (NSArray *) warnings {
     NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
     const char *name(iterator_.Name());
@@ -2633,21 +2706,16 @@ struct PackageNameOrdering :
 }
 
 - (Source *) source {
 }
 
 - (Source *) source {
-    if (!cached_) {
+    if (source_ == nil) {
         @synchronized (database_) {
             if ([database_ era] != era_ || file_.end())
         @synchronized (database_) {
             if ([database_ era] != era_ || file_.end())
-                source_ = nil;
-            else {
-                source_ = [database_ getSource:file_.File()];
-                if (source_ != nil)
-                    [source_ retain];
-            }
-
-            cached_ = true;
+                source_ = (Source *) [NSNull null];
+            else
+                source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
         }
     }
 
         }
     }
 
-    return source_;
+    return source_ == (Source *) [NSNull null] ? nil : source_;
 }
 
 - (NSString *) role {
 }
 
 - (NSString *) role {
@@ -2716,7 +2784,12 @@ struct PackageNameOrdering :
     return [self hasTag:@"cydia::commercial"];
 }
 
     return [self hasTag:@"cydia::commercial"];
 }
 
-- (CYString &) cyname {
+- (void) setIndex:(size_t)index {
+    if (metadata_->index_ != index)
+        metadata_->index_ = index;
+}
+
+- (CYString &) cyname {
     return name_.empty() ? id_ : name_;
 }
 
     return name_.empty() ? id_ : name_;
 }
 
@@ -2730,57 +2803,42 @@ struct PackageNameOrdering :
     return _not(uint32_t);
 }
 
     return _not(uint32_t);
 }
 
-- (uint32_t) compareForChanges {
-    union {
-        uint32_t key;
-
-        struct {
-            uint32_t timestamp : 30;
-            uint32_t ignored : 1;
-            uint32_t upgradable : 1;
-        } bits;
-    } value;
-
-    bool upgradable([self upgradableAndEssential:YES]);
-    value.bits.upgradable = upgradable ? 1 : 0;
-
-    if (upgradable) {
-        value.bits.timestamp = 0;
-        value.bits.ignored = [self ignored] ? 0 : 1;
-        value.bits.upgradable = 1;
-    } else {
-        value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
-        value.bits.ignored = 0;
-        value.bits.upgradable = 0;
-    }
-
-    return _not(uint32_t) - value.key;
-}
-
 - (void) clear {
 - (void) clear {
+@synchronized (database_) {
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
-    resolver->Protect(iterator_);
-}
+
+    pkgCacheFile &cache([database_ cache]);
+    cache->SetReInstall(iterator_, false);
+    cache->MarkKeep(iterator_, false);
+} }
 
 - (void) install {
 
 - (void) install {
+@synchronized (database_) {
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
     resolver->Protect(iterator_);
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
     resolver->Protect(iterator_);
+
     pkgCacheFile &cache([database_ cache]);
     pkgCacheFile &cache([database_ cache]);
+    cache->SetReInstall(iterator_, false);
     cache->MarkInstall(iterator_, false);
     cache->MarkInstall(iterator_, false);
+
     pkgDepCache::StateCache &state((*cache)[iterator_]);
     if (!state.Install())
         cache->SetReInstall(iterator_, true);
     pkgDepCache::StateCache &state((*cache)[iterator_]);
     if (!state.Install())
         cache->SetReInstall(iterator_, true);
-}
+} }
 
 - (void) remove {
 
 - (void) remove {
+@synchronized (database_) {
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
     pkgProblemResolver *resolver = [database_ resolver];
     resolver->Clear(iterator_);
-    resolver->Protect(iterator_);
     resolver->Remove(iterator_);
     resolver->Remove(iterator_);
-    [database_ cache]->MarkDelete(iterator_, true);
-}
+    resolver->Protect(iterator_);
+
+    pkgCacheFile &cache([database_ cache]);
+    cache->SetReInstall(iterator_, false);
+    cache->MarkDelete(iterator_, true);
+} }
 
 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
     _profile(Package$isUnfilteredAndSearchedForBy)
 
 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
     _profile(Package$isUnfilteredAndSearchedForBy)
@@ -2817,19 +2875,18 @@ struct PackageNameOrdering :
     _end
 }
 
     _end
 }
 
-- (bool) isInstalledAndVisible:(NSNumber *)number {
-    return (![number boolValue] || [self visible]) && ![self uninstalled];
+- (bool) isInstalledAndUnfiltered:(NSNumber *)number {
+    return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
 }
 
 - (bool) isVisibleInSection:(NSString *)name {
 }
 
 - (bool) isVisibleInSection:(NSString *)name {
-    NSString *section = [self section];
+    NSString *section([self section]);
 
 
-    return
-        [self visible] && (
-            name == nil ||
-            section == nil && [name length] == 0 ||
-            [name isEqualToString:section]
-        );
+    return (
+        name == nil ||
+        section == nil && [name length] == 0 ||
+        [name isEqualToString:section]
+    ) && [self visible];
 }
 
 - (bool) isVisibleInSource:(Source *)source {
 }
 
 - (bool) isVisibleInSource:(Source *)source {
@@ -2958,6 +3015,7 @@ struct PackageNameOrdering :
 /* }}} */
 
 static NSString *Colon_;
 /* }}} */
 
 static NSString *Colon_;
+static NSString *Elision_;
 static NSString *Error_;
 static NSString *Warning_;
 
 static NSString *Error_;
 static NSString *Warning_;
 
@@ -2975,11 +3033,17 @@ static NSString *Warning_;
     return era_;
 }
 
     return era_;
 }
 
+- (void) releasePackages {
+    CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
+    CFArrayRemoveAllValues(packages_);
+}
+
 - (void) dealloc {
 - (void) dealloc {
+    // XXX: actually implement this thing
     _assert(false);
     _assert(false);
-    NSRecycleZone(zone_);
-    // XXX: malloc_destroy_zone(zone_);
+    [self releasePackages];
     apr_pool_destroy(pool_);
     apr_pool_destroy(pool_);
+    NSRecycleZone(zone_);
     [super dealloc];
 }
 
     [super dealloc];
 }
 
@@ -3069,7 +3133,7 @@ static NSString *Warning_;
 }
 
 - (Package *) packageWithName:(NSString *)name {
 }
 
 - (Package *) packageWithName:(NSString *)name {
-@synchronized ([Database class]) {
+@synchronized (self) {
     if (static_cast<pkgDepCache *>(cache_) == NULL)
         return nil;
     pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
     if (static_cast<pkgDepCache *>(cache_) == NULL)
         return nil;
     pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
@@ -3087,7 +3151,13 @@ static NSString *Warning_;
         zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
         apr_pool_create(&pool_, NULL);
 
         zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
         apr_pool_create(&pool_, NULL);
 
-        packages_ = [[NSMutableArray alloc] init];
+        size_t capacity(MetaFile_->active_);
+        if (capacity == 0)
+            capacity = 16384;
+        else
+            capacity += 1024;
+
+        packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
 
         int fds[2];
 
 
         int fds[2];
 
@@ -3100,7 +3170,7 @@ static NSString *Warning_;
         [NSThread
             detachNewThreadSelector:@selector(_readCydia:)
             toTarget:self
         [NSThread
             detachNewThreadSelector:@selector(_readCydia:)
             toTarget:self
-            withObject:[[NSNumber numberWithInt:fds[0]] retain]
+            withObject:[NSNumber numberWithInt:fds[0]]
         ];
 
         _assert(pipe(fds) != -1);
         ];
 
         _assert(pipe(fds) != -1);
@@ -3109,7 +3179,7 @@ static NSString *Warning_;
         [NSThread
             detachNewThreadSelector:@selector(_readStatus:)
             toTarget:self
         [NSThread
             detachNewThreadSelector:@selector(_readStatus:)
             toTarget:self
-            withObject:[[NSNumber numberWithInt:fds[0]] retain]
+            withObject:[NSNumber numberWithInt:fds[0]]
         ];
 
         _assert(pipe(fds) != -1);
         ];
 
         _assert(pipe(fds) != -1);
@@ -3125,7 +3195,7 @@ static NSString *Warning_;
         [NSThread
             detachNewThreadSelector:@selector(_readOutput:)
             toTarget:self
         [NSThread
             detachNewThreadSelector:@selector(_readOutput:)
             toTarget:self
-            withObject:[[NSNumber numberWithInt:fds[0]] retain]
+            withObject:[NSNumber numberWithInt:fds[0]]
         ];
     } return self;
 }
         ];
     } return self;
 }
@@ -3155,7 +3225,7 @@ static NSString *Warning_;
 }
 
 - (NSArray *) packages {
 }
 
 - (NSArray *) packages {
-    return packages_;
+    return (NSArray *) packages_;
 }
 
 - (NSArray *) sources {
 }
 
 - (NSArray *) sources {
@@ -3171,7 +3241,7 @@ static NSString *Warning_;
 
     NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
 
 
     NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
 
-    for (Package *package in packages_) {
+    for (Package *package in [self packages]) {
         if (![package broken])
             continue;
         pkgCache::PkgIterator pkg([package iterator]);
         if (![package broken])
             continue;
         pkgCache::PkgIterator pkg([package iterator]);
@@ -3263,13 +3333,11 @@ static NSString *Warning_;
     return [self popErrorWithTitle:title] || !success;
 }
 
     return [self popErrorWithTitle:title] || !success;
 }
 
-- (void) reloadData { _pooled
-@synchronized ([Database class]) {
-    @synchronized (self) {
-        ++era_;
-    }
+- (void) reloadData { CYPoolStart() {
+@synchronized (self) {
+    ++era_;
 
 
-    [packages_ removeAllObjects];
+    [self releasePackages];
     sources_.clear();
 
     _error->Discard();
     sources_.clear();
 
     _error->Discard();
@@ -3288,15 +3356,12 @@ static NSString *Warning_;
     delete policy_;
     policy_ = NULL;
 
     delete policy_;
     policy_ = NULL;
 
-    if (now_ != nil) {
-        [now_ release];
-        now_ = nil;
-    }
-
     cache_.Close();
 
     apr_pool_clear(pool_);
     cache_.Close();
 
     apr_pool_clear(pool_);
+
     NSRecycleZone(zone_);
     NSRecycleZone(zone_);
+    zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
 
     int chk(creat("/tmp/cydia.chk", 0644));
     if (chk != -1)
 
     int chk(creat("/tmp/cydia.chk", 0644));
     if (chk != -1)
@@ -3329,7 +3394,7 @@ static NSString *Warning_;
 
     unlink("/tmp/cydia.chk");
 
 
     unlink("/tmp/cydia.chk");
 
-    now_ = [[NSDate date] retain];
+    now_ = [[NSDate date] timeIntervalSince1970];
 
     policy_ = new pkgDepCache::Policy();
     records_ = new pkgRecords(cache_);
 
     policy_ = new pkgDepCache::Policy();
     records_ = new pkgRecords(cache_);
@@ -3362,8 +3427,6 @@ static NSString *Warning_;
             return;
     }
 
             return;
     }
 
-    _trace();
-
     for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
         std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
         for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
     for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
         std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
         for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
@@ -3375,8 +3438,6 @@ static NSString *Warning_;
             }
     }
 
             }
     }
 
-    _trace();
-
     {
         /*std::vector<Package *> packages;
         packages.reserve(std::max(10000U, [packages_ count] + 1000));
     {
         /*std::vector<Package *> packages;
         packages.reserve(std::max(10000U, [packages_ count] + 1000));
@@ -3388,7 +3449,7 @@ static NSString *Warning_;
         for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
             if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
                 //packages.push_back(package);
         for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
             if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
                 //packages.push_back(package);
-                [packages_ addObject:package];
+                CFArrayAppendValue(packages_, [package retain]);
 
         _trace();
 
 
         _trace();
 
@@ -3398,9 +3459,9 @@ static NSString *Warning_;
             packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
         _trace();*/
 
             packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
         _trace();*/
 
-        [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
-        [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
-        [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
+        [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
 
         /*_trace();
         PrintTimes();
 
         /*_trace();
         PrintTimes();
@@ -3414,11 +3475,32 @@ static NSString *Warning_;
 
         //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
 
 
         //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
 
-        CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
+        CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
 
         //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
 
         _trace();
 
         //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
 
         _trace();
+
+        size_t count(CFArrayGetCount(packages_));
+        MetaFile_->active_ = count;
+
+        for (size_t index(0); index != count; ++index)
+            [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
+
+        _trace();
+    }
+} } CYPoolEnd() _trace(); }
+
+- (void) clear {
+@synchronized (self) {
+    delete resolver_;
+    resolver_ = new pkgProblemResolver(cache_);
+
+    for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
+        if (!cache_[iterator].Keep()) {
+            cache_->MarkKeep(iterator, false);
+            cache_->SetReInstall(iterator, false);
+        }
     }
 } }
 
     }
 } }
 
@@ -3565,11 +3647,6 @@ static NSString *Warning_;
     [self updateWithStatus:status_];
 }
 
     [self updateWithStatus:status_];
 }
 
-- (void) setVisible {
-    for (Package *package in packages_)
-        [package setVisible];
-}
-
 - (void) updateWithStatus:(Status &)status {
     _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
     NSString *title(UCLocalize("REFRESHING_DATA"));
 - (void) updateWithStatus:(Status &)status {
     _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
     NSString *title(UCLocalize("REFRESHING_DATA"));
@@ -3625,7 +3702,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 /* Web Scripting {{{ */
 @interface CydiaObject : NSObject {
     id indirect_;
 /* Web Scripting {{{ */
 @interface CydiaObject : NSObject {
     id indirect_;
-    id delegate_;
+    _transient id delegate_;
 }
 
 - (id) initWithDelegate:(IndirectDelegate *)indirect;
 }
 
 - (id) initWithDelegate:(IndirectDelegate *)indirect;
@@ -3695,14 +3772,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         return @"getPackageById";
     else if (selector == @selector(installPackages:))
         return @"installPackages";
         return @"getPackageById";
     else if (selector == @selector(installPackages:))
         return @"installPackages";
-    else if (selector == @selector(setAutoPopup:))
-        return @"setAutoPopup";
     else if (selector == @selector(setButtonImage:withStyle:toFunction:))
         return @"setButtonImage";
     else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
         return @"setButtonTitle";
     else if (selector == @selector(setButtonImage:withStyle:toFunction:))
         return @"setButtonImage";
     else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
         return @"setButtonTitle";
-    else if (selector == @selector(setFinishHook:))
-        return @"setFinishHook";
     else if (selector == @selector(setPopupHook:))
         return @"setPopupHook";
     else if (selector == @selector(setSpecial:))
     else if (selector == @selector(setPopupHook:))
         return @"setPopupHook";
     else if (selector == @selector(setSpecial:))
@@ -3735,7 +3808,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (NSArray *) getInstalledPackages {
     NSArray *packages([[Database sharedInstance] packages]);
 
 - (NSArray *) getInstalledPackages {
     NSArray *packages([[Database sharedInstance] packages]);
-    NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
+    NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
     for (Package *package in packages)
         if ([package installed] != nil)
             [installed addObject:package];
     for (Package *package in packages)
         if ([package installed] != nil)
             [installed addObject:package];
@@ -3813,10 +3886,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
 }
 
     [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
 }
 
-- (void) setAutoPopup:(BOOL)popup {
-    [indirect_ setAutoPopup:popup];
-}
-
 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
     [indirect_ setButtonImage:button withStyle:style toFunction:function];
 }
 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
     [indirect_ setButtonImage:button withStyle:style toFunction:function];
 }
@@ -3838,10 +3907,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     Changed_ = true;
 }
 
     Changed_ = true;
 }
 
-- (void) setFinishHook:(id)function {
-    [indirect_ setFinishHook:function];
-}
-
 - (void) setPopupHook:(id)function {
     [indirect_ setPopupHook:function];
 }
 - (void) setPopupHook:(id)function {
     [indirect_ setPopupHook:function];
 }
@@ -3887,8 +3952,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
 }
 
 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
 }
 
-- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
-    [super webView:sender didClearWindowObject:window forFrame:frame];
+- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
+    [super webView:view didClearWindowObject:window forFrame:frame];
 
     WebDataSource *source([frame dataSource]);
     NSURLResponse *response([source response]);
 
     WebDataSource *source([frame dataSource]);
     NSURLResponse *response([source response]);
@@ -3924,8 +3989,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
 }
 
         [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
 }
 
-- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
-    NSMutableURLRequest *copy = [request mutableCopy];
+- (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
+    NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
     [self _setMoreHeaders:copy];
     return copy;
 }
     [self _setMoreHeaders:copy];
     return copy;
 }
@@ -3939,7 +4004,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
         cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
 
     if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
         cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
 
-        WebView *webview([document_ webView]);
+        WebView *webview([[webview_ _documentView] webView]);
 
         Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
 
 
         Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
 
@@ -4015,15 +4080,18 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
     }
 }
 
-- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
+- (void) _doContinue {
     [self dismissModalViewControllerAnimated:YES];
     [delegate_ cancelAndClear:NO];
     [self dismissModalViewControllerAnimated:YES];
     [delegate_ cancelAndClear:NO];
+}
 
 
+- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
+    [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
     return nil;
 }
 
     return nil;
 }
 
-- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
-    [super webView:sender didClearWindowObject:window forFrame:frame];
+- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
+    [super webView:view didClearWindowObject:window forFrame:frame];
     [window setValue:changes_ forKey:@"changes"];
     [window setValue:issues_ forKey:@"issues"];
     [window setValue:sizes_ forKey:@"sizes"];
     [window setValue:changes_ forKey:@"changes"];
     [window setValue:issues_ forKey:@"issues"];
     [window setValue:sizes_ forKey:@"sizes"];
@@ -4117,32 +4185,30 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
         [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
 
 
         [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
 
-        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("CANCEL")
             // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(cancelButtonClicked)
             initWithTitle:UCLocalize("CANCEL")
             // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(cancelButtonClicked)
-        ];
-        [[self navigationItem] setLeftBarButtonItem:leftItem];
-        [leftItem release];
+        ] autorelease]];
     } return self;
 }
 
 - (void) applyRightButton {
     } return self;
 }
 
 - (void) applyRightButton {
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("CONFIRM")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(confirmButtonClicked)
-    ];
 #if !AlwaysReload && !IgnoreInstall
 #if !AlwaysReload && !IgnoreInstall
-    if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
-    else [super applyRightButton];
+    if (issues_ == nil && ![self isLoading])
+        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("CONFIRM")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(confirmButtonClicked)
+        ] autorelease]];
+    else
+        [super applyRightButton];
 #else
     [[self navigationItem] setRightBarButtonItem:nil];
 #endif
 #else
     [[self navigationItem] setRightBarButtonItem:nil];
 #endif
-    [rightItem release];
 }
 
 - (void) cancelButtonClicked {
 }
 
 - (void) cancelButtonClicked {
@@ -4171,8 +4237,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 /* Progress Data {{{ */
 @interface ProgressData : NSObject {
     SEL selector_;
 /* Progress Data {{{ */
 @interface ProgressData : NSObject {
     SEL selector_;
-    id target_;
-    id object_;
+    // XXX: should these really both be _transient?
+    _transient id target_;
+    _transient id object_;
 }
 
 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
 }
 
 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
@@ -4299,16 +4366,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     CGRect prgrect = {{
         (bounds.size.width - prgsize.width) / 2,
 
     CGRect prgrect = {{
         (bounds.size.width - prgsize.width) / 2,
-        bounds.size.height - prgsize.height - 64
+        bounds.size.height - prgsize.height - 20
     }, prgsize};
 
     }, prgsize};
 
-    float closewidth = bounds.size.width - 20;
-    if (closewidth > 300) closewidth = 300;
+    float closewidth = std::min(bounds.size.width - 20, 300.0f);
 
     [progress_ setFrame:prgrect];
     [status_ setFrame:CGRectMake(
         10,
 
     [progress_ setFrame:prgrect];
     [status_ setFrame:CGRectMake(
         10,
-        bounds.size.height - prgsize.height - 94,
+        bounds.size.height - prgsize.height - 50,
         bounds.size.width - 20,
         24
     )];
         bounds.size.width - 20,
         24
     )];
@@ -4316,11 +4382,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         10,
         20,
         bounds.size.width - 20,
         10,
         20,
         bounds.size.width - 20,
-        bounds.size.height - 106
+        bounds.size.height - 62
     )];
     [close_ setFrame:CGRectMake(
         (bounds.size.width - closewidth) / 2,
     )];
     [close_ setFrame:CGRectMake(
         (bounds.size.width - closewidth) / 2,
-        bounds.size.height - prgsize.height - 94,
+        bounds.size.height - prgsize.height - 50,
         closewidth,
         32 + prgsize.height
     )];
         closewidth,
         32 + prgsize.height
     )];
@@ -4343,8 +4409,10 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
     if ([context isEqualToString:@"conffile"]) {
         FILE *input = [database_ input];
 
     if ([context isEqualToString:@"conffile"]) {
         FILE *input = [database_ input];
-        if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
-        else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
+        if (button == [alert cancelButtonIndex])
+            fprintf(input, "N\n");
+        else if (button == [alert firstOtherButtonIndex])
+            fprintf(input, "Y\n");
         fflush(input);
     }
 }
         fflush(input);
     }
 }
@@ -4434,8 +4502,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
     [[data target] performSelector:[data selector] withObject:[data object]];
 
 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
     [[data target] performSelector:[data selector] withObject:[data object]];
-    [data release];
-
     [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
 }
 
     [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
 }
 
@@ -4489,11 +4555,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [NSThread
         detachNewThreadSelector:@selector(_detachNewThreadData:)
         toTarget:self
     [NSThread
         detachNewThreadSelector:@selector(_detachNewThreadData:)
         toTarget:self
-        withObject:[[ProgressData alloc]
+        withObject:[[[ProgressData alloc]
             initWithSelector:selector
             target:target
             object:object
             initWithSelector:selector
             target:target
             object:object
-        ]
+        ] autorelease]
     ];
 }
 
     ];
 }
 
@@ -4623,9 +4689,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 
 @implementation ContentView
 @end
 
 @implementation ContentView
+
 - (id) initWithFrame:(CGRect)frame {
     if ((self = [super initWithFrame:frame]) != nil) {
 - (id) initWithFrame:(CGRect)frame {
     if ((self = [super initWithFrame:frame]) != nil) {
-        /* Fix landscape stretching. */
         [self setNeedsDisplayOnBoundsChange:YES];
     } return self;
 }
         [self setNeedsDisplayOnBoundsChange:YES];
     } return self;
 }
@@ -4638,10 +4704,47 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [super drawRect:rect];
     [delegate_ drawContentRect:rect];
 }
     [super drawRect:rect];
     [delegate_ drawContentRect:rect];
 }
+
+@end
+/* }}} */
+/* Cydia TableView Cell {{{ */
+@interface CYTableViewCell : UITableViewCell {
+    ContentView *content_;
+    bool highlighted_;
+}
+
+@end
+
+@implementation CYTableViewCell
+
+- (void) dealloc {
+    [content_ release];
+    [super dealloc];
+}
+
+- (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
+    //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
+
+    if (view == content_) {
+        //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
+        highlighted_ = highlighted;
+    }
+
+    [super _updateHighlightColorsForView:view highlighted:highlighted];
+}
+
+- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
+    //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
+    highlighted_ = selected;
+
+    [super setSelected:selected animated:animated];
+    [content_ setNeedsDisplay];
+}
+
 @end
 /* }}} */
 /* Package Cell {{{ */
 @end
 /* }}} */
 /* Package Cell {{{ */
-@interface PackageCell : UITableViewCell <
+@interface PackageCell : CYTableViewCell <
     ContentDelegate
 > {
     UIImage *icon_;
     ContentDelegate
 > {
     UIImage *icon_;
@@ -4651,10 +4754,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSString *source_;
     UIImage *badge_;
     Package *package_;
     NSString *source_;
     UIImage *badge_;
     Package *package_;
-    UIColor *color_;
-    ContentView *content_;
-    BOOL faded_;
-    float fade_;
     UIImage *placard_;
 }
 
     UIImage *placard_;
 }
 
@@ -4705,15 +4804,9 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) dealloc {
     [self clearPackage];
 
 - (void) dealloc {
     [self clearPackage];
-    [content_ release];
-    [color_ release];
     [super dealloc];
 }
 
     [super dealloc];
 }
 
-- (float) fade {
-    return faded_ ? [self selectionPercent] : fade_;
-}
-
 - (PackageCell *) init {
     CGRect frame(CGRectMake(0, 0, 320, 74));
     if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
 - (PackageCell *) init {
     CGRect frame(CGRectMake(0, 0, 320, 74));
     if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
@@ -4726,8 +4819,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
         [content_ setDelegate:self];
         [content_ setOpaque:YES];
 
         [content_ setDelegate:self];
         [content_ setOpaque:YES];
-        if ([self respondsToSelector:@selector(selectionPercent)])
-            faded_ = YES;
     } return self;
 }
 
     } return self;
 }
 
@@ -4798,7 +4889,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) drawContentRect:(CGRect)rect {
 }
 
 - (void) drawContentRect:(CGRect)rect {
-    bool selected([self isSelected]);
+    bool highlighted(highlighted_);
     float width([self bounds].size.width);
 
 #if 0
     float width([self bounds].size.width);
 
 #if 0
@@ -4829,15 +4920,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         )];
     }
 
         )];
     }
 
-    if (selected)
+    if (highlighted)
         UISetColor(White_);
 
         UISetColor(White_);
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(commercial_ ? Purple_ : Black_);
     [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
     [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 
         UISetColor(commercial_ ? Purple_ : Black_);
     [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
     [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(commercial_ ? Purplish_ : Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 
         UISetColor(commercial_ ? Purplish_ : Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 
@@ -4845,12 +4936,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
 }
 
         [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
 }
 
-- (void) setSelected:(BOOL)selected animated:(BOOL)fade {
-    //[self _setBackgroundColor];
-    [super setSelected:selected animated:fade];
-    [content_ setNeedsDisplay];
-}
-
 + (int) heightForPackage:(Package *)package {
     return 73;
 }
 + (int) heightForPackage:(Package *)package {
     return 73;
 }
@@ -4858,7 +4943,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 /* }}} */
 /* Section Cell {{{ */
 @end
 /* }}} */
 /* Section Cell {{{ */
-@interface SectionCell : UITableViewCell <
+@interface SectionCell : CYTableViewCell <
     ContentDelegate
 > {
     NSString *basic_;
     ContentDelegate
 > {
     NSString *basic_;
@@ -4866,8 +4951,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSString *name_;
     NSString *count_;
     UIImage *icon_;
     NSString *name_;
     NSString *count_;
     UIImage *icon_;
-    ContentView *content_;
-    id switch_;
+    UISwitch *switch_;
     BOOL editing_;
 }
 
     BOOL editing_;
 }
 
@@ -4903,15 +4987,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [self clearSection];
     [icon_ release];
     [switch_ release];
     [self clearSection];
     [icon_ release];
     [switch_ release];
-    [content_ release];
-
     [super dealloc];
 }
 
 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
     if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
         icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
     [super dealloc];
 }
 
 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
     if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
         icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
-        switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
+        switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
         [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
 
         UIView *content([self contentView]);
         [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
 
         UIView *content([self contentView]);
@@ -4927,14 +5009,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) onSwitch:(id)sender {
 }
 
 - (void) onSwitch:(id)sender {
-    NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
+    NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
     if (metadata == nil) {
         metadata = [NSMutableDictionary dictionaryWithCapacity:2];
         [Sections_ setObject:metadata forKey:basic_];
     }
 
     if (metadata == nil) {
         metadata = [NSMutableDictionary dictionaryWithCapacity:2];
         [Sections_ setObject:metadata forKey:basic_];
     }
 
-    Changed_ = true;
     [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
     [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
+    Changed_ = true;
 }
 
 - (void) setSection:(Section *)section editing:(BOOL)editing {
 }
 
 - (void) setSection:(Section *)section editing:(BOOL)editing {
@@ -4968,6 +5050,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 
     [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
     }
 
     [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
+    [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
+
     [content_ setNeedsDisplay];
 }
 
     [content_ setNeedsDisplay];
 }
 
@@ -4979,20 +5063,19 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) drawContentRect:(CGRect)rect {
 }
 
 - (void) drawContentRect:(CGRect)rect {
-    BOOL selected = [self isSelected];
+    bool highlighted(highlighted_);
 
     [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
 
 
     [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
 
-    if (selected)
+    if (highlighted)
         UISetColor(White_);
 
         UISetColor(White_);
 
-    if (!selected)
-        UISetColor(Black_);
-
     float width(rect.size.width);
     if (editing_)
         width -= 87;
 
     float width(rect.size.width);
     if (editing_)
         width -= 87;
 
+    if (!highlighted)
+        UISetColor(Black_);
     [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
     CGSize size = [count_ sizeWithFont:Font14_];
     [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
     CGSize size = [count_ sizeWithFont:Font14_];
@@ -5134,6 +5217,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     NSString *name_;
     bool commercial_;
     NSMutableArray *buttons_;
     NSString *name_;
     bool commercial_;
     NSMutableArray *buttons_;
+    UIBarButtonItem *button_;
 }
 
 - (id) initWithDatabase:(Database *)database;
 }
 
 - (id) initWithDatabase:(Database *)database;
@@ -5148,7 +5232,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [package_ release];
     if (name_ != nil)
         [name_ release];
         [package_ release];
     if (name_ != nil)
         [name_ release];
+
     [buttons_ release];
     [buttons_ release];
+
+    if (button_ != nil)
+        [button_ release];
+
     [super dealloc];
 }
 
     [super dealloc];
 }
 
@@ -5186,12 +5275,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     }
 }
 
     }
 }
 
-- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
-    return [super webView:sender didFinishLoadForFrame:frame];
-}
-
-- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
-    [super webView:sender didClearWindowObject:window forFrame:frame];
+- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
+    [super webView:view didClearWindowObject:window forFrame:frame];
     [window setValue:package_ forKey:@"package"];
 }
 
     [window setValue:package_ forKey:@"package"];
 }
 
@@ -5248,13 +5333,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (UIBarButtonItem *) rightButton {
 }
 
 - (UIBarButtonItem *) rightButton {
-    int count = [buttons_ count];
-    return [[[UIBarButtonItem alloc]
-        initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(customButtonClicked)
-    ] autorelease];
+    return button_;
 }
 #endif
 
 }
 #endif
 
@@ -5297,30 +5376,26 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
             [buttons_ addObject:UCLocalize("REINSTALL")];
         if (![package_ uninstalled])
             [buttons_ addObject:UCLocalize("REMOVE")];
             [buttons_ addObject:UCLocalize("REINSTALL")];
         if (![package_ uninstalled])
             [buttons_ addObject:UCLocalize("REMOVE")];
+    }
 
 
-        if (special_ != NULL) {
-            CGRect frame([document_ frame]);
-            frame.size.height = 0;
-            [document_ setFrame:frame];
-
-            if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
-                [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
-            else
-                [scroller_ scrollRectToVisible:CGRectZero animated:NO];
-
-            WebThreadLock();
-            [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
+    if (button_ != nil)
+        [button_ release];
 
 
-            [self setButtonTitle:nil withStyle:nil toFunction:nil];
+    NSString *title;
+    switch ([buttons_ count]) {
+        case 0: title = nil; break;
+        case 1: title = [buttons_ objectAtIndex:0]; break;
+        default: title = UCLocalize("MODIFY"); break;
+    }
 
 
-            [self setFinishHook:nil];
-            [self setPopupHook:nil];
-            WebThreadUnlock();
+    button_ = [[UIBarButtonItem alloc]
+        initWithTitle:title
+        style:UIBarButtonItemStylePlain
+        target:self
+        action:@selector(customButtonClicked)
+    ];
 
 
-            //[self yieldToSelector:@selector(callFunction:) withObject:special_];
-            [super callFunction:special_];
-        }
-    }
+    [self reloadURL];
 }
 
 - (bool) isLoading {
 }
 
 - (bool) isLoading {
@@ -5339,14 +5414,17 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     UITableViewDelegate
 > {
     _transient Database *database_;
     UITableViewDelegate
 > {
     _transient Database *database_;
+    unsigned era_;
     NSMutableArray *packages_;
     NSMutableArray *sections_;
     UITableView *list_;
     NSMutableArray *index_;
     NSMutableDictionary *indices_;
     NSMutableArray *packages_;
     NSMutableArray *sections_;
     UITableView *list_;
     NSMutableArray *index_;
     NSMutableDictionary *indices_;
-    id target_;
+    // XXX: this target_ seems to be delegate_. :(
+    _transient id target_;
     SEL action_;
     SEL action_;
-    id delegate_;
+    // XXX: why do we even have this delegate_?
+    _transient id delegate_;
 }
 
 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
 }
 
 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
@@ -5394,11 +5472,15 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
 }
 
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
+@synchronized (database_) {
+    if ([database_ era] != era_)
+        return nil;
+
     Section *section([sections_ objectAtIndex:[path section]]);
     NSInteger row([path row]);
     Package *package([packages_ objectAtIndex:([section row] + row)]);
     Section *section([sections_ objectAtIndex:[path section]]);
     NSInteger row([path row]);
     Package *package([packages_ objectAtIndex:([section row] + row)]);
-    return package;
-}
+    return [[package retain] autorelease];
+} }
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
@@ -5463,6 +5545,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) reloadData {
 }
 
 - (void) reloadData {
+    era_ = [database_ era];
     NSArray *packages = [database_ packages];
 
     [packages_ removeAllObjects];
     NSArray *packages = [database_ packages];
 
     [packages_ removeAllObjects];
@@ -5675,14 +5758,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @end
 /* }}} */
 /* Source Cell {{{ */
 @end
 /* }}} */
 /* Source Cell {{{ */
-@interface SourceCell : UITableViewCell <
+@interface SourceCell : CYTableViewCell <
     ContentDelegate
 > {
     UIImage *icon_;
     NSString *origin_;
     NSString *description_;
     NSString *label_;
     ContentDelegate
 > {
     UIImage *icon_;
     NSString *origin_;
     NSString *description_;
     NSString *label_;
-    ContentView *content_;
 }
 
 - (void) setSource:(Source *)source;
 }
 
 - (void) setSource:(Source *)source;
@@ -5721,7 +5803,6 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 - (void) dealloc {
     [self clearSource];
 
 - (void) dealloc {
     [self clearSource];
-    [content_ release];
     [super dealloc];
 }
 
     [super dealloc];
 }
 
@@ -5740,30 +5821,25 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     } return self;
 }
 
     } return self;
 }
 
-- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
-    [super setSelected:selected animated:animated];
-    [content_ setNeedsDisplay];
-}
-
 - (void) drawContentRect:(CGRect)rect {
 - (void) drawContentRect:(CGRect)rect {
-    bool selected([self isSelected]);
+    bool highlighted(highlighted_);
     float width(rect.size.width);
 
     if (icon_ != nil)
         [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
 
     float width(rect.size.width);
 
     if (icon_ != nil)
         [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
 
-    if (selected)
+    if (highlighted)
         UISetColor(White_);
 
         UISetColor(White_);
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(Black_);
     [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
         UISetColor(Black_);
     [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(Blue_);
     [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 
         UISetColor(Blue_);
     [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
 
-    if (!selected)
+    if (!highlighted)
         UISetColor(Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 }
         UISetColor(Gray_);
     [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
 }
@@ -5801,7 +5877,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation SourceTable
 
 
 @implementation SourceTable
 
-- (void) _deallocConnection:(NSURLConnection *)connection {
+- (void) _releaseConnection:(NSURLConnection *)connection {
     if (connection != nil) {
         [connection cancel];
         //[connection setDelegate:nil];
     if (connection != nil) {
         [connection cancel];
         //[connection setDelegate:nil];
@@ -5817,11 +5893,11 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if (error_ != nil)
         [error_ release];
 
     if (error_ != nil)
         [error_ release];
 
-    //[self _deallocConnection:installer_];
-    [self _deallocConnection:trivial_];
-    [self _deallocConnection:trivial_gz_];
-    [self _deallocConnection:trivial_bz2_];
-    //[self _deallocConnection:automatic_];
+    //[self _releaseConnection:installer_];
+    [self _releaseConnection:trivial_];
+    [self _releaseConnection:trivial_gz_];
+    [self _releaseConnection:trivial_bz2_];
+    //[self _releaseConnection:automatic_];
 
     [sources_ release];
     [list_ release];
 
     [sources_ release];
     [list_ release];
@@ -5942,6 +6018,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) _endConnection:(NSURLConnection *)connection {
 }
 
 - (void) _endConnection:(NSURLConnection *)connection {
+    // XXX: the memory management in this method is horribly awkward
+
     NSURLConnection **field = NULL;
     if (connection == trivial_)
         field = &trivial_;
     NSURLConnection **field = NULL;
     if (connection == trivial_)
         field = &trivial_;
@@ -6081,6 +6159,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
                 cydia_ = false;
 
 
                 cydia_ = false;
 
+                // XXX: this is stupid
                 hud_ = [[delegate_ addProgressHUD] retain];
                 [hud_ setText:UCLocalize("VERIFYING_URL")];
             } break;
                 hud_ = [[delegate_ addProgressHUD] retain];
                 [hud_ setText:UCLocalize("VERIFYING_URL")];
             } break;
@@ -6145,11 +6224,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
     _trace();
 
     [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
     _trace();
 
-     int count([sources_ count]);
+    int count([sources_ count]);
     offset_ = 0;
     for (int i = 0; i != count; i++) {
     offset_ = 0;
     for (int i = 0; i != count; i++) {
-        if ([[sources_ objectAtIndex:i] record] == nil) break;
-        else offset_++;
+        if ([[sources_ objectAtIndex:i] record] == nil)
+            break;
+        offset_++;
     }
 
     [list_ setEditing:NO];
     }
 
     [list_ setEditing:NO];
@@ -6188,34 +6268,27 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
 }
 
 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
-    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
+    [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
         initWithTitle:UCLocalize("ADD")
         style:UIBarButtonItemStylePlain
         target:self
         action:@selector(addButtonClicked)
         initWithTitle:UCLocalize("ADD")
         style:UIBarButtonItemStylePlain
         target:self
         action:@selector(addButtonClicked)
-    ];
-    [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
-    [leftItem release];
+    ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
 
 
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
-        style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+        initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
+        style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
         target:self
         action:@selector(editButtonClicked)
         target:self
         action:@selector(editButtonClicked)
-    ];
-    [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
-    [rightItem release];
+    ] autorelease] animated:animated];
 
 
-    if (IsWildcat_ && !editing) {
-        UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
+    if (IsWildcat_ && !editing)
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("SETTINGS")
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(settingsButtonClicked)
             initWithTitle:UCLocalize("SETTINGS")
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(settingsButtonClicked)
-            ];
-        [[self navigationItem] setLeftBarButtonItem:settingsItem];
-        [settingsItem release];
-    }
+        ] autorelease]];
 }
 
 - (void) settingsButtonClicked {
 }
 
 - (void) settingsButtonClicked {
@@ -6252,7 +6325,7 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (NSString *) title { return UCLocalize("INSTALLED"); }
 
 - (id) initWithDatabase:(Database *)database {
 - (NSString *) title { return UCLocalize("INSTALLED"); }
 
 - (id) initWithDatabase:(Database *)database {
-    if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
+    if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
         [self updateRoleButton];
         [self queueStatusDidChange];
     } return self;
         [self updateRoleButton];
         [self queueStatusDidChange];
     } return self;
@@ -6267,15 +6340,16 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) queueStatusDidChange {
 #if !AlwaysReload
     if (IsWildcat_) {
 - (void) queueStatusDidChange {
 #if !AlwaysReload
     if (IsWildcat_) {
-        UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
-            initWithTitle:UCLocalize("QUEUE")
-            style:UIBarButtonItemStyleDone
-            target:self
-            action:@selector(queueButtonClicked)
-        ];
-        if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
-        else [[self navigationItem] setLeftBarButtonItem:nil];
-        [queueItem release];
+        if (Queuing_) {
+            [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+                initWithTitle:UCLocalize("QUEUE")
+                style:UIBarButtonItemStyleDone
+                target:self
+                action:@selector(queueButtonClicked)
+            ] autorelease]];
+        } else {
+            [[self navigationItem] setLeftBarButtonItem:nil];
+        }
     }
 #endif
 }
     }
 #endif
 }
@@ -6285,14 +6359,13 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 }
 
 - (void) updateRoleButton {
 }
 
 - (void) updateRoleButton {
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
-        style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
-        target:self
-        action:@selector(roleButtonClicked)
-    ];
-    if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
-    [rightItem release];
+    if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
+        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
+            style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
+            target:self
+            action:@selector(roleButtonClicked)
+        ] autorelease]];
 }
 
 - (void) roleButtonClicked {
 }
 
 - (void) roleButtonClicked {
@@ -6326,6 +6399,8 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
         [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
     if (UniqueID_ != nil)
         [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
         [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
     if (UniqueID_ != nil)
         [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
+    if (PLMN_ != nil)
+        [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
 }
 
 - (void) aboutButtonClicked {
 }
 
 - (void) aboutButtonClicked {
@@ -6381,14 +6456,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
     if ((self = [super init]) != nil) {
         [[self navigationItem] setTitle:UCLocalize("MANAGE")];
 
     if ((self = [super init]) != nil) {
         [[self navigationItem] setTitle:UCLocalize("MANAGE")];
 
-        UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("SETTINGS")
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(settingsButtonClicked)
             initWithTitle:UCLocalize("SETTINGS")
             style:UIBarButtonItemStylePlain
             target:self
             action:@selector(settingsButtonClicked)
-        ];
-        [[self navigationItem] setLeftBarButtonItem:settingsItem];
-        [settingsItem release];
+        ] autorelease]];
 
         [self queueStatusDidChange];
     } return self;
 
         [self queueStatusDidChange];
     } return self;
@@ -6415,15 +6488,12 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 - (void) queueStatusDidChange {
 #if !AlwaysReload
     if (!IsWildcat_ && Queuing_) {
 - (void) queueStatusDidChange {
 #if !AlwaysReload
     if (!IsWildcat_ && Queuing_) {
-        UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
+        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
             initWithTitle:UCLocalize("QUEUE")
             style:UIBarButtonItemStyleDone
             target:self
             action:@selector(queueButtonClicked)
             initWithTitle:UCLocalize("QUEUE")
             style:UIBarButtonItemStyleDone
             target:self
             action:@selector(queueButtonClicked)
-        ];
-        [[self navigationItem] setRightBarButtonItem:queueItem];
-
-        [queueItem release];
+        ] autorelease]];
     } else {
         [[self navigationItem] setRightBarButtonItem:nil];
     }
     } else {
         [[self navigationItem] setRightBarButtonItem:nil];
     }
@@ -6449,6 +6519,14 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 
 @implementation RefreshBar
 
 
 @implementation RefreshBar
 
+- (void) dealloc {
+    [indicator_ release];
+    [prompt_ release];
+    [progress_ release];
+    [cancel_ release];
+    [super dealloc];
+}
+
 - (void) positionViews {
     CGRect frame = [cancel_ frame];
     frame.origin.x = [self frame].size.width - frame.size.width - 5;
 - (void) positionViews {
     CGRect frame = [cancel_ frame];
     frame.origin.x = [self frame].size.width - frame.size.width - 5;
@@ -6548,10 +6626,25 @@ bool DepSubstrate(const pkgCache::VerIterator &iterator) {
 @class CYNavigationController;
 
 /* Cydia Tab Bar Controller {{{ */
 @class CYNavigationController;
 
 /* Cydia Tab Bar Controller {{{ */
-@interface CYTabBarController : UITabBarController {
-    Database *database_;
+@interface CYTabBarController : UITabBarController <
+    ProgressDelegate
+> {
+    _transient Database *database_;
+    RefreshBar *refreshbar_;
+
+    bool dropped_;
+    bool updating_;
+    // XXX: ok, "updatedelegate_"?...
+    _transient NSObject<CydiaDelegate> *updatedelegate_;
+
+    id root_;
 }
 
 }
 
+- (void) dropBar:(BOOL)animated;
+- (void) beginUpdate;
+- (void) raiseBar:(BOOL)animated;
+- (BOOL) updating;
+
 @end
 
 @implementation CYTabBarController
 @end
 
 @implementation CYTabBarController
@@ -6570,46 +6663,270 @@ freeing the view controllers on tab change */
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
 - (id) initWithDatabase:(Database *)database {
     if ((self = [super init]) != nil) {
         database_ = database;
-    } return self;
-}
 
 
-@end
-/* }}} */
+        [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
 
 
-/* Cydia Navigation Controller {{{ */
-@interface CYNavigationController : UINavigationController {
-    _transient Database *database_;
-    id<UINavigationControllerDelegate> delegate_;
+        refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
+    } return self;
 }
 
 }
 
-- (id) initWithDatabase:(Database *)database;
-- (void) reloadData;
-
-@end
-
-
-@implementation CYNavigationController
-
 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
-    // Inherit autorotation settings for modal parents.
-    if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
-        return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
-    } else {
-        return [super shouldAutorotateToInterfaceOrientation:orientation];
-    }
+    return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
 }
 
 }
 
-- (void) dealloc {
-    [super dealloc];
+- (void) setUpdate:(NSDate *)date {
+    [self beginUpdate];
 }
 
 }
 
-- (void) reloadData {
-    size_t count([[self viewControllers] count]);
-    for (size_t i(0); i != count; ++i) {
-        CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
-        [page reloadData];
-    }
-}
+- (void) beginUpdate {
+    [self dropBar:YES];
+    [refreshbar_ start];
+
+    updating_ = true;
+
+    [NSThread
+        detachNewThreadSelector:@selector(performUpdate)
+        toTarget:self
+        withObject:nil
+    ];
+}
+
+- (void) performUpdate { _pooled
+    Status status;
+    status.setDelegate(self);
+    [database_ updateWithStatus:status];
+
+    [self
+        performSelectorOnMainThread:@selector(completeUpdate)
+        withObject:nil
+        waitUntilDone:NO
+    ];
+}
+
+- (void) completeUpdate {
+    if (!updating_)
+        return;
+    updating_ = false;
+
+    [self raiseBar:YES];
+    [refreshbar_ stop];
+    [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
+}
+
+- (void) cancelUpdate {
+    updating_ = false;
+    [self raiseBar:YES];
+    [refreshbar_ stop];
+    [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
+}
+
+- (void) cancelPressed {
+    [self cancelUpdate];
+}
+
+- (BOOL) updating {
+    return updating_;
+}
+
+- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
+    [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
+}
+
+- (void) startProgress {
+}
+
+- (void) setProgressTitle:(NSString *)title {
+    [self
+        performSelectorOnMainThread:@selector(_setProgressTitle:)
+        withObject:title
+        waitUntilDone:YES
+    ];
+}
+
+- (bool) isCancelling:(size_t)received {
+    return !updating_;
+}
+
+- (void) setProgressPercent:(float)percent {
+    [self
+        performSelectorOnMainThread:@selector(_setProgressPercent:)
+        withObject:[NSNumber numberWithFloat:percent]
+        waitUntilDone:YES
+    ];
+}
+
+- (void) addProgressOutput:(NSString *)output {
+    [self
+        performSelectorOnMainThread:@selector(_addProgressOutput:)
+        withObject:output
+        waitUntilDone:YES
+    ];
+}
+
+- (void) _setProgressTitle:(NSString *)title {
+    [refreshbar_ setPrompt:title];
+}
+
+- (void) _setProgressPercent:(NSNumber *)percent {
+    [refreshbar_ setProgress:[percent floatValue]];
+}
+
+- (void) _addProgressOutput:(NSString *)output {
+}
+
+- (void) setUpdateDelegate:(id)delegate {
+    updatedelegate_ = delegate;
+}
+
+- (CGFloat) statusBarHeight {
+    if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
+        return [[UIApplication sharedApplication] statusBarFrame].size.height;
+    } else {
+        return [[UIApplication sharedApplication] statusBarFrame].size.width;
+    }
+}
+
+- (UIView *) transitionView {
+    if ([self respondsToSelector:@selector(_transitionView)])
+        return [self _transitionView];
+    else
+        return MSHookIvar<id>(self, "_viewControllerTransitionView");
+}
+
+- (void) dropBar:(BOOL)animated {
+    if (dropped_)
+        return;
+    dropped_ = true;
+
+    UIView *transition([self transitionView]);
+    [[self view] addSubview:refreshbar_];
+
+    CGRect barframe([refreshbar_ frame]);
+
+    if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
+        barframe.origin.y = [self statusBarHeight];
+    else
+        barframe.origin.y = 0;
+
+    [refreshbar_ setFrame:barframe];
+
+    if (animated)
+        [UIView beginAnimations:nil context:NULL];
+
+    CGRect viewframe = [transition frame];
+    viewframe.origin.y += barframe.size.height;
+    viewframe.size.height -= barframe.size.height;
+    [transition setFrame:viewframe];
+
+    if (animated)
+        [UIView commitAnimations];
+
+    // Ensure bar has the proper width for our view, it might have changed
+    barframe.size.width = viewframe.size.width;
+    [refreshbar_ setFrame:barframe];
+
+    // XXX: fix Apple's layout bug
+    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+}
+
+- (void) raiseBar:(BOOL)animated {
+    if (!dropped_)
+        return;
+    dropped_ = false;
+
+    UIView *transition([self transitionView]);
+    [refreshbar_ removeFromSuperview];
+
+    CGRect barframe([refreshbar_ frame]);
+
+    if (animated)
+        [UIView beginAnimations:nil context:NULL];
+
+    CGRect viewframe = [transition frame];
+    viewframe.origin.y -= barframe.size.height;
+    viewframe.size.height += barframe.size.height;
+    [transition setFrame:viewframe];
+
+    if (animated)
+        [UIView commitAnimations];
+
+    // XXX: fix Apple's layout bug
+    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+}
+
+#if 0
+- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
+    // XXX: fix Apple's layout bug
+    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+}
+#endif
+
+- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
+    bool dropped(dropped_);
+
+    if (dropped)
+        [self raiseBar:NO];
+
+    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
+
+    if (dropped)
+        [self dropBar:NO];
+
+    // XXX: fix Apple's layout bug
+    // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+}
+
+- (void) statusBarFrameChanged:(NSNotification *)notification {
+    if (dropped_) {
+        [self raiseBar:NO];
+        [self dropBar:NO];
+    }
+}
+
+- (void) dealloc {
+    [refreshbar_ release];
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+    [super dealloc];
+}
+
+@end
+/* }}} */
+
+/* Cydia Navigation Controller {{{ */
+@interface CYNavigationController : UINavigationController {
+    _transient Database *database_;
+    _transient id<UINavigationControllerDelegate> delegate_;
+}
+
+- (id) initWithDatabase:(Database *)database;
+- (void) reloadData;
+
+@end
+
+
+@implementation CYNavigationController
+
+- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
+    // Inherit autorotation settings for modal parents.
+    if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
+        return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
+    } else {
+        return [super shouldAutorotateToInterfaceOrientation:orientation];
+    }
+}
+
+- (void) dealloc {
+    [super dealloc];
+}
+
+- (void) reloadData {
+    size_t count([[self viewControllers] count]);
+    for (size_t i(0); i != count; ++i) {
+        CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
+        [page reloadData];
+    }
+}
 
 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
     delegate_ = delegate;
 
 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
     delegate_ = delegate;
@@ -6780,13 +7097,18 @@ freeing the view controllers on tab change */
     static NSString *reuseIdentifier = @"SectionCell";
 
     SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
     static NSString *reuseIdentifier = @"SectionCell";
 
     SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
-    if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
+    if (cell == nil)
+        cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
+
     [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
 
     return cell;
 }
 
 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
 
     return cell;
 }
 
 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
+    if (editing_)
+        return;
+
     Section *section = [self sectionAtIndexPath:indexPath];
     NSString *name = [section name];
     NSString *title;
     Section *section = [self sectionAtIndexPath:indexPath];
     NSString *name = [section name];
     NSString *title;
@@ -6846,40 +7168,13 @@ freeing the view controllers on tab change */
     [sections_ removeAllObjects];
     [filtered_ removeAllObjects];
 
     [sections_ removeAllObjects];
     [filtered_ removeAllObjects];
 
-#if 0
-    typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
-    SectionMap sections;
-    sections.resize(64);
-#else
     NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
     NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
-#endif
 
     _trace();
     for (Package *package in packages) {
         NSString *name([package section]);
         NSString *key(name == nil ? @"" : name);
 
 
     _trace();
     for (Package *package in packages) {
         NSString *name([package section]);
         NSString *key(name == nil ? @"" : name);
 
-#if 0
-        Section **section;
-
-        _profile(SectionsView$reloadData$Section)
-            section = &sections[key];
-            if (*section == nil) {
-                _profile(SectionsView$reloadData$Section$Allocate)
-                    *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
-                _end
-            }
-        _end
-
-        [*section addToCount];
-
-        _profile(SectionsView$reloadData$Filter)
-            if (![package valid] || ![package visible])
-                continue;
-        _end
-
-        [*section addToRow];
-#else
         Section *section;
 
         _profile(SectionsView$reloadData$Section)
         Section *section;
 
         _profile(SectionsView$reloadData$Section)
@@ -6900,16 +7195,10 @@ freeing the view controllers on tab change */
         _end
 
         [section addToRow];
         _end
 
         [section addToRow];
-#endif
     }
     _trace();
 
     }
     _trace();
 
-#if 0
-    for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
-        [sections_ addObject:i->second];
-#else
     [sections_ addObjectsFromArray:[sections allValues]];
     [sections_ addObjectsFromArray:[sections allValues]];
-#endif
 
     [sections_ sortUsingSelector:@selector(compareByLocalized:)];
 
 
     [sections_ sortUsingSelector:@selector(compareByLocalized:)];
 
@@ -6923,14 +7212,12 @@ freeing the view controllers on tab change */
         [filtered_ addObject:section];
     }
 
         [filtered_ addObject:section];
     }
 
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+        initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
         style:UIBarButtonItemStylePlain
         target:self
         action:@selector(editButtonClicked)
         style:UIBarButtonItemStylePlain
         target:self
         action:@selector(editButtonClicked)
-    ];
-    [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
-    [rightItem release];
+    ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
 
     [list_ reloadData];
     _trace();
 
     [list_ reloadData];
     _trace();
@@ -6964,7 +7251,8 @@ freeing the view controllers on tab change */
     UITableViewDelegate
 > {
     _transient Database *database_;
     UITableViewDelegate
 > {
     _transient Database *database_;
-    NSMutableArray *packages_;
+    unsigned era_;
+    CFMutableArrayRef packages_;
     NSMutableArray *sections_;
     UITableView *list_;
     unsigned upgrades_;
     NSMutableArray *sections_;
     UITableView *list_;
     unsigned upgrades_;
@@ -6982,7 +7270,8 @@ freeing the view controllers on tab change */
     [list_ setDelegate:nil];
     [list_ setDataSource:nil];
 
     [list_ setDelegate:nil];
     [list_ setDataSource:nil];
 
-    [packages_ release];
+    CFRelease(packages_);
+
     [sections_ release];
     [list_ release];
     [super dealloc];
     [sections_ release];
     [list_ release];
     [super dealloc];
@@ -7015,11 +7304,19 @@ freeing the view controllers on tab change */
     return [[sections_ objectAtIndex:section] count];
 }
 
     return [[sections_ objectAtIndex:section] count];
 }
 
+- (Package *) packageAtIndex:(NSUInteger)index {
+    return (Package *) CFArrayGetValueAtIndex(packages_, index);
+}
+
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
+@synchronized (database_) {
+    if ([database_ era] != era_)
+        return nil;
+
     Section *section([sections_ objectAtIndex:[path section]]);
     NSInteger row([path row]);
     Section *section([sections_ objectAtIndex:[path section]]);
     NSInteger row([path row]);
-    return [packages_ objectAtIndex:([section row] + row)];
-}
+    return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
+} }
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
 
 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
     PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
@@ -7044,7 +7341,7 @@ freeing the view controllers on tab change */
 
 - (void) refreshButtonClicked {
     [delegate_ beginUpdate];
 
 - (void) refreshButtonClicked {
     [delegate_ beginUpdate];
-    [[self navigationItem] setLeftBarButtonItem:nil];
+    [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
 }
 
 - (void) upgradeButtonClicked {
 }
 
 - (void) upgradeButtonClicked {
@@ -7058,7 +7355,8 @@ freeing the view controllers on tab change */
         database_ = database;
         [[self navigationItem] setTitle:UCLocalize("CHANGES")];
 
         database_ = database;
         [[self navigationItem] setTitle:UCLocalize("CHANGES")];
 
-        packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
+        packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
+
         sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
 
         list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
         sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
 
         list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
@@ -7076,63 +7374,57 @@ freeing the view controllers on tab change */
 - (void) _reloadPackages:(NSArray *)packages {
     _trace();
     for (Package *package in packages)
 - (void) _reloadPackages:(NSArray *)packages {
     _trace();
     for (Package *package in packages)
-        if (
-            [package uninstalled] && [package valid] && [package visible] ||
-            [package upgradableAndEssential:YES]
-        )
-            [packages_ addObject:package];
+        if ([package upgradableAndEssential:YES] || [package visible])
+            CFArrayAppendValue(packages_, package);
 
     _trace();
 
     _trace();
-    [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
+    [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
     _trace();
 }
 
 - (void) reloadData {
     _trace();
 }
 
 - (void) reloadData {
+    era_ = [database_ era];
     NSArray *packages = [database_ packages];
 
     NSArray *packages = [database_ packages];
 
-    [packages_ removeAllObjects];
+    CFArrayRemoveAllValues(packages_);
+
     [sections_ removeAllObjects];
 
     [sections_ removeAllObjects];
 
+#if 1
     UIProgressHUD *hud([delegate_ addProgressHUD]);
     UIProgressHUD *hud([delegate_ addProgressHUD]);
-    // XXX: localize
-    [hud setText:@"Loading Changes"];
-    NSLog(@"HUD:%@::%@", delegate_, hud);
+    [hud setText:UCLocalize("LOADING")];
+    //NSLog(@"HUD:%@::%@", delegate_, hud);
     [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
     [delegate_ removeProgressHUD:hud];
     [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
     [delegate_ removeProgressHUD:hud];
+#else
+    [self _reloadPackages:packages];
+#endif
 
     Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
 
     Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
-    Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
+    Section *ignored = nil;
     Section *section = nil;
     Section *section = nil;
-    NSDate *last = nil;
+    time_t last = 0;
 
     upgrades_ = 0;
     bool unseens = false;
 
     CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
 
 
     upgrades_ = 0;
     bool unseens = false;
 
     CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
 
-    for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
-        Package *package = [packages_ objectAtIndex:offset];
+    for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
+        Package *package = [self packageAtIndex:offset];
 
         BOOL uae = [package upgradableAndEssential:YES];
 
         if (!uae) {
             unseens = true;
 
         BOOL uae = [package upgradableAndEssential:YES];
 
         if (!uae) {
             unseens = true;
-            NSDate *seen;
-
-            _profile(ChangesController$reloadData$Remember)
-                seen = [package seen];
-            _end
+            time_t seen([package seen]);
 
 
-            if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
+            if (section == nil || last != seen) {
                 last = seen;
 
                 NSString *name;
                 last = seen;
 
                 NSString *name;
-                if (seen == nil)
-                    name = UCLocalize("UNKNOWN");
-                else {
-                    name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
-                    [name autorelease];
-                }
+                name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
+                [name autorelease];
 
                 _profile(ChangesController$reloadData$Allocate)
                     name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
 
                 _profile(ChangesController$reloadData$Allocate)
                     name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
@@ -7142,9 +7434,12 @@ freeing the view controllers on tab change */
             }
 
             [section addToCount];
             }
 
             [section addToCount];
-        } else if ([package ignored])
+        } else if ([package ignored]) {
+            if (ignored == nil) {
+                ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
+            }
             [ignored addToCount];
             [ignored addToCount];
-        else {
+        else {
             ++upgrades_;
             [upgradable addToCount];
         }
             ++upgrades_;
             [upgradable addToCount];
         }
@@ -7156,7 +7451,7 @@ freeing the view controllers on tab change */
     if (unseens) {
         Section *last = [sections_ lastObject];
         size_t count = [last count];
     if (unseens) {
         Section *last = [sections_ lastObject];
         size_t count = [last count];
-        [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
+        CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
         [sections_ removeLastObject];
     }
 
         [sections_ removeLastObject];
     }
 
@@ -7167,23 +7462,21 @@ freeing the view controllers on tab change */
 
     [list_ reloadData];
 
 
     [list_ reloadData];
 
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(upgradeButtonClicked)
-    ];
-    if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
-    [rightItem release];
+    if (upgrades_ > 0)
+        [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(upgradeButtonClicked)
+        ] autorelease]];
 
 
-    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("REFRESH")
-        style:UIBarButtonItemStylePlain
-        target:self
-        action:@selector(refreshButtonClicked)
-    ];
-    if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
-    [leftItem release];
+    if (![delegate_ updating])
+        [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
+            initWithTitle:UCLocalize("REFRESH")
+            style:UIBarButtonItemStylePlain
+            target:self
+            action:@selector(refreshButtonClicked)
+        ] autorelease]];
 }
 
 @end
 }
 
 @end
@@ -7230,7 +7523,13 @@ freeing the view controllers on tab change */
         search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
         [search_ layoutSubviews];
         [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
         search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
         [search_ layoutSubviews];
         [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
-        UITextField *textField = [search_ searchField];
+
+        UITextField *textField;
+        if ([search_ respondsToSelector:@selector(searchField)])
+            textField = [search_ searchField];
+        else
+            textField = MSHookIvar<UITextField *>(search_, "_searchField");
+
         [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
         [search_ setDelegate:self];
         [textField setEnablesReturnKeyAutomatically:NO];
         [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
         [search_ setDelegate:self];
         [textField setEnablesReturnKeyAutomatically:NO];
@@ -7265,8 +7564,8 @@ freeing the view controllers on tab change */
     NSString *name_;
     Package *package_;
     UITableView *table_;
     NSString *name_;
     Package *package_;
     UITableView *table_;
-    id subscribedSwitch_;
-    id ignoredSwitch_;
+    UISwitch *subscribedSwitch_;
+    UISwitch *ignoredSwitch_;
     UITableViewCell *subscribedCell_;
     UITableViewCell *ignoredCell_;
 }
     UITableViewCell *subscribedCell_;
     UITableViewCell *ignoredCell_;
 }
@@ -7301,38 +7600,23 @@ freeing the view controllers on tab change */
     if (package_ == nil)
         return 0;
 
     if (package_ == nil)
         return 0;
 
-    return 1;
+    return 2;
 }
 
 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
     return UCLocalize("SHOW_ALL_CHANGES_EX");
 }
 
 }
 
 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
     return UCLocalize("SHOW_ALL_CHANGES_EX");
 }
 
-- (void) onSomething:(BOOL)value withKey:(NSString *)key {
+- (void) onSubscribed:(id)control {
+    bool value([control isOn]);
     if (package_ == nil)
         return;
     if (package_ == nil)
         return;
-
-    NSMutableDictionary *metadata([package_ metadata]);
-
-    BOOL before;
-    if (NSNumber *number = [metadata objectForKey:key])
-        before = [number boolValue];
-    else
-        before = NO;
-
-    if (value != before) {
-        [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
-        Changed_ = true;
+    if ([package_ setSubscribed:value])
         [delegate_ updateData];
         [delegate_ updateData];
-    }
-}
-
-- (void) onSubscribed:(id)control {
-    [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
 }
 
 - (void) onIgnored:(id)control {
 }
 
 - (void) onIgnored:(id)control {
-    [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
+    // TODO: set Held state - possibly call out to dpkg, etc.
 }
 
 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 }
 
 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
@@ -7362,11 +7646,11 @@ freeing the view controllers on tab change */
         [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
         [[self view] addSubview:table_];
 
         [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
         [[self view] addSubview:table_];
 
-        subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
+        subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
         [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
         [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
 
         [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
         [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
 
-        ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
+        ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
         [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
         [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
 
         [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
         [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
 
@@ -7401,7 +7685,6 @@ freeing the view controllers on tab change */
 
 @end
 /* }}} */
 
 @end
 /* }}} */
-
 /* Signature Controller {{{ */
 @interface SignatureController : CYBrowserController {
     _transient Database *database_;
 /* Signature Controller {{{ */
 @interface SignatureController : CYBrowserController {
     _transient Database *database_;
@@ -7419,9 +7702,9 @@ freeing the view controllers on tab change */
     [super dealloc];
 }
 
     [super dealloc];
 }
 
-- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
+- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
     // XXX: dude!
     // XXX: dude!
-    [super webView:sender didClearWindowObject:window forFrame:frame];
+    [super webView:view didClearWindowObject:window forFrame:frame];
 }
 
 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
 }
 
 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
@@ -7438,13 +7721,15 @@ freeing the view controllers on tab change */
 
 @end
 /* }}} */
 
 @end
 /* }}} */
+
 /* Role Controller {{{ */
 @interface RoleController : CYViewController <
     UITableViewDataSource,
     UITableViewDelegate
 > {
     _transient Database *database_;
 /* Role Controller {{{ */
 @interface RoleController : CYViewController <
     UITableViewDataSource,
     UITableViewDelegate
 > {
     _transient Database *database_;
-    id roledelegate_;
+    // XXX: ok, "roledelegate_"?...
+    _transient id roledelegate_;
     UITableView *table_;
     UISegmentedControl *segment_;
     UIView *container_;
     UITableView *table_;
     UISegmentedControl *segment_;
     UIView *container_;
@@ -7540,327 +7825,138 @@ freeing the view controllers on tab change */
         nil];
 
         [Metadata_ setObject:Settings_ forKey:@"Settings"];
         nil];
 
         [Metadata_ setObject:Settings_ forKey:@"Settings"];
+        Changed_ = true;
 
 
-        Changed_ = true;
-
-        if (rolling)
-            [roledelegate_ loadData];
-        else
-            [roledelegate_ updateData];
-    }
-}
-
-- (void) segmentChanged:(UISegmentedControl *)control {
-    [self showDoneButton];
-}
-
-- (void) doneButtonClicked {
-    [self save];
-    [[self navigationController] dismissModalViewControllerAnimated:YES];
-}
-
-- (void) showDoneButton {
-    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
-        initWithTitle:UCLocalize("DONE")
-        style:UIBarButtonItemStyleDone
-        target:self
-        action:@selector(doneButtonClicked)
-    ];
-    [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
-    [rightItem release];
-}
-
-- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
-    // XXX: For not having a single cell in the table, this sure is a lot of sections.
-    return 6;
-}
-
-- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
-    return 0; // :(
-}
-
-- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
-    return nil; // This method is required by the protocol.
-}
-
-- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
-    if (section == 1)
-        return UCLocalize("ROLE_EX");
-    if (section == 4)
-        return [NSString stringWithFormat:
-            @"%@: %@\n%@: %@\n%@: %@",
-            UCLocalize("USER"), UCLocalize("USER_EX"),
-            UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
-            UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
-        ];
-    else return nil;
-}
-
-- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
-    if (section == 3) return 44.0f;
-    else return 0;
-}
-
-- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
-    if (section == 3) return container_;
-    else return nil;
-}
-
-@end
-/* }}} */
-
-/* Cydia Container {{{ */
-@interface CYContainer : UIViewController <ProgressDelegate> {
-    _transient Database *database_;
-    RefreshBar *refreshbar_;
-
-    bool dropped_;
-    bool updating_;
-    id updatedelegate_;
-    UITabBarController *root_;
-}
-
-- (void) setTabBarController:(UITabBarController *)controller;
-
-- (void) dropBar:(BOOL)animated;
-- (void) beginUpdate;
-- (void) raiseBar:(BOOL)animated;
-- (BOOL) updating;
-
-@end
-
-@implementation CYContainer
-
-- (BOOL) _reallyWantsFullScreenLayout {
-    return YES;
-}
-
-// NOTE: UIWindow only sends the top controller these messages,
-//       So we have to forward them on.
-
-- (void) viewDidAppear:(BOOL)animated {
-    [super viewDidAppear:animated];
-    [root_ viewDidAppear:animated];
-}
-
-- (void) viewWillAppear:(BOOL)animated {
-    [super viewWillAppear:animated];
-    [root_ viewWillAppear:animated];
-}
-
-- (void) viewDidDisappear:(BOOL)animated {
-    [super viewDidDisappear:animated];
-    [root_ viewDidDisappear:animated];
-}
-
-- (void) viewWillDisappear:(BOOL)animated {
-    [super viewWillDisappear:animated];
-    [root_ viewWillDisappear:animated];
-}
-
-- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
-    return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
-}
-
-- (void) setTabBarController:(UITabBarController *)controller {
-    root_ = controller;
-    [[self view] addSubview:[root_ view]];
-}
-
-- (void) setUpdate:(NSDate *)date {
-    [self beginUpdate];
-}
-
-- (void) beginUpdate {
-    [self dropBar:YES];
-    [refreshbar_ start];
-
-    updating_ = true;
-
-    [NSThread
-        detachNewThreadSelector:@selector(performUpdate)
-        toTarget:self
-        withObject:nil
-    ];
-}
-
-- (void) performUpdate { _pooled
-    Status status;
-    status.setDelegate(self);
-    [database_ updateWithStatus:status];
-
-    [self
-        performSelectorOnMainThread:@selector(completeUpdate)
-        withObject:nil
-        waitUntilDone:NO
-    ];
-}
-
-- (void) completeUpdate {
-    updating_ = false;
-
-    [self raiseBar:YES];
-    [refreshbar_ stop];
-    [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
-}
-
-- (void) cancelUpdate {
-    [refreshbar_ cancel];
-    [self completeUpdate];
-}
-
-- (void) cancelPressed {
-    [self cancelUpdate];
-}
-
-- (BOOL) updating {
-    return updating_;
-}
-
-- (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
-    [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
-}
-
-- (void) startProgress {
-}
-
-- (void) setProgressTitle:(NSString *)title {
-    [self
-        performSelectorOnMainThread:@selector(_setProgressTitle:)
-        withObject:title
-        waitUntilDone:YES
-    ];
-}
-
-- (bool) isCancelling:(size_t)received {
-    return !updating_;
-}
-
-- (void) setProgressPercent:(float)percent {
-    [self
-        performSelectorOnMainThread:@selector(_setProgressPercent:)
-        withObject:[NSNumber numberWithFloat:percent]
-        waitUntilDone:YES
-    ];
-}
-
-- (void) addProgressOutput:(NSString *)output {
-    [self
-        performSelectorOnMainThread:@selector(_addProgressOutput:)
-        withObject:output
-        waitUntilDone:YES
-    ];
-}
-
-- (void) _setProgressTitle:(NSString *)title {
-    [refreshbar_ setPrompt:title];
-}
-
-- (void) _setProgressPercent:(NSNumber *)percent {
-    [refreshbar_ setProgress:[percent floatValue]];
-}
-
-- (void) _addProgressOutput:(NSString *)output {
-}
-
-- (void) setUpdateDelegate:(id)delegate {
-    updatedelegate_ = delegate;
-}
-
-- (CGFloat) statusBarHeight {
-    if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
-        return [[UIApplication sharedApplication] statusBarFrame].size.height;
-    } else {
-        return [[UIApplication sharedApplication] statusBarFrame].size.width;
-    }
-}
-
-- (void) dropBar:(BOOL)animated {
-    if (dropped_) return;
-    dropped_ = true;
-
-    [[self view] addSubview:refreshbar_];
-
-    CGFloat sboffset = [self statusBarHeight];
-
-    CGRect barframe = [refreshbar_ frame];
-    barframe.origin.y = sboffset;
-    [refreshbar_ setFrame:barframe];
-
-    if (animated) [UIView beginAnimations:nil context:NULL];
-    CGRect viewframe = [[root_ view] frame];
-    viewframe.origin.y += barframe.size.height + sboffset;
-    viewframe.size.height -= barframe.size.height + sboffset;
-    [[root_ view] setFrame:viewframe];
-    if (animated) [UIView commitAnimations];
-
-    // Ensure bar has the proper width for our view, it might have changed
-    barframe.size.width = viewframe.size.width;
-    [refreshbar_ setFrame:barframe];
-
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+        if (rolling)
+            [roledelegate_ loadData];
+        else
+            [roledelegate_ updateData];
+    }
 }
 
 }
 
-- (void) raiseBar:(BOOL)animated {
-    if (!dropped_) return;
-    dropped_ = false;
+- (void) segmentChanged:(UISegmentedControl *)control {
+    [self showDoneButton];
+}
 
 
-    [refreshbar_ removeFromSuperview];
+- (void) saveAndClose {
+    [self save];
 
 
-    CGFloat sboffset = [self statusBarHeight];
+    [[self navigationItem] setRightBarButtonItem:nil];
+    [[self navigationController] dismissModalViewControllerAnimated:YES];
+}
 
 
-    if (animated) [UIView beginAnimations:nil context:NULL];
-    CGRect barframe = [refreshbar_ frame];
-    CGRect viewframe = [[root_ view] frame];
-    viewframe.origin.y -= barframe.size.height + sboffset;
-    viewframe.size.height += barframe.size.height + sboffset;
-    [[root_ view] setFrame:viewframe];
-    if (animated) [UIView commitAnimations];
+- (void) doneButtonClicked {
+    UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
+    [spinner startAnimating];
+    UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
+    [[self navigationItem] setRightBarButtonItem:spinItem];
 
 
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+    [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
 }
 
 }
 
-- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+- (void) showDoneButton {
+    [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
+        initWithTitle:UCLocalize("DONE")
+        style:UIBarButtonItemStyleDone
+        target:self
+        action:@selector(doneButtonClicked)
+    ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
 }
 
 }
 
-- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
-    if (dropped_) {
-        [self raiseBar:NO];
-        [self dropBar:NO];
-    }
+- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
+    // XXX: For not having a single cell in the table, this sure is a lot of sections.
+    return 6;
+}
 
 
-    // XXX: fix Apple's layout bug
-    [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
+- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
+    return 0; // :(
 }
 
 }
 
-- (void) statusBarFrameChanged:(NSNotification *)notification {
-    if (dropped_) {
-        [self raiseBar:NO];
-        [self dropBar:NO];
-    }
+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
+    return nil; // This method is required by the protocol.
 }
 
 }
 
-- (void) dealloc {
-    [refreshbar_ release];
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-    [super dealloc];
+- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
+    if (section == 1)
+        return UCLocalize("ROLE_EX");
+    if (section == 4)
+        return [NSString stringWithFormat:
+            @"%@: %@\n%@: %@\n%@: %@",
+            UCLocalize("USER"), UCLocalize("USER_EX"),
+            UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
+            UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
+        ];
+    else return nil;
 }
 
 }
 
-- (id) initWithDatabase:(Database *)database {
-    if ((self = [super init]) != nil) {
-        database_ = database;
+- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
+    return section == 3 ? 44.0f : 0;
+}
 
 
-        [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
-        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
+- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
+    return section == 3 ? container_ : nil;
+}
 
 
-        refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
+@end
+/* }}} */
+/* Stash Controller {{{ */
+@interface CYStashController : CYViewController {
+    // XXX: just delete these things
+    _transient UIActivityIndicatorView *spinner_;
+    _transient UILabel *status_;
+    _transient UILabel *caption_;
+}
+@end
+
+@implementation CYStashController
+- (id) init {
+    if ((self = [super init])) {
+        [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
+
+        spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
+        CGRect spinrect = [spinner_ frame];
+        spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
+        spinrect.origin.y = [[self view] frame].size.height - 80.0f;
+        [spinner_ setFrame:spinrect];
+        [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
+        [[self view] addSubview:spinner_];
+        [spinner_ startAnimating];
+
+        CGRect captrect;
+        captrect.size.width = [[self view] frame].size.width;
+        captrect.size.height = 40.0f;
+        captrect.origin.x = 0;
+        captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
+        caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
+        [caption_ setText:@"Initializing Filesystem"];
+        [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
+        [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
+        [caption_ setTextColor:[UIColor whiteColor]];
+        [caption_ setBackgroundColor:[UIColor clearColor]];
+        [caption_ setShadowColor:[UIColor blackColor]];
+        [caption_ setTextAlignment:UITextAlignmentCenter];
+        [[self view] addSubview:caption_];
+
+        CGRect statusrect;
+        statusrect.size.width = [[self view] frame].size.width;
+        statusrect.size.height = 30.0f;
+        statusrect.origin.x = 0;
+        statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
+        status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
+        [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
+        [status_ setText:@"(Cydia will exit when complete.)"];
+        [status_ setFont:[UIFont systemFontOfSize:16.0f]];
+        [status_ setTextColor:[UIColor whiteColor]];
+        [status_ setBackgroundColor:[UIColor clearColor]];
+        [status_ setShadowColor:[UIColor blackColor]];
+        [status_ setTextAlignment:UITextAlignmentCenter];
+        [[self view] addSubview:status_];
     } return self;
 }
 
     } return self;
 }
 
+- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
+    return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
+}
 @end
 /* }}} */
 
 @end
 /* }}} */
 
@@ -7878,12 +7974,13 @@ typedef enum {
     ConfirmationControllerDelegate,
     ProgressControllerDelegate,
     CydiaDelegate,
     ConfirmationControllerDelegate,
     ProgressControllerDelegate,
     CydiaDelegate,
-    UINavigationControllerDelegate
+    UINavigationControllerDelegate,
+    UITabBarControllerDelegate
 > {
 > {
-    UIWindow *window_;
-    CYContainer *container_;
+    // XXX: evaluate all fields for _transient
 
 
-    id tabbar_;
+    UIWindow *window_;
+    CYTabBarController *tabbar_;
 
     NSMutableArray *essential_;
     NSMutableArray *broken_;
 
     NSMutableArray *essential_;
     NSMutableArray *broken_;
@@ -7891,9 +7988,8 @@ typedef enum {
     Database *database_;
 
     int tag_;
     Database *database_;
 
     int tag_;
-
-    UIKeyboard *keyboard_;
-    UIProgressHUD *hud_;
+    unsigned locked_;
+    NSURL *starturl_;
 
     SectionsController *sections_;
     ChangesController *changes_;
 
     SectionsController *sections_;
     ChangesController *changes_;
@@ -7903,9 +7999,7 @@ typedef enum {
     InstalledController *installed_;
     id queueDelegate_;
 
     InstalledController *installed_;
     id queueDelegate_;
 
-#if RecyclePackageViews
-    NSMutableArray *details_;
-#endif
+    CYStashController *stash_;
 
     bool loaded_;
 }
 
     bool loaded_;
 }
@@ -7914,6 +8008,9 @@ typedef enum {
 - (void) setPage:(CYViewController *)page;
 - (void) loadData;
 
 - (void) setPage:(CYViewController *)page;
 - (void) loadData;
 
+// XXX: I hate prototypes
+- (id) queueBadgeController;
+
 @end
 
 static _finline void _setHomePage(Cydia *self) {
 @end
 
 static _finline void _setHomePage(Cydia *self) {
@@ -7923,11 +8020,11 @@ static _finline void _setHomePage(Cydia *self) {
 @implementation Cydia
 
 - (void) beginUpdate {
 @implementation Cydia
 
 - (void) beginUpdate {
-    [container_ beginUpdate];
+    [tabbar_ beginUpdate];
 }
 
 - (BOOL) updating {
 }
 
 - (BOOL) updating {
-    return [container_ updating];
+    return [tabbar_ updating];
 }
 
 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
 }
 
 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
@@ -7965,21 +8062,24 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) _saveConfig {
 }
 
 - (void) _saveConfig {
+    _trace();
+    MetaFile_.Sync();
+    _trace();
+
     if (Changed_) {
     if (Changed_) {
-        _trace();
         NSString *error(nil);
         NSString *error(nil);
+
         if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
             _trace();
             NSError *error(nil);
             if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
                 NSLog(@"failure to save metadata data: %@", error);
             _trace();
         if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
             _trace();
             NSError *error(nil);
             if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
                 NSLog(@"failure to save metadata data: %@", error);
             _trace();
+
+            Changed_ = false;
         } else {
             NSLog(@"failure to serialize metadata: %@", error);
         } else {
             NSLog(@"failure to serialize metadata: %@", error);
-            return;
         }
         }
-
-        Changed_ = false;
     }
 }
 
     }
 }
 
@@ -7995,12 +8095,16 @@ static _finline void _setHomePage(Cydia *self) {
         [search_ reloadData];
 
     [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
         [search_ reloadData];
 
     [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
+
+    [queueDelegate_ queueStatusDidChange];
+    [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
 }
 
 - (int)indexOfTabWithTag:(int)tag {
     int i = 0;
     for (UINavigationController *controller in [tabbar_ viewControllers]) {
 }
 
 - (int)indexOfTabWithTag:(int)tag {
     int i = 0;
     for (UINavigationController *controller in [tabbar_ viewControllers]) {
-        if ([[controller tabBarItem] tag] == tag) return i;
+        if ([[controller tabBarItem] tag] == tag)
+            return i;
         i += 1;
     }
 
         i += 1;
     }
 
@@ -8010,6 +8114,30 @@ static _finline void _setHomePage(Cydia *self) {
 - (void) _refreshIfPossible {
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
 - (void) _refreshIfPossible {
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
+    bool recently = false;
+    NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
+    if (update != nil) {
+        NSTimeInterval interval([update timeIntervalSinceNow]);
+        if (interval <= 0 && interval > -(15*60))
+            recently = true;
+    }
+
+    // Don't automatic refresh if:
+    //  - We already refreshed recently.
+    //  - We already auto-refreshed this launch.
+    //  - Auto-refresh is disabled.
+    if (recently || loaded_ || ManualRefresh) {
+        [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
+
+        // If we are cancelling due to ManualRefresh or a recent refresh
+        // we need to make sure it knows it's already loaded.
+        loaded_ = true;
+        return;
+    } else {
+        // We are going to load, so remember that.
+        loaded_ = true;
+    }
+
     SCNetworkReachabilityFlags flags; {
         SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
         SCNetworkReachabilityGetFlags(reachability, &flags);
     SCNetworkReachabilityFlags flags; {
         SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
         SCNetworkReachabilityGetFlags(reachability, &flags);
@@ -8028,21 +8156,9 @@ static _finline void _setHomePage(Cydia *self) {
         )
     );
 
         )
     );
 
-    if (loaded_ || ManualRefresh || !reachable) loaded:
-        [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
-    else {
-        loaded_ = true;
-
-        NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
-
-        if (update != nil) {
-            NSTimeInterval interval([update timeIntervalSinceNow]);
-            if (interval <= 0 && interval > -(15*60))
-                goto loaded;
-        }
-
-        [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
-    }
+    // If we can reach the server, auto-refresh!
+    if (reachable)
+        [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
 
     [pool release];
 }
 
     [pool release];
 }
@@ -8052,13 +8168,13 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) _reloadData {
 }
 
 - (void) _reloadData {
-    UIProgressHUD *hud([self addProgressHUD]);
-    [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
+    UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
+    [hud setText:UCLocalize("RELOADING_DATA")];
 
     [database_ yieldToSelector:@selector(reloadData) withObject:nil];
 
     [database_ yieldToSelector:@selector(reloadData) withObject:nil];
-    _trace();
 
 
-    [self removeProgressHUD:hud];
+    if (hud != nil)
+        [self removeProgressHUD:hud];
 
     size_t changes(0);
 
 
     size_t changes(0);
 
@@ -8076,18 +8192,19 @@ static _finline void _setHomePage(Cydia *self) {
         }
     }
 
         }
     }
 
+    UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
     if (changes != 0) {
         NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
     if (changes != 0) {
         NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
-        [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
-        [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
+        [changesItem setBadgeValue:badge];
+        [changesItem setAnimatedBadge:([essential_ count] > 0)];
 
         if ([self respondsToSelector:@selector(setApplicationBadge:)])
             [self setApplicationBadge:badge];
         else
             [self setApplicationBadgeString:badge];
     } else {
 
         if ([self respondsToSelector:@selector(setApplicationBadge:)])
             [self setApplicationBadge:badge];
         else
             [self setApplicationBadgeString:badge];
     } else {
-        [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
-        [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
+        [changesItem setBadgeValue:nil];
+        [changesItem setAnimatedBadge:NO];
 
         if ([self respondsToSelector:@selector(removeApplicationBadge)])
             [self removeApplicationBadge];
 
         if ([self respondsToSelector:@selector(removeApplicationBadge)])
             [self removeApplicationBadge];
@@ -8101,7 +8218,6 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) updateData {
 }
 
 - (void) updateData {
-    [database_ setVisible];
     [self _updateData];
 }
 
     [self _updateData];
 }
 
@@ -8129,8 +8245,9 @@ static _finline void _setHomePage(Cydia *self) {
 
     ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
     CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
 
     ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
     CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
-    if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
-    [container_ presentModalViewController:navigation animated:YES];
+    if (IsWildcat_)
+        [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
+    [tabbar_ presentModalViewController:navigation animated:YES];
 
     [progress
         detachNewThreadSelector:@selector(update_)
 
     [progress
         detachNewThreadSelector:@selector(update_)
@@ -8164,11 +8281,12 @@ static _finline void _setHomePage(Cydia *self) {
 
     ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
     [page setDelegate:self];
 
     ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
     [page setDelegate:self];
-    CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
+    CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
     [confirm_ setDelegate:self];
 
     [confirm_ setDelegate:self];
 
-    if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
-    [container_ presentModalViewController:confirm_ animated:YES];
+    if (IsWildcat_)
+        [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
+    [tabbar_ presentModalViewController:confirm_ animated:YES];
 
     return true;
 }
 
     return true;
 }
@@ -8227,14 +8345,17 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
 }
 
 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
+    Queuing_ = false;
+
     ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
 
     if (navigation != nil) {
         [navigation pushViewController:progress animated:YES];
     } else {
         navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
     ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
 
     if (navigation != nil) {
         [navigation pushViewController:progress animated:YES];
     } else {
         navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
-        if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
-        [container_ presentModalViewController:navigation animated:YES];
+        if (IsWildcat_)
+            [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
+        [tabbar_ presentModalViewController:navigation animated:YES];
     }
 
     [progress
     }
 
     [progress
@@ -8243,9 +8364,12 @@ static _finline void _setHomePage(Cydia *self) {
         withObject:nil
         title:UCLocalize("RUNNING")
     ];
         withObject:nil
         title:UCLocalize("RUNNING")
     ];
+
+    ++locked_;
 }
 
 - (void) progressControllerIsComplete:(ProgressController *)progress {
 }
 
 - (void) progressControllerIsComplete:(ProgressController *)progress {
+    --locked_;
     [self complete];
 }
 
     [self complete];
 }
 
@@ -8254,9 +8378,9 @@ static _finline void _setHomePage(Cydia *self) {
 
     CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
     [navController setViewControllers:[NSArray arrayWithObject:page]];
 
     CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
     [navController setViewControllers:[NSArray arrayWithObject:page]];
-    for (CYNavigationController *page in [tabbar_ viewControllers]) {
-        if (page != navController) [page setViewControllers:nil];
-    }
+    for (CYNavigationController *page in [tabbar_ viewControllers])
+        if (page != navController)
+            [page setViewControllers:nil];
 }
 
 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
 }
 
 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
@@ -8283,7 +8407,8 @@ static _finline void _setHomePage(Cydia *self) {
             _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
             withClass:[ManageController class]
         ] retain];
             _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
             withClass:[ManageController class]
         ] retain];
-        if (!IsWildcat_) queueDelegate_ = manage_;
+        if (!IsWildcat_)
+            queueDelegate_ = manage_;
     }
     return manage_;
 }
     }
     return manage_;
 }
@@ -8303,12 +8428,13 @@ static _finline void _setHomePage(Cydia *self) {
 - (InstalledController *) installedController {
     if (installed_ == nil) {
         installed_ = [[InstalledController alloc] initWithDatabase:database_];
 - (InstalledController *) installedController {
     if (installed_ == nil) {
         installed_ = [[InstalledController alloc] initWithDatabase:database_];
-        if (IsWildcat_) queueDelegate_ = installed_;
+        if (IsWildcat_)
+            queueDelegate_ = installed_;
     }
     return installed_;
 }
 
     }
     return installed_;
 }
 
-- (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
+- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
     int tag = [[viewController tabBarItem] tag];
     if (tag == tag_) {
         [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
     int tag = [[viewController tabBarItem] tag];
     if (tag == tag_) {
         [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
@@ -8334,19 +8460,16 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (void) showSettings {
 }
 
 - (void) showSettings {
-    RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
-    CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
-    if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
-    [container_ presentModalViewController:nav animated:YES];
+    RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
+    CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
+    if (IsWildcat_)
+        [nav setModalPresentationStyle:UIModalPresentationFormSheet];
+    [tabbar_ presentModalViewController:nav animated:YES];
 }
 
 - (void) setPackageController:(PackageController *)view {
     WebThreadLock();
     [view setPackage:nil];
 }
 
 - (void) setPackageController:(PackageController *)view {
     WebThreadLock();
     [view setPackage:nil];
-#if RecyclePackageViews
-    if ([details_ count] < 3)
-        [details_ addObject:view];
-#endif
     WebThreadUnlock();
 }
 
     WebThreadUnlock();
 }
 
@@ -8355,31 +8478,14 @@ static _finline void _setHomePage(Cydia *self) {
 }
 
 - (PackageController *) packageController {
 }
 
 - (PackageController *) packageController {
-#if RecyclePackageViews
-    PackageController *view;
-    size_t count([details_ count]);
-
-    if (count == 0) {
-        view = [self _packageController];
-      renew:
-        [details_ addObject:[self _packageController]];
-    } else {
-        view = [[[details_ lastObject] retain] autorelease];
-        [details_ removeLastObject];
-        if (count == 1)
-            goto renew;
-    }
-
-    return view;
-#else
     return [self _packageController];
     return [self _packageController];
-#endif
 }
 
 // Returns the navigation controller for the queuing badge.
 - (id) queueBadgeController {
     int index = [self indexOfTabWithTag:kManageTag];
 }
 
 // Returns the navigation controller for the queuing badge.
 - (id) queueBadgeController {
     int index = [self indexOfTabWithTag:kManageTag];
-    if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
+    if (index == -1)
+        index = [self indexOfTabWithTag:kInstalledTag];
 
     return [[tabbar_ viewControllers] objectAtIndex:index];
 }
 
     return [[tabbar_ viewControllers] objectAtIndex:index];
 }
@@ -8387,29 +8493,13 @@ static _finline void _setHomePage(Cydia *self) {
 - (void) cancelAndClear:(bool)clear {
     @synchronized (self) {
         if (clear) {
 - (void) cancelAndClear:(bool)clear {
     @synchronized (self) {
         if (clear) {
-            // Clear all marks.
-            pkgCacheFile &cache([database_ cache]);
-            for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
-                // Unmark method taken from Synaptic Package Manager.
-                // Thanks for being sane, unlike Aptitude.
-                if (!cache[iterator].Keep()) {
-                    cache->MarkKeep(iterator, false);
-                    cache->SetReInstall(iterator, false);
-                }
-            }
-
-            // Stop queuing.
+            [database_ clear];
             Queuing_ = false;
             Queuing_ = false;
-            [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
         } else {
         } else {
-            // Start queuing.
             Queuing_ = true;
             Queuing_ = true;
-            [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
         }
 
         }
 
-        // Show the changes in the current view.
-        [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
-        [queueDelegate_ queueStatusDidChange];
+        [self _updateData];
     }
 }
 
     }
 }
 
@@ -8466,20 +8556,32 @@ static _finline void _setHomePage(Cydia *self) {
     [super applicationWillSuspend];
 }
 
     [super applicationWillSuspend];
 }
 
+- (BOOL) isSafeToSuspend {
+    // Use external process status API internally.
+    // This is probably a really bad idea.
+    // XXX: what is the point of this? does this solve anything at all?
+    uint64_t status = 0;
+    int notify_token;
+    if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
+        notify_get_state(notify_token, &status);
+        notify_cancel(notify_token);
+    }
+
+    return locked_ == 0 && status == 0;
+}
+
 - (void) applicationSuspend:(__GSEvent *)event {
 - (void) applicationSuspend:(__GSEvent *)event {
-    // FIXME: This needs to be fixed, but we no longer have a progress_.
-    //        What's the best solution?
-    if (hud_ == nil)// && ![progress_ isRunning])
+    if ([self isSafeToSuspend])
         [super applicationSuspend:event];
 }
 
 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
         [super applicationSuspend:event];
 }
 
 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
-    if (hud_ == nil)
+    if ([self isSafeToSuspend])
         [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
 }
 
 - (void) _setSuspended:(BOOL)value {
         [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
 }
 
 - (void) _setSuspended:(BOOL)value {
-    if (hud_ == nil)
+    if ([self isSafeToSuspend])
         [super _setSuspended:value];
 }
 
         [super _setSuspended:value];
 }
 
@@ -8489,7 +8591,12 @@ static _finline void _setHomePage(Cydia *self) {
 
     [window_ setUserInteractionEnabled:NO];
     [hud show:YES];
 
     [window_ setUserInteractionEnabled:NO];
     [hud show:YES];
-    [[container_ view] addSubview:hud];
+
+    UIViewController *target = tabbar_;
+    while ([target modalViewController] != nil) target = [target modalViewController];
+    [[target view] addSubview:hud];
+
+    ++locked_;
     return hud;
 }
 
     return hud;
 }
 
@@ -8497,6 +8604,7 @@ static _finline void _setHomePage(Cydia *self) {
     [hud show:NO];
     [hud removeFromSuperview];
     [window_ setUserInteractionEnabled:YES];
     [hud show:NO];
     [hud removeFromSuperview];
     [window_ setUserInteractionEnabled:YES];
+    --locked_;
 }
 
 - (CYViewController *) pageForPackage:(NSString *)name {
 }
 
 - (CYViewController *) pageForPackage:(NSString *)name {
@@ -8560,25 +8668,106 @@ static _finline void _setHomePage(Cydia *self) {
     return nil;
 }
 
     return nil;
 }
 
-- (void) applicationOpenURL:(NSURL *)url {
-    [super applicationOpenURL:url];
-    int tag;
-    if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
+- (BOOL) openCydiaURL:(NSURL *)url {
+    CYViewController *page = nil;
+    int tag = 0;
+
+    NSLog(@"open url: %@", url);
+
+    if ((page = [self pageForURL:url hasTag:&tag])) {
         [self setPage:page];
         tag_ = tag;
         [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
     }
         [self setPage:page];
         tag_ = tag;
         [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
     }
+
+    return !!page;
+}
+
+- (void) applicationOpenURL:(NSURL *)url {
+    [super applicationOpenURL:url];
+    NSLog(@"first: %@", url);
+    if (!loaded_) starturl_ = [url retain];
+    else [self openCydiaURL:url];
 }
 
 - (void) applicationWillResignActive:(UIApplication *)application {
     // Stop refreshing if you get a phone call or lock the device.
 }
 
 - (void) applicationWillResignActive:(UIApplication *)application {
     // Stop refreshing if you get a phone call or lock the device.
-    if ([container_ updating]) [container_ cancelUpdate];
+    if ([tabbar_ updating])
+        [tabbar_ cancelUpdate];
 
     if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
         [super applicationWillResignActive:application];
 }
 
 
     if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
         [super applicationWillResignActive:application];
 }
 
+- (void) addStashController {
+    ++locked_;
+    stash_ = [[CYStashController alloc] init];
+    [window_ addSubview:[stash_ view]];
+}
+
+- (void) removeStashController {
+    [[stash_ view] removeFromSuperview];
+    [stash_ release];
+    --locked_;
+}
+
+- (void) stash {
+    [self setIdleTimerDisabled:YES];
+
+    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
+    [self setStatusBarShowsProgress:YES];
+    UpdateExternalStatus(1);
+
+    [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
+
+    UpdateExternalStatus(0);
+    [self setStatusBarShowsProgress:NO];
+
+    [self removeStashController];
+
+    if (ExecFork() == 0) {
+        execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
+        perror("launchctl stop");
+    }
+}
+
+- (void) setupTabBarController {
+    tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
+    [tabbar_ setDelegate:self];
+
+    NSMutableArray *items([NSMutableArray arrayWithObjects:
+        [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
+        [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
+        [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
+        [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
+    nil]);
+
+    if (IsWildcat_) {
+        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
+        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
+    } else {
+        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
+    }
+
+    NSMutableArray *controllers([NSMutableArray array]);
+
+    for (UITabBarItem *item in items) {
+        CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
+        [controller setTabBarItem:item];
+        [controllers addObject:controller];
+    }
+
+    [tabbar_ setViewControllers:controllers];
+}
+
 - (void) applicationDidFinishLaunching:(id)unused {
 - (void) applicationDidFinishLaunching:(id)unused {
+_trace();
+    [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
+        initWithMemoryCapacity:524288
+        diskCapacity:10485760
+        diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
+    ] autorelease]];
+
     [CYBrowserController _initialize];
 
     [NSURLProtocol registerClass:[CydiaURLProtocol class]];
     [CYBrowserController _initialize];
 
     [NSURLProtocol registerClass:[CydiaURLProtocol class]];
@@ -8601,8 +8790,6 @@ static _finline void _setHomePage(Cydia *self) {
     [window_ makeKey:self];
     [window_ setHidden:NO];
 
     [window_ makeKey:self];
     [window_ setHidden:NO];
 
-    database_ = [Database sharedInstance];
-
     if (
         readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
         readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
     if (
         readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
         readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
@@ -8615,82 +8802,92 @@ static _finline void _setHomePage(Cydia *self) {
         //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
         false
     ) {
         //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
         false
     ) {
-        [self setIdleTimerDisabled:YES];
-
-        hud_ = [self addProgressHUD];
-        [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
-        [self setStatusBarShowsProgress:YES];
-
-        [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
-
-        [self setStatusBarShowsProgress:NO];
-        [self removeProgressHUD:hud_];
-        hud_ = nil;
-
-        if (ExecFork() == 0) {
-            execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
-            perror("launchctl stop");
-        }
-
+        [self addStashController];
+        // XXX: this would be much cleaner as a yieldToSelector:
+        // that way the removeStashController could happen right here inline
+        // we also could no longer require the useless stash_ field anymore
+        [self performSelector:@selector(stash) withObject:nil afterDelay:0];
         return;
     }
 
         return;
     }
 
-    _trace();
-
-    NSMutableArray *items([NSMutableArray arrayWithObjects:
-        [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
-        [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
-        [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
-        [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
-    nil]);
-
-    if (IsWildcat_) {
-        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
-        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
-    } else {
-        [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
-    }
-
-    NSMutableArray *controllers([NSMutableArray array]);
-
-    for (UITabBarItem *item in items) {
-        CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
-        [controller setTabBarItem:item];
-        [controllers addObject:controller];
-    }
+    database_ = [Database sharedInstance];
 
 
-    tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
-    [tabbar_ setViewControllers:controllers];
-    [tabbar_ setDelegate:self];
-    [tabbar_ setSelectedIndex:0];
+    [self setupTabBarController];
+    [tabbar_ setUpdateDelegate:self];
+    [window_ addSubview:[tabbar_ view]];
 
 
-    container_ = [[CYContainer alloc] initWithDatabase:database_];
-    [container_ setUpdateDelegate:self];
-    [container_ setTabBarController:tabbar_];
-    [window_ addSubview:[container_ view]];
+    // Show pinstripes while loading data.
+    [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
 
     [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
 
     [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
+_trace();
 }
 
 - (void) loadData {
 }
 
 - (void) loadData {
+_trace();
     if (Role_ == nil) {
         [self showSettings];
         return;
     }
 
     if (Role_ == nil) {
         [self showSettings];
         return;
     }
 
-    [UIKeyboard initImplementationNow];
+    [window_ setUserInteractionEnabled:NO];
+
+    UIView *container = [[[UIView alloc] init] autorelease];
+    [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
+
+    UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
+    [spinner startAnimating];
+    [container addSubview:spinner];
+
+    UILabel *label = [[[UILabel alloc] init] autorelease];
+    [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
+    [label setBackgroundColor:[UIColor clearColor]];
+    [label setTextColor:[UIColor blackColor]];
+    [label setShadowColor:[UIColor whiteColor]];
+    [label setShadowOffset:CGSizeMake(0, 1)];
+    [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
+    [container addSubview:label];
+
+    CGSize viewsize = [[tabbar_ view] frame].size;
+    CGSize spinnersize = [spinner bounds].size;
+    CGSize textsize = [[label text] sizeWithFont:[label font]];
+    float bothwidth = spinnersize.width + textsize.width + 5.0f;
+
+    CGRect containrect = {
+        CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
+        CGSizeMake(bothwidth, spinnersize.height)
+    };
+    CGRect textrect = {
+        CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
+        textsize
+    };
+    CGRect spinrect = {
+        CGPointZero,
+        spinnersize
+    };
+
+    [container setFrame:containrect];
+    [spinner setFrame:spinrect];
+    [label setFrame:textrect];
+    [[tabbar_ view] addSubview:container];
 
     [self reloadData];
 
     [self reloadData];
+    PrintTimes();
 
 
-#if RecyclePackageViews
-    details_ = [[NSMutableArray alloc] initWithCapacity:4];
-    [details_ addObject:[self _packageController]];
-    [details_ addObject:[self _packageController]];
-#endif
+    // Show the initial page
+    if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
+        [tabbar_ setSelectedIndex:0];
+        _setHomePage(self);
+    }
 
 
-    PrintTimes();
+    [starturl_ release];
+    starturl_ = nil;
+
+    [window_ setUserInteractionEnabled:YES];
 
 
-    _setHomePage(self);
+    // XXX: does this actually slow anything down?
+    [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
+    [container removeFromSuperview];
 }
 
 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
 }
 
 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
@@ -8886,6 +9083,22 @@ int main(int argc, char *argv[]) { _pooled
 
     UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
 
 
     UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
 
+    CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
+    $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
+    CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
+
+    CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
+    $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
+    CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
+
+    if (mcc != NULL && mnc != NULL)
+        PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
+
+    if (mnc != NULL)
+        CFRelease(mnc);
+    if (mcc != NULL)
+        CFRelease(mcc);
+
     if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
         Build_ = [system objectForKey:@"ProductBuildVersion"];
     if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
     if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
         Build_ = [system objectForKey:@"ProductBuildVersion"];
     if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
@@ -8898,7 +9111,6 @@ int main(int argc, char *argv[]) { _pooled
     Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
     _trace();
     SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
     Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
     _trace();
     SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
-    _trace();
 
     if (Metadata_ == NULL)
         Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
 
     if (Metadata_ == NULL)
         Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
@@ -8915,11 +9127,6 @@ int main(int argc, char *argv[]) { _pooled
     if (Settings_ != nil)
         Role_ = [Settings_ objectForKey:@"Role"];
 
     if (Settings_ != nil)
         Role_ = [Settings_ objectForKey:@"Role"];
 
-    if (Packages_ == nil) {
-        Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
-        [Metadata_ setObject:Packages_ forKey:@"Packages"];
-    }
-
     if (Sections_ == nil) {
         Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
         [Metadata_ setObject:Sections_ forKey:@"Sections"];
     if (Sections_ == nil) {
         Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
         [Metadata_ setObject:Sections_ forKey:@"Sections"];
@@ -8931,9 +9138,17 @@ int main(int argc, char *argv[]) { _pooled
     }
     /* }}} */
 
     }
     /* }}} */
 
-#if RecycleWebViews
-    Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
-#endif
+    _trace();
+    MetaFile_.Open("/var/lib/cydia/metadata.cb0");
+    _trace();
+
+    if (Packages_ != nil) {
+        CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
+        _trace();
+        [Metadata_ removeObjectForKey:@"Packages"];
+        Packages_ = nil;
+        Changed_ = true;
+    }
 
     Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
 
 
     Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
 
@@ -8976,7 +9191,10 @@ int main(int argc, char *argv[]) { _pooled
 
     if (lang != NULL)
         _config->Set("APT::Acquire::Translation", lang);
 
     if (lang != NULL)
         _config->Set("APT::Acquire::Translation", lang);
-    _config->Set("Acquire::http::Timeout", 15);
+
+    // XXX: this timeout might be important :(
+    //_config->Set("Acquire::http::Timeout", 15);
+
     _config->Set("Acquire::http::MaxParallel", 3);
     /* }}} */
     /* Color Choices {{{ */
     _config->Set("Acquire::http::MaxParallel", 3);
     /* }}} */
     /* Color Choices {{{ */
@@ -9005,6 +9223,7 @@ int main(int argc, char *argv[]) { _pooled
     /* }}} */
 
     Colon_ = UCLocalize("COLON_DELIMITED");
     /* }}} */
 
     Colon_ = UCLocalize("COLON_DELIMITED");
+    Elision_ = UCLocalize("ELISION");
     Error_ = UCLocalize("ERROR");
     Warning_ = UCLocalize("WARNING");
 
     Error_ = UCLocalize("ERROR");
     Warning_ = UCLocalize("WARNING");