Index: includes/CategoryPage.php
===================================================================
--- includes/CategoryPage.php	(revision 25594)
+++ includes/CategoryPage.php	(working copy)
@@ -84,8 +84,8 @@
 		$this->doCategoryQuery();
 		$this->finaliseCategoryState();
 
-		$r = $this->getCategoryTop() .
-			$this->getSubcategorySection() .
+		$r = $this->getSubcategorySection() .
+			$this->getCategoryTop() .
 			$this->getPagesSection() .
 			$this->getImageSection() .
 			$this->getCategoryBottom();
@@ -178,8 +178,6 @@
 
 	function finaliseCategoryState() {
 		if( $this->flip ) {
-			$this->children            = array_reverse( $this->children );
-			$this->children_start_char = array_reverse( $this->children_start_char );
 			$this->articles            = array_reverse( $this->articles );
 			$this->articles_start_char = array_reverse( $this->articles_start_char );
 		}
@@ -197,14 +195,32 @@
 			$pageCondition = '1 = 1';
 			$this->flip = false;
 		}
+
+		$db_key = $this->title->getDBKey();
+
 		$res = $dbr->select(
 			array( 'page', 'categorylinks' ),
+			array( 'page_title', 'page_len', 'page_is_redirect', 'cl_sortkey' ),
+			array( 'cl_from          =  page_id',
+			       'cl_to'           => $db_key,
+			       'page_namespace'  => NS_CATEGORY ),
+			__METHOD__,
+			array( 'ORDER BY' => 'cl_sortkey',
+			       'USE INDEX' => 'cl_sortkey' ) );
+
+		while( $x = $dbr->fetchObject ( $res ) ) {
+			$title = Title::makeTitle( NS_CATEGORY, $x->page_title );
+			$this->addSubcategory( $title, $x->cl_sortkey, $x->page_len );
+		}
+		$dbr->freeResult( $res );
+
+		$res = $dbr->select(
+			array( 'page', 'categorylinks' ),
 			array( 'page_title', 'page_namespace', 'page_len', 'page_is_redirect', 'cl_sortkey' ),
 			array( $pageCondition,
 			       'cl_from          =  page_id',
-			       'cl_to'           => $this->title->getDBKey()),
-			       #'page_is_redirect' => 0),
-			#+ $pageCondition,
+			       'cl_to'           => $db_key,
+			       'page_namespace   <> ' . NS_CATEGORY),
 			__METHOD__,
 			array( 'ORDER BY' => $this->flip ? 'cl_sortkey DESC' : 'cl_sortkey',
 			       'USE INDEX' => 'cl_sortkey', 
@@ -222,9 +238,7 @@
 
 			$title = Title::makeTitle( $x->page_namespace, $x->page_title );
 
-			if( $title->getNamespace() == NS_CATEGORY ) {
-				$this->addSubcategory( $title, $x->cl_sortkey, $x->page_len );
-			} elseif( $this->showGallery && $title->getNamespace() == NS_IMAGE ) {
+			if( $this->showGallery && $title->getNamespace() == NS_IMAGE ) {
 				$this->addImage( $title, $x->cl_sortkey, $x->page_len, $x->page_is_redirect );
 			} else {
 				$this->addPage( $title, $x->cl_sortkey, $x->page_len, $x->page_is_redirect );
