--- imp/lib/IMAP/Tree.php.orig	2009-12-28 19:54:47.000000000 +0100
+++ imp/lib/IMAP/Tree.php	2009-12-29 02:36:21.000000000 +0100
@@ -261,6 +261,15 @@
      */
     function _store()
     {
+        /* clean the expanded folders list */
+        $this->_cleanExpandedList();
+
+        /* We only need to store if the expanded folders has been changed */
+        if ($GLOBALS['prefs']->isDirty('expanded_folders') && !is_null($this->_expanded)) {
+            $GLOBALS['prefs']->setValue('expanded_folders', serialize($this->_expanded));
+        }
+
         /* We only need to restore the object if the tree has changed. */
         if (empty($this->_changed)) {
             return;
@@ -1185,11 +1194,51 @@
     {
         $this->_initExpandedList();
         if ($action == 'add') {
+            if (!$GLOBALS['prefs']->isDirty('expanded_folders') && $this->_expanded[$id] == false) {
+                $GLOBALS['prefs']->setDirty('expanded_folders', true);
+	    }
             $this->_expanded[$id] = true;
         } else {
+            if (!$GLOBALS['prefs']->isDirty('expanded_folders') && isset($this->_expanded_[$id])) {
+                $GLOBALS['prefs']->setDirty('expanded_folders', true);
+            }
             unset($this->_expanded[$id]);
         }
-        $GLOBALS['prefs']->setValue('expanded_folders', serialize($this->_expanded));
+    }
+
+    /**
+     * Clean the expanded list, to delete non-existing folder in the list
+     *
+     * @access private
+     *
+     */
+    function _cleanExpandedList()
+    {
+        /* we don't need to purge, as we don't get any data from the IMAP server */
+        if (is_null($this->_fulllist)) {
+	    return;
+	}
+
+        /* build fulllist */
+	$fulllist = array();
+	$this->_forceopen = true;
+        $mailbox = $this->reset();
+	do {
+	    if ($this->_isNonIMAPElt($mailbox) || $this->isVFolder($mailbox)) {
+	        $fulllist[ ($mailbox['c'] > 0 ? $mailbox['p'] . $this->_delimiter : '') . $mailbox['v'] ] = true;
+	    } else {
+	        $fulllist[ $mailbox['v'] ] = true;
+	    }
+	} while(($mailbox = $this->next(IMPTREE_NEXT_SHOWCLOSED)));
+	$this->_forceopen = false;
+
+        /* compute the list of element to delete from _expanded */
+	$to_remove = array_diff_key($this->_expanded, $fulllist);
+
+        /* remove useless elements */
+        foreach (array_keys($to_remove) as $key) {
+            $this->_modifyExpandedList($key, 'remove');
+	}
     }
 
     /**