Made the gnutls password encryption work on Win32.
[claws.git] / src / mh.c
index a4ee8c817c58b4054f91114647c9b91c703ed867..913a41c9a6c0e3c88e0d86e4ef9240b845c8dda1 100644 (file)
--- a/src/mh.c
+++ b/src/mh.c
@@ -1,10 +1,10 @@
 /*
  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
+ * Copyright (C) 1999-2013 Hiroyuki Yamamoto and the Claws Mail team
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
+ * the Free Software Foundation; either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * 
  */
 
 #ifdef HAVE_CONFIG_H
 #  include "config.h"
+#include "claws-features.h"
 #endif
 
 #include "defs.h"
 #include <unistd.h>
 #include <string.h>
 #include <errno.h>
-
-#undef MEASURE_TIME
-
-#ifdef MEASURE_TIME
-#  include <sys/time.h>
-#endif
+#include <time.h>
 
 #include "folder.h"
+#include "folder_item_prefs.h"
 #include "mh.h"
 #include "procmsg.h"
 #include "procheader.h"
 #include "utils.h"
 #include "codeconv.h"
+#include "statusbar.h"
+#include "gtkutils.h"
+#include "timing.h"
+#include "msgcache.h"
 
 /* Define possible missing constants for Windows. */
 #ifdef G_OS_WIN32
@@ -77,17 +78,21 @@ static gint     mh_add_msg          (Folder         *folder,
 static gint     mh_add_msgs            (Folder         *folder,
                                         FolderItem     *dest,
                                         GSList         *file_list,
-                                        GRelation      *relation);
+                                        GHashTable     *relation);
 static gint     mh_copy_msg            (Folder         *folder,
                                         FolderItem     *dest,
                                         MsgInfo        *msginfo);
 static gint    mh_copy_msgs            (Folder         *folder, 
                                         FolderItem     *dest, 
                                         MsgInfoList    *msglist, 
-                                        GRelation      *relation);
+                                        GHashTable     *relation);
 static gint     mh_remove_msg          (Folder         *folder,
                                         FolderItem     *item,
                                         gint            num);
+static gint    mh_remove_msgs          (Folder         *folder, 
+                                        FolderItem     *item, 
+                                        MsgInfoList    *msglist, 
+                                        GHashTable     *relation);
 static gint     mh_remove_all_msg      (Folder         *folder,
                                         FolderItem     *item);
 static gboolean mh_is_msg_changed      (Folder         *folder,
@@ -126,11 +131,15 @@ static gchar   *mh_item_get_path          (Folder *folder,
 
 static gboolean mh_scan_required       (Folder         *folder,
                                         FolderItem     *item);
+static void mh_set_mtime               (Folder         *folder,
+                                        FolderItem *item);
 static int mh_item_close               (Folder         *folder,
                                         FolderItem     *item);
+#if 0
 static gint mh_get_flags               (Folder *folder, FolderItem *item,
-                                        MsgInfoList *msginfo_list, GRelation *msgflags);
-static void mh_write_sequences         (FolderItem     *item);
+                                        MsgInfoList *msginfo_list, GHashTable *msgflags);
+#endif
+static void mh_write_sequences         (FolderItem     *item, gboolean remove_unseen);
 
 static FolderClass mh_class;
 
@@ -140,6 +149,7 @@ FolderClass *mh_get_class(void)
                mh_class.type = F_MH;
                mh_class.idstr = "mh";
                mh_class.uistr = "MH";
+               mh_class.supports_server_search = FALSE;
                
                /* Folder functions */
                mh_class.new_folder = mh_folder_new;
@@ -156,8 +166,9 @@ FolderClass *mh_get_class(void)
                mh_class.remove_folder = mh_remove_folder;
                mh_class.get_num_list = mh_get_num_list;
                mh_class.scan_required = mh_scan_required;
+               mh_class.set_mtime = mh_set_mtime;
                mh_class.close = mh_item_close;
-               mh_class.get_flags = mh_get_flags;
+               mh_class.get_flags = NULL; /*mh_get_flags */;
 
                /* Message functions */
                mh_class.get_msginfo = mh_get_msginfo;
@@ -166,7 +177,9 @@ FolderClass *mh_get_class(void)
                mh_class.add_msgs = mh_add_msgs;
                mh_class.copy_msg = mh_copy_msg;
                mh_class.copy_msgs = mh_copy_msgs;
+               mh_class.search_msgs = folder_item_search_msgs_local;
                mh_class.remove_msg = mh_remove_msg;
+               mh_class.remove_msgs = mh_remove_msgs;
                mh_class.remove_all_msg = mh_remove_all_msg;
                mh_class.is_msg_changed = mh_is_msg_changed;
        }
@@ -199,12 +212,12 @@ static void mh_folder_init(Folder *folder, const gchar *name, const gchar *path)
 gboolean mh_scan_required(Folder *folder, FolderItem *item)
 {
        gchar *path;
-       struct stat s;
+       GStatBuf s;
 
        path = folder_item_get_path(item);
-       g_return_val_if_fail(path != NULL, FALSE);
+       cm_return_val_if_fail(path != NULL, FALSE);
 
-       if (stat(path, &s) < 0) {
+       if (g_stat(path, &s) < 0) {
                FILE_OP_ERROR(path, "stat");
                g_free(path);
                return FALSE;
@@ -213,7 +226,7 @@ gboolean mh_scan_required(Folder *folder, FolderItem *item)
        if ((s.st_mtime > item->mtime) &&
                (s.st_mtime - 3600 != item->mtime)) {
                debug_print("MH scan required, folder updated: %s (%ld > %ld)\n",
-                           path,
+                           path?path:"(null)",
                            (long int) s.st_mtime,
                            (long int) item->mtime);
                g_free(path);
@@ -221,48 +234,53 @@ gboolean mh_scan_required(Folder *folder, FolderItem *item)
        }
 
        debug_print("MH scan not required: %s (%ld <= %ld)\n",
-                   path,
+                   path?path:"(null)",
                    (long int) s.st_mtime,
                    (long int) item->mtime);
        g_free(path);
        return FALSE;
 }
 
-void mh_get_last_num(Folder *folder, FolderItem *item)
+static void mh_get_last_num(Folder *folder, FolderItem *item)
 {
-       gchar *path;
-       DIR *dp;
-       struct dirent *d;
+       gchar *path, *fullpath;
+       GDir *dp;
+       const gchar *d;
+       GError *error = NULL;
        gint max = 0;
        gint num;
 
-       g_return_if_fail(item != NULL);
+       cm_return_if_fail(item != NULL);
 
-       debug_print("mh_get_last_num(): Scanning %s ...\n", item->path);
+       debug_print("mh_get_last_num(): Scanning %s ...\n", item->path?item->path:"(null)");
 
        path = folder_item_get_path(item);
-       g_return_if_fail(path != NULL);
-       if (change_dir(path) < 0) {
-               g_free(path);
-               return;
-       }
-       g_free(path);
+       cm_return_if_fail(path != NULL);
 
-       if ((dp = opendir(".")) == NULL) {
-               FILE_OP_ERROR(item->path, "opendir");
+       if ((dp = g_dir_open(path, 0, &error)) == NULL) {
+               g_message("Couldn't open current directory: %s (%d).\n",
+                               error->message, error->code);
+               g_error_free(error);
+               g_free(path);
                return;
        }
 
-       while ((d = readdir(dp)) != NULL) {
-               if ((num = to_number(d->d_name)) > 0 &&
-                   dirent_is_regular_file(d)) {
+       while ((d = g_dir_read_name(dp)) != NULL) {
+               fullpath = g_strconcat(path, G_DIR_SEPARATOR_S, d, NULL);
+               if ((num = to_number(d)) > 0 &&
+                   g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) {
                        if (max < num)
                                max = num;
                }
+               g_free(fullpath);
+
+               if (num % 2000 == 0)
+                       GTK_EVENTS_FLUSH();
        }
-       closedir(dp);
+       g_dir_close(dp);
+       g_free(path);
 
-       debug_print("Last number in dir %s = %d\n", item->path, max);
+       debug_print("Last number in dir %s = %d\n", item->path?item->path:"(null)", max);
        item->last_num = max;
 }
 
@@ -270,38 +288,38 @@ gint mh_get_num_list(Folder *folder, FolderItem *item, GSList **list, gboolean *
 {
 
        gchar *path;
-       DIR *dp;
-       struct dirent *d;
+       GDir *dp;
+       const gchar *d;
+       GError *error = NULL;
        gint num, nummsgs = 0;
 
-       g_return_val_if_fail(item != NULL, -1);
+       cm_return_val_if_fail(item != NULL, -1);
 
-       debug_print("mh_get_num_list(): Scanning %s ...\n", item->path);
+       debug_print("mh_get_num_list(): Scanning %s ...\n", item->path?item->path:"(null)");
 
        *old_uids_valid = TRUE;
 
        path = folder_item_get_path(item);
-       g_return_val_if_fail(path != NULL, -1);
-       if (change_dir(path) < 0) {
+       cm_return_val_if_fail(path != NULL, -1);
+
+       if ((dp = g_dir_open(path, 0, &error)) == NULL) {
+               g_message("Couldn't open current directory: %s (%d).\n",
+                               error->message, error->code);
+               g_error_free(error);
                g_free(path);
                return -1;
        }
        g_free(path);
 
-       if ((dp = opendir(".")) == NULL) {
-               FILE_OP_ERROR(item->path, "opendir");
-               return -1;
-       }
-
-       while ((d = readdir(dp)) != NULL) {
-               if ((num = to_number(d->d_name)) > 0) {
+       while ((d = g_dir_read_name(dp)) != NULL) {
+               if ((num = to_number(d)) > 0) {
                        *list = g_slist_prepend(*list, GINT_TO_POINTER(num));
                        nummsgs++;
                }
        }
-       closedir(dp);
+       g_dir_close(dp);
 
-       item->mtime = time(NULL);
+       mh_set_mtime(folder, item);
        return nummsgs;
 }
 
@@ -310,8 +328,8 @@ static gchar *mh_fetch_msg(Folder *folder, FolderItem *item, gint num)
        gchar *path;
        gchar *file;
 
-       g_return_val_if_fail(item != NULL, NULL);
-       g_return_val_if_fail(num > 0, NULL);
+       cm_return_val_if_fail(item != NULL, NULL);
+       cm_return_val_if_fail(num > 0, NULL);
 
        path = folder_item_get_path(item);
        file = g_strconcat(path, G_DIR_SEPARATOR_S, itos(num), NULL);
@@ -330,7 +348,7 @@ static MsgInfo *mh_get_msginfo(Folder *folder, FolderItem *item, gint num)
        MsgInfo *msginfo;
        gchar *file;
 
-       g_return_val_if_fail(item != NULL, NULL);
+       cm_return_val_if_fail(item != NULL, NULL);
        if (num <= 0)
                return NULL;
 
@@ -352,7 +370,12 @@ static gchar *mh_get_new_msg_filename(FolderItem *dest)
        gchar *destpath;
 
        destpath = folder_item_get_path(dest);
-       g_return_val_if_fail(destpath != NULL, NULL);
+       cm_return_val_if_fail(destpath != NULL, NULL);
+
+       if (dest->last_num < 0) {
+               mh_get_last_num(dest->folder, dest);
+               if (dest->last_num < 0) return NULL;
+       }
 
        if (!is_dir_exist(destpath))
                make_dir_hier(destpath);
@@ -378,7 +401,7 @@ static gint mh_add_msg(Folder *folder, FolderItem *dest, const gchar *file, MsgF
        GSList file_list;
        MsgFileInfo fileinfo;
 
-       g_return_val_if_fail(file != NULL, -1);
+       cm_return_val_if_fail(file != NULL, -1);
 
        fileinfo.msginfo = NULL;
        fileinfo.file = (gchar *)file;
@@ -391,14 +414,14 @@ static gint mh_add_msg(Folder *folder, FolderItem *dest, const gchar *file, MsgF
 } 
  
 static gint mh_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list, 
-                 GRelation *relation)
+                 GHashTable *relation)
 { 
        gchar *destfile;
        GSList *cur;
        MsgFileInfo *fileinfo;
 
-       g_return_val_if_fail(dest != NULL, -1);
-       g_return_val_if_fail(file_list != NULL, -1);
+       cm_return_val_if_fail(dest != NULL, -1);
+       cm_return_val_if_fail(file_list != NULL, -1);
 
        if (dest->last_num < 0) {
                mh_get_last_num(folder, dest);
@@ -415,7 +438,7 @@ static gint mh_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
                if (link(fileinfo->file, destfile) < 0) {
 #endif
                        if (copy_file(fileinfo->file, destfile, TRUE) < 0) {
-                               g_warning(_("can't copy message %s to %s\n"),
+                               g_warning("can't copy message %s to %s",
                                          fileinfo->file, destfile);
                                g_free(destfile);
                                return -1;
@@ -425,11 +448,11 @@ static gint mh_add_msgs(Folder *folder, FolderItem *dest, GSList *file_list,
 #endif
 
                if (relation != NULL)
-                       g_relation_insert(relation, fileinfo, GINT_TO_POINTER(dest->last_num + 1));
+                       g_hash_table_insert(relation, fileinfo, GINT_TO_POINTER(dest->last_num + 1));
                g_free(destfile);
                dest->last_num++;
        }
-       mh_write_sequences(dest);
+       mh_write_sequences(dest, TRUE);
        return dest->last_num;
 }
 
@@ -437,7 +460,7 @@ static gint mh_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
 {
        GSList msglist;
 
-       g_return_val_if_fail(msginfo != NULL, -1);
+       cm_return_val_if_fail(msginfo != NULL, -1);
 
        msglist.data = msginfo;
        msglist.next = NULL;
@@ -446,57 +469,91 @@ static gint mh_copy_msg(Folder *folder, FolderItem *dest, MsgInfo *msginfo)
 }
 
 static gint mh_copy_msgs(Folder *folder, FolderItem *dest, MsgInfoList *msglist, 
-                        GRelation *relation)
+                        GHashTable *relation)
 {
        gboolean dest_need_scan = FALSE;
+       gboolean src_need_scan = FALSE;
+       FolderItem *src = NULL;
        gchar *srcfile;
        gchar *destfile;
-       gint filemode = 0;
        FolderItemPrefs *prefs;
        MsgInfo *msginfo = NULL;
-       gboolean remove_special_headers = FALSE;
        MsgInfoList *cur = NULL;
-       g_return_val_if_fail(dest != NULL, -1);
-       g_return_val_if_fail(msglist != NULL, -1);
+       gint curnum = 0, total = 0;
+       gchar *srcpath = NULL;
+       gboolean full_fetch = FALSE;
+       time_t last_dest_mtime = (time_t)0;
+       time_t last_src_mtime = (time_t)0;
+
+       cm_return_val_if_fail(dest != NULL, -1);
+       cm_return_val_if_fail(msglist != NULL, -1);
        
        msginfo = (MsgInfo *)msglist->data;
 
-       g_return_val_if_fail(msginfo != NULL, -1);
+       cm_return_val_if_fail(msginfo != NULL, -1);
 
        if (msginfo->folder == dest) {
-               g_warning("the src folder is identical to the dest.\n");
+               g_warning("the src folder is identical to the dest.");
                return -1;
        }
 
+       if (msginfo->folder->folder != dest->folder)
+               full_fetch = TRUE;
+       
+       if (FOLDER_TYPE(msginfo->folder->folder) == F_MH) {
+               src = msginfo->folder;
+       }
+
        if (dest->last_num < 0) {
                mh_get_last_num(folder, dest);
                if (dest->last_num < 0) return -1;
        }
 
-       if ((MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags))
-       && !folder_has_parent_of_type(dest, F_QUEUE)
-       && !folder_has_parent_of_type(dest, F_DRAFT)) {
-               /* as every msginfo comes from the same folder, it is supposed they
-                * will either match the preceding condition either all or none.
-                */
-               remove_special_headers = TRUE;
-       } else if (!(MSG_IS_QUEUED(msginfo->flags) || MSG_IS_DRAFT(msginfo->flags))
-       && (folder_has_parent_of_type(dest, F_QUEUE)
-        || folder_has_parent_of_type(dest, F_DRAFT))) {
-               return -1;
-       } 
-
        prefs = dest->prefs;
 
+       srcpath = folder_item_get_path(msginfo->folder);
+
+       dest_need_scan = mh_scan_required(dest->folder, dest);
+       last_dest_mtime = dest->mtime;
+
+       if (src) {
+               src_need_scan = mh_scan_required(src->folder, src);
+               last_src_mtime = src->mtime;
+       }
+
+       total = g_slist_length(msglist);
+       if (total > 100) {
+               if (MSG_IS_MOVE(msginfo->flags))
+                       statusbar_print_all(_("Moving messages..."));
+               else
+                       statusbar_print_all(_("Copying messages..."));
+       }
        for (cur = msglist; cur; cur = cur->next) {
                msginfo = (MsgInfo *)cur->data;
-               if (!msginfo)
-                       continue;
-               srcfile = procmsg_get_message_file(msginfo);
+               if (!msginfo) {
+                       goto err_reset_status;
+               }
+               if (!full_fetch) {
+                       srcfile = g_strconcat(srcpath, 
+                               G_DIR_SEPARATOR_S, 
+                               itos(msginfo->msgnum), NULL);
+               } else {
+                       srcfile = procmsg_get_message_file(msginfo);
+               }
+               if (!srcfile) {
+                       goto err_reset_status;
+               }
                destfile = mh_get_new_msg_filename(dest);
                if (!destfile) {
                        g_free(srcfile);
-                       continue;
+                       goto err_reset_status;
+               }
+
+               if (total > 100) {
+                       statusbar_progress_all(curnum, total, 100);
+                       if (curnum % 100 == 0)
+                               GTK_EVENTS_FLUSH();
+                       curnum++;
                }
 
                debug_print("Copying message %s%c%d to %s ...\n",
@@ -504,81 +561,168 @@ static gint mh_copy_msgs(Folder *folder, FolderItem *dest, MsgInfoList *msglist,
                            msginfo->msgnum, dest->path);
 
 
-               if (remove_special_headers) {
-                       if (procmsg_remove_special_headers(srcfile, destfile) !=0) {
-                               g_free(srcfile);
-                               g_free(destfile);
-                               continue;
+               if (MSG_IS_MOVE(msginfo->flags)) {
+                       msginfo->flags.tmp_flags &= ~MSG_MOVE_DONE;
+                       if (move_file(srcfile, destfile, TRUE) < 0) {
+                               FILE_OP_ERROR(srcfile, "move");
+                               if (copy_file(srcfile, destfile, TRUE) < 0) {
+                                       FILE_OP_ERROR(srcfile, "copy");
+                                       g_free(srcfile);
+                                       g_free(destfile);
+                                       goto err_reset_status;
+                               }
+                       } else {
+                               /* say unlinking's not necessary */
+                               msginfo->flags.tmp_flags |= MSG_MOVE_DONE;
                        }
                } else if (copy_file(srcfile, destfile, TRUE) < 0) {
                        FILE_OP_ERROR(srcfile, "copy");
                        g_free(srcfile);
                        g_free(destfile);
-                       continue;
-               }
+                       goto err_reset_status;
+               } 
                if (prefs && prefs->enable_folder_chmod && prefs->folder_chmod) {
                        if (chmod(destfile, prefs->folder_chmod) < 0)
                                FILE_OP_ERROR(destfile, "chmod");
-
-                       /* for mark file */
-                       filemode = prefs->folder_chmod;
-                       if (filemode & S_IRGRP) filemode |= S_IWGRP;
-                       if (filemode & S_IROTH) filemode |= S_IWOTH;
                }
-               if (relation)
-                       g_relation_insert(relation, msginfo, GINT_TO_POINTER(dest->last_num+1));
+               if (relation) {
+                       if (g_hash_table_lookup(relation, msginfo) != NULL)
+                               g_warning("already in: %p", msginfo);
+                       
+                       g_hash_table_insert(relation, msginfo, GINT_TO_POINTER(dest->last_num+1));
+               }
                g_free(srcfile);
                g_free(destfile);
                dest->last_num++;
        }
 
-       dest_need_scan = mh_scan_required(dest->folder, dest);
-       if (!dest_need_scan)
-               dest->mtime = time(NULL);
-       else
-               mh_write_sequences(dest);
+       g_free(srcpath);
+       mh_write_sequences(dest, TRUE);
 
+       if (dest->mtime == last_dest_mtime && !dest_need_scan) {
+               mh_set_mtime(folder, dest);
+       }
+
+       if (src && src->mtime == last_src_mtime && !src_need_scan) {
+               mh_set_mtime(folder, src);
+       }
+
+       if (total > 100) {
+               statusbar_progress_all(0,0,0);
+               statusbar_pop_all();
+       }
        return dest->last_num;
+err_reset_status:
+       g_free(srcpath);
+       mh_write_sequences(dest, TRUE);
+       if (total > 100) {
+               statusbar_progress_all(0,0,0);
+               statusbar_pop_all();
+       }
+       return -1;
+
 }
 
 static gint mh_remove_msg(Folder *folder, FolderItem *item, gint num)
 {
        gboolean need_scan = FALSE;
+       time_t last_mtime = (time_t)0;
        gchar *file;
 
-       g_return_val_if_fail(item != NULL, -1);
+       cm_return_val_if_fail(item != NULL, -1);
 
        file = mh_fetch_msg(folder, item, num);
-       g_return_val_if_fail(file != NULL, -1);
+       cm_return_val_if_fail(file != NULL, -1);
 
        need_scan = mh_scan_required(folder, item);
+       last_mtime = item->mtime;
 
-       if (g_unlink(file) < 0) {
+       if (claws_unlink(file) < 0) {
                FILE_OP_ERROR(file, "unlink");
                g_free(file);
                return -1;
        }
 
-       if (!need_scan)
-               item->mtime = time(NULL);
-
+       if (item->mtime == last_mtime && !need_scan) {
+               mh_set_mtime(folder, item);
+       }
        g_free(file);
        return 0;
 }
 
+static gint mh_remove_msgs(Folder *folder, FolderItem *item, 
+                   MsgInfoList *msglist, GHashTable *relation)
+{
+       gboolean need_scan = FALSE;
+       gchar *path, *file;
+       time_t last_mtime = (time_t)0;
+       MsgInfoList *cur;
+       gint total = 0, curnum = 0;
+
+       cm_return_val_if_fail(item != NULL, -1);
+
+       path = folder_item_get_path(item);
+       
+       need_scan = mh_scan_required(folder, item);
+       last_mtime = item->mtime;
+
+       total = g_slist_length(msglist);
+       if (total > 100) {
+               statusbar_print_all(_("Deleting messages..."));
+       }
+
+       for (cur = msglist; cur; cur = cur->next) {
+               MsgInfo *msginfo = (MsgInfo *)cur->data;
+               if (msginfo == NULL)
+                       continue;
+               if (MSG_IS_MOVE(msginfo->flags) && MSG_IS_MOVE_DONE(msginfo->flags)) {
+                       msginfo->flags.tmp_flags &= ~MSG_MOVE_DONE;
+                       continue;
+               }
+               if (total > 100) {
+                       statusbar_progress_all(curnum, total, 100);
+                       if (curnum % 100 == 0)
+                               GTK_EVENTS_FLUSH();
+                       curnum++;
+               }
+
+               file = g_strconcat(path, G_DIR_SEPARATOR_S, itos(msginfo->msgnum), NULL);
+               if (file == NULL)
+                       continue;
+               
+               if (claws_unlink(file) < 0) {
+                       g_free(file);
+                       continue;
+               }
+               
+               g_free(file);
+       }
+
+       if (total > 100) {
+               statusbar_progress_all(0,0,0);
+               statusbar_pop_all();
+       }
+       if (item->mtime == last_mtime && !need_scan) {
+               mh_set_mtime(folder, item);
+       }
+
+       g_free(path);
+       return 0;
+}
+
 static gint mh_remove_all_msg(Folder *folder, FolderItem *item)
 {
        gchar *path;
        gint val;
 
-       g_return_val_if_fail(item != NULL, -1);
+       cm_return_val_if_fail(item != NULL, -1);
 
        path = folder_item_get_path(item);
-       g_return_val_if_fail(path != NULL, -1);
+       cm_return_val_if_fail(path != NULL, -1);
        val = remove_all_numbered_files(path);
        g_free(path);
 
-       mh_write_sequences(item);
+       mh_write_sequences(item, TRUE);
 
        return val;
 }
@@ -586,24 +730,29 @@ static gint mh_remove_all_msg(Folder *folder, FolderItem *item)
 static gboolean mh_is_msg_changed(Folder *folder, FolderItem *item,
                                  MsgInfo *msginfo)
 {
-       struct stat s;
+       GStatBuf s;
+       gchar *path;
 
-       if (g_stat(itos(msginfo->msgnum), &s) < 0 ||
+       path = g_strdup_printf("%s%c%d", folder_item_get_path(item),
+                       G_DIR_SEPARATOR, msginfo->msgnum);
+       if (g_stat((path), &s) < 0 ||
            msginfo->size  != s.st_size || (
                (msginfo->mtime - s.st_mtime != 0) &&
                (msginfo->mtime - s.st_mtime != 3600) &&
-               (msginfo->mtime - s.st_mtime != -3600)))
+               (msginfo->mtime - s.st_mtime != -3600))) {
+               g_free(path);
                return TRUE;
+       }
 
+       g_free(path);
        return FALSE;
 }
 
 static gint mh_scan_tree(Folder *folder)
 {
        FolderItem *item;
-       gchar *rootpath;
 
-       g_return_val_if_fail(folder != NULL, -1);
+       cm_return_val_if_fail(folder != NULL, -1);
 
        if (!folder->node) {
                item = folder_item_new(folder, folder->name, NULL);
@@ -612,13 +761,6 @@ static gint mh_scan_tree(Folder *folder)
        } else
                item = FOLDER_ITEM(folder->node->data);
 
-       rootpath = folder_item_get_path(item);
-       if (change_dir(rootpath) < 0) {
-               g_free(rootpath);
-               return -1;
-       }
-       g_free(rootpath);
-
        mh_create_tree(folder);
        mh_remove_missing_folder_items(folder);
        mh_scan_tree_recursive(item);
@@ -630,31 +772,85 @@ static gint mh_scan_tree(Folder *folder)
 { \
        if (!is_dir_exist(dir)) { \
                if (is_file_exist(dir)) { \
-                       g_warning("File `%s' already exists.\n" \
+                       g_warning("File '%s' already exists. " \
                                    "Can't create folder.", dir); \
                        return -1; \
                } \
-               if (make_dir(dir) < 0) \
+               if (make_dir_hier(dir) < 0) \
                        return -1; \
+               debug_print("Created dir '%s'\n", dir); \
        } \
 }
 
 static gint mh_create_tree(Folder *folder)
 {
-       gchar *rootpath;
+       gchar *rootpath, *f, *path;
 
-       g_return_val_if_fail(folder != NULL, -1);
+       cm_return_val_if_fail(folder != NULL, -1);
 
-       CHDIR_RETURN_VAL_IF_FAIL(get_mail_base_dir(), -1);
        rootpath = LOCAL_FOLDER(folder)->rootpath;
+#ifdef G_OS_UNIX
+       if (*rootpath == '/') {
+#elif defined G_OS_WIN32
+       if (g_ascii_isalpha(*rootpath) && !strncmp(rootpath + 1, "\:", 2)) {
+#endif
+               /* Folder path is absolute. */
+               rootpath = g_strdup(rootpath);
+       } else {
+               /* Folder path is relative, using mail base dir. */
+               rootpath = g_strconcat(get_mail_base_dir(), G_DIR_SEPARATOR_S,
+                               rootpath, NULL);
+       }
+
        MAKE_DIR_IF_NOT_EXIST(rootpath);
-       CHDIR_RETURN_VAL_IF_FAIL(rootpath, -1);
-       MAKE_DIR_IF_NOT_EXIST(INBOX_DIR);
-       MAKE_DIR_IF_NOT_EXIST(OUTBOX_DIR);
-       MAKE_DIR_IF_NOT_EXIST(QUEUE_DIR);
-       MAKE_DIR_IF_NOT_EXIST(DRAFT_DIR);
-       MAKE_DIR_IF_NOT_EXIST(TRASH_DIR);
 
+       /* Create special directories as needed */
+       if (folder->inbox != NULL &&
+                       folder->inbox->path != NULL)
+               f = folder->inbox->path;
+       else
+               f = INBOX_DIR;
+       path = g_strconcat(rootpath, G_DIR_SEPARATOR_S, f, NULL);
+       MAKE_DIR_IF_NOT_EXIST(path);
+       g_free(path);
+
+       if (folder->outbox != NULL &&
+                       folder->outbox->path != NULL)
+               f = folder->outbox->path;
+       else
+               f = OUTBOX_DIR;
+       path = g_strconcat(rootpath, G_DIR_SEPARATOR_S, f, NULL);
+       MAKE_DIR_IF_NOT_EXIST(path);
+       g_free(path);
+
+       if (folder->draft != NULL &&
+                       folder->draft->path != NULL)
+               f = folder->draft->path;
+       else
+               f = DRAFT_DIR;
+       path = g_strconcat(rootpath, G_DIR_SEPARATOR_S, f, NULL);
+       MAKE_DIR_IF_NOT_EXIST(path);
+       g_free(path);
+
+       if (folder->queue != NULL &&
+                       folder->queue->path != NULL)
+               f = folder->queue->path;
+       else
+               f = QUEUE_DIR;
+       path = g_strconcat(rootpath, G_DIR_SEPARATOR_S, f, NULL);
+       MAKE_DIR_IF_NOT_EXIST(path);
+       g_free(path);
+
+       if (folder->trash != NULL &&
+                       folder->trash->path != NULL)
+               f = folder->trash->path;
+       else
+               f = TRASH_DIR;
+       path = g_strconcat(rootpath, G_DIR_SEPARATOR_S, f, NULL);
+       MAKE_DIR_IF_NOT_EXIST(path);
+       g_free(path);
+
+       g_free(rootpath);
        return 0;
 }
 
@@ -664,11 +860,11 @@ static gchar *mh_item_get_path(Folder *folder, FolderItem *item)
 {
        gchar *folder_path, *path;
        gchar *real_path;
-       g_return_val_if_fail(folder != NULL, NULL);
-       g_return_val_if_fail(item != NULL, NULL);
+       cm_return_val_if_fail(folder != NULL, NULL);
+       cm_return_val_if_fail(item != NULL, NULL);
 
        folder_path = g_strdup(LOCAL_FOLDER(folder)->rootpath);
-       g_return_val_if_fail(folder_path != NULL, NULL);
+       cm_return_val_if_fail(folder_path != NULL, NULL);
 
         /* FIXME: [W32] The code below does not correctly merge
            relative filenames; there should be a function to handle
@@ -693,14 +889,38 @@ static gchar *mh_item_get_path(Folder *folder, FolderItem *item)
        if (!is_dir_exist(real_path) && is_dir_exist(path)) {
                /* mmh, older version did put utf8 filenames instead of
                 * the correct encoding */
-               rename(path, real_path);
-               folder_item_scan(item);
+               if (g_rename(path, real_path) == 0)
+                       folder_item_scan(item);
        }
 
        g_free(path);
        return real_path;
 }
 
+static gboolean mh_renumber_msg(MsgInfo *info)
+{
+       gchar *src, *dest;
+       gboolean result = FALSE;
+       guint num;
+       cm_return_val_if_fail(info != NULL, FALSE);
+
+       src = folder_item_fetch_msg(info->folder, info->msgnum);
+       dest = mh_get_new_msg_filename(info->folder);
+       num = info->folder->last_num + 1;
+
+       if (move_file(src, dest, FALSE) == 0) {
+               msgcache_remove_msg(info->folder->cache, info->msgnum);
+               info->msgnum = num;
+               msgcache_add_msg(info->folder->cache, info);
+               result = TRUE;
+       }
+
+       g_free(src);
+       g_free(dest);
+
+       return result;
+}
+
 static FolderItem *mh_create_folder(Folder *folder, FolderItem *parent,
                                    const gchar *name)
 {
@@ -710,20 +930,32 @@ static FolderItem *mh_create_folder(Folder *folder, FolderItem *parent,
        gchar *mh_sequences_filename;
        FILE *mh_sequences_file;
 
-       g_return_val_if_fail(folder != NULL, NULL);
-       g_return_val_if_fail(parent != NULL, NULL);
-       g_return_val_if_fail(name != NULL, NULL);
+       cm_return_val_if_fail(folder != NULL, NULL);
+       cm_return_val_if_fail(parent != NULL, NULL);
+       cm_return_val_if_fail(name != NULL, NULL);
 
        path = folder_item_get_path(parent);
        if (!is_dir_exist(path)) 
                if (make_dir_hier(path) != 0)
                        return NULL;
-               
+
        real_name = mh_filename_from_utf8(name);
        fullpath = g_strconcat(path, G_DIR_SEPARATOR_S, real_name, NULL);
        g_free(real_name);
        g_free(path);
 
+       if (to_number(name) > 0) {
+               MsgInfo *info = folder_item_get_msginfo(parent, to_number(name));
+               if (info != NULL) {
+                       gboolean ok = mh_renumber_msg(info);
+                       procmsg_msginfo_free(&info);
+                       if (!ok) {
+                               g_free(fullpath);
+                               return NULL;
+                       }
+               }
+       }
+
        if (make_dir(fullpath) < 0) {
                g_free(fullpath);
                return NULL;
@@ -762,10 +994,10 @@ static gint mh_rename_folder(Folder *folder, FolderItem *item,
        gchar *newpath, *utf8newpath;
        gchar *paths[2];
 
-       g_return_val_if_fail(folder != NULL, -1);
-       g_return_val_if_fail(item != NULL, -1);
-       g_return_val_if_fail(item->path != NULL, -1);
-       g_return_val_if_fail(name != NULL, -1);
+       cm_return_val_if_fail(folder != NULL, -1);
+       cm_return_val_if_fail(item != NULL, -1);
+       cm_return_val_if_fail(item->path != NULL, -1);
+       cm_return_val_if_fail(name != NULL, -1);
 
        oldpath = folder_item_get_path(item);
        if (!is_dir_exist(oldpath))
@@ -810,16 +1042,17 @@ static gint mh_rename_folder(Folder *folder, FolderItem *item,
 static gint mh_remove_folder(Folder *folder, FolderItem *item)
 {
        gchar *path;
+       gint ret;
 
-       g_return_val_if_fail(folder != NULL, -1);
-       g_return_val_if_fail(item != NULL, -1);
-       g_return_val_if_fail(item->path != NULL, -1);
+       cm_return_val_if_fail(folder != NULL, -1);
+       cm_return_val_if_fail(item != NULL, -1);
+       cm_return_val_if_fail(item->path != NULL, -1);
 
        path = folder_item_get_path(item);
-       if (remove_dir_recursive(path) < 0) {
-               g_warning("can't remove directory `%s'\n", path);
+       if ((ret = remove_dir_recursive(path)) < 0) {
+               g_warning("can't remove directory '%s'", path);
                g_free(path);
-               return -1;
+               return ret;
        }
 
        g_free(path);
@@ -832,8 +1065,8 @@ static MsgInfo *mh_parse_msg(const gchar *file, FolderItem *item)
        MsgInfo *msginfo;
        MsgFlags flags;
 
-       g_return_val_if_fail(item != NULL, NULL);
-       g_return_val_if_fail(file != NULL, NULL);
+       cm_return_val_if_fail(item != NULL, NULL);
+       cm_return_val_if_fail(file != NULL, NULL);
 
        flags.perm_flags = MSG_NEW|MSG_UNREAD;
        flags.tmp_flags = 0;
@@ -858,7 +1091,7 @@ static gboolean mh_remove_missing_folder_items_func(GNode *node, gpointer data)
        FolderItem *item;
        gchar *path;
 
-       g_return_val_if_fail(node->data != NULL, FALSE);
+       cm_return_val_if_fail(node->data != NULL, FALSE);
 
        if (G_NODE_IS_ROOT(node))
                return FALSE;
@@ -867,7 +1100,7 @@ static gboolean mh_remove_missing_folder_items_func(GNode *node, gpointer data)
 
        path = folder_item_get_path(item);
        if (!is_dir_exist(path)) {
-               debug_print("folder '%s' not found. removing...\n", path);
+               debug_print("folder '%s' not found. removing...\n", path?path:"(null)");
                folder_item_remove(item);
        }
        g_free(path);
@@ -877,7 +1110,7 @@ static gboolean mh_remove_missing_folder_items_func(GNode *node, gpointer data)
 
 static void mh_remove_missing_folder_items(Folder *folder)
 {
-       g_return_if_fail(folder != NULL);
+       cm_return_if_fail(folder != NULL);
 
        debug_print("searching missing folders...\n");
 
@@ -888,38 +1121,27 @@ static void mh_remove_missing_folder_items(Folder *folder)
 static void mh_scan_tree_recursive(FolderItem *item)
 {
        Folder *folder;
-#ifdef G_OS_WIN32
        GDir *dir;
-#else
-       DIR *dp;
-       struct dirent *d;
-#endif
        const gchar *dir_name;
-       struct stat s;
-       gchar *real_path, *entry, *utf8entry, *utf8name;
+       gchar *entry, *utf8entry, *utf8name, *path;
        gint n_msg = 0;
+       GError *error = NULL;
 
-       g_return_if_fail(item != NULL);
-       g_return_if_fail(item->folder != NULL);
+       cm_return_if_fail(item != NULL);
+       cm_return_if_fail(item->folder != NULL);
 
        folder = item->folder;
 
-       real_path = item->path ? mh_filename_from_utf8(item->path) : g_strdup(".");
-#ifdef G_OS_WIN32
-       dir = g_dir_open(real_path, 0, NULL);
+       path = folder_item_get_path(item);
+       debug_print("mh_scan_tree_recursive() opening '%s'\n", path);
+       dir = g_dir_open(path, 0, &error);
        if (!dir) {
-               g_warning("failed to open directory: %s\n", real_path);
-               g_free(real_path);
-               return;
-       }
-#else
-       dp = opendir(real_path);
-       if (!dp) {
-               FILE_OP_ERROR(real_path, "opendir");
+               g_warning("failed to open directory '%s': %s (%d)",
+                               path, error->message, error->code);
+               g_error_free(error);
+               g_free(path);
                return;
        }
-#endif
-       g_free(real_path);
 
        debug_print("scanning %s ...\n",
                    item->path ? item->path
@@ -927,42 +1149,32 @@ static void mh_scan_tree_recursive(FolderItem *item)
        if (folder->ui_func)
                folder->ui_func(folder, item, folder->ui_func_data);
 
-#ifdef G_OS_WIN32
        while ((dir_name = g_dir_read_name(dir)) != NULL) {
-#else
-       while ((d = readdir(dp)) != NULL) {
-               dir_name = d->d_name;
-#endif
                if (dir_name[0] == '.') continue;
 
+               entry = g_strconcat(path, G_DIR_SEPARATOR_S, dir_name, NULL);
+
                utf8name = mh_filename_to_utf8(dir_name);
                if (item->path)
                        utf8entry = g_strconcat(item->path, G_DIR_SEPARATOR_S,
                                                utf8name, NULL);
                else
                        utf8entry = g_strdup(utf8name);
-               entry = mh_filename_from_utf8(utf8entry);
 
-               if (
-#if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
-                       d->d_type == DT_DIR ||
-                       (d->d_type == DT_UNKNOWN &&
-#endif
-                       g_stat(entry, &s) == 0 && S_ISDIR(s.st_mode)
-#if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
-                       )
-#endif
-                  ) {
+               if (g_file_test(entry, G_FILE_TEST_IS_DIR)) {
                        FolderItem *new_item = NULL;
                        GNode *node;
 
                        node = item->node;
                        for (node = node->children; node != NULL; node = node->next) {
                                FolderItem *cur_item = FOLDER_ITEM(node->data);
-                               if (!strcmp2(cur_item->path, entry)) {
+                               gchar *curpath = folder_item_get_path(cur_item);
+                               if (!strcmp2(curpath, entry)) {
                                        new_item = cur_item;
+                                       g_free(curpath);
                                        break;
                                }
+                               g_free(curpath);
                        }
                        if (!new_item) {
                                debug_print("new folder '%s' found.\n", entry);
@@ -1002,13 +1214,10 @@ static void mh_scan_tree_recursive(FolderItem *item)
                g_free(utf8name);
        }
 
-#ifdef G_OS_WIN32
        g_dir_close(dir);
-#else
-       closedir(dp);
-#endif
+       g_free(path);
 
-       item->mtime = time(NULL);
+       mh_set_mtime(folder, item);
 }
 
 static gboolean mh_rename_folder_func(GNode *node, gpointer data)
@@ -1023,7 +1232,7 @@ static gboolean mh_rename_folder_func(GNode *node, gpointer data)
 
        oldpathlen = strlen(oldpath);
        if (strncmp(oldpath, item->path, oldpathlen) != 0) {
-               g_warning("path doesn't match: %s, %s\n", oldpath, item->path);
+               g_warning("path doesn't match: %s, %s", oldpath, item->path);
                return TRUE;
        }
 
@@ -1045,7 +1254,7 @@ static gchar *mh_filename_from_utf8(const gchar *path)
        gchar *real_path = g_filename_from_utf8(path, -1, NULL, NULL, NULL);
 
        if (!real_path) {
-               g_warning("mh_filename_from_utf8: faild to convert character set\n");
+               g_warning("mh_filename_from_utf8: failed to convert character set");
                real_path = g_strdup(path);
        }
 
@@ -1056,7 +1265,7 @@ static gchar *mh_filename_to_utf8(const gchar *path)
 {
        gchar *utf8path = g_filename_to_utf8(path, -1, NULL, NULL, NULL);
        if (!utf8path) {
-               g_warning("mh_filename_to_utf8: faild to convert character set\n");
+               g_warning("mh_filename_to_utf8: failed to convert character set");
                utf8path = g_strdup(path);
        }
 
@@ -1078,7 +1287,7 @@ static gchar *get_unseen_seq_name(void)
                gchar buf[BUFFSIZE];
                gchar *tmp;
                gchar *profile_path = g_strconcat(
-                       g_get_home_dir(), G_DIR_SEPARATOR_S,
+                       get_home_dir(), G_DIR_SEPARATOR_S,
                        ".mh_profile", NULL);
                FILE *fp = g_fopen(profile_path, "r");
                if (fp) {
@@ -1103,112 +1312,15 @@ static gchar *get_unseen_seq_name(void)
        return seq_name;        
 }
 
-static gint mh_get_flags(Folder *folder, FolderItem *item,
-                           MsgInfoList *msginfo_list, GRelation *msgflags)
-{
-       gchar *mh_sequences_filename;
-       FILE *mh_sequences_file;
-       gchar buf[BUFFSIZE];
-       gchar *unseen_list = NULL;
-       gchar *path;
-       MsgInfoList *mcur = NULL;
-/*
-       GTimer *timer = g_timer_new();
-       g_timer_start(timer);
-*/
-       if (!item)
-               return 0;
-
-       /* don't update from .mh_sequences if the item's opened: mails may have
-        * been marked read/unread and it's not yet written in the file. */     
-       if (item->opened)
-               return 0;
-
-       path = folder_item_get_path(item);
-
-       mh_sequences_filename = g_strconcat(path, G_DIR_SEPARATOR_S,
-                                           ".mh_sequences", NULL);
-       g_free(path);
-       if ((mh_sequences_file = g_fopen(mh_sequences_filename, "r+b")) != NULL) {
-               while (fgets(buf, sizeof(buf), mh_sequences_file) != NULL) {
-                       if (!strncmp(buf, get_unseen_seq_name(), strlen(get_unseen_seq_name()))) {
-                               unseen_list = g_strdup(buf+strlen(get_unseen_seq_name()));
-                               break;
-                       }
-               }
-               fclose(mh_sequences_file);
-       }
-       
-       g_free(mh_sequences_filename);
-       
-       if (unseen_list) {
-               gchar *cur = NULL;
-               gchar *token = NULL, *next = NULL, *boundary = NULL;
-               gint num = 0;
-               GHashTable *unseen_table = g_hash_table_new(g_direct_hash, g_direct_equal);
-
-               cur = unseen_list = strretchomp(unseen_list);
-               debug_print("found unseen list in .mh_sequences: %s\n", unseen_list);
-next_token:
-               while (*cur && *cur == ' ')
-                       cur++;
-               
-               if ((next = strchr(cur, ' ')) != NULL) {
-                       token = cur;
-                       cur = next+1;
-                       *next = '\0';
-               } else {
-                       token = cur;
-                       cur = NULL;
-               }
-               
-               if ((boundary = strchr(token, '-')) != NULL) {
-                       gchar *start, *end;
-                       int i;
-                       start = token;
-                       end = boundary+1;
-                       *boundary='\0';
-                       for (i = atoi(start); i <= atoi(end); i++) {
-                               g_hash_table_insert(unseen_table, GINT_TO_POINTER(i), GINT_TO_POINTER(1));
-                       }
-               } else if ((num = atoi(token)) > 0) {
-                       g_hash_table_insert(unseen_table, GINT_TO_POINTER(num), GINT_TO_POINTER(1));
-               }
-               
-               if (cur)
-                       goto next_token;
-               for (mcur = msginfo_list; mcur; mcur = mcur->next) {
-                       MsgInfo *msginfo = (MsgInfo *)mcur->data;
-                       MsgPermFlags flags = msginfo->flags.perm_flags;
-                       if (g_hash_table_lookup(unseen_table, GINT_TO_POINTER(msginfo->msgnum))) {
-                               flags |= MSG_UNREAD;
-                       } else if (!(flags & MSG_NEW)) { /* don't mark new msgs as read */
-                               flags &= ~(MSG_UNREAD);
-                       }
-                       if (flags != msginfo->flags.perm_flags)
-                               g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
-               }
-               g_hash_table_destroy(unseen_table);
-               g_free(unseen_list);
-       }
-/*
-       g_timer_stop(timer);
-       printf("mh_get_flags: %f secs\n", g_timer_elapsed(timer, NULL));
-       g_timer_destroy(timer);
-*/
-       return 0;
-}
-
-static void mh_write_sequences(FolderItem *item)
+static void mh_write_sequences(FolderItem *item, gboolean remove_unseen)
 {
        gchar *mh_sequences_old, *mh_sequences_new;
        FILE *mh_sequences_old_fp, *mh_sequences_new_fp;
        gchar buf[BUFFSIZE];
        gchar *path = NULL;
-/*
-       GTimer *timer = g_timer_new();
-       g_timer_start(timer);
-*/
+       gboolean err = FALSE;
+       START_TIMING("");
+
        if (!item)
                return;
        
@@ -1224,11 +1336,12 @@ static void mh_write_sequences(FolderItem *item)
                MsgInfo *info = NULL;
                gint start = -1, end = -1;
                gchar *sequence = g_strdup("");
+               gint seq_len = 0;
                msglist = g_slist_sort(msglist, sort_cache_list_by_msgnum);
                cur = msglist;
                
-               /* write the unseen sequence */
-               do {
+               /* write the unseen sequence if we don't have to scrap it */
+               if (!remove_unseen) do {
                        info = (MsgInfo *)(cur ? cur->data:NULL);
                        if (info && (MSG_IS_UNREAD(info->flags) || MSG_IS_NEW(info->flags))) {
                                if (start < 0)
@@ -1237,49 +1350,93 @@ static void mh_write_sequences(FolderItem *item)
                                        end = info->msgnum;
                        } else {
                                if (start > 0 && end > 0) {
-                                       gchar *tmp = sequence;
+                                       gchar tmp[32];
+                                       gint tmp_len = 0;
                                        if (start != end)
-                                               sequence = g_strdup_printf("%s %d-%d ", tmp, start, end);
+                                               snprintf(tmp, 31, " %d-%d", start, end);
                                        else
-                                               sequence = g_strdup_printf("%s %d ", tmp, start);
-                                       g_free(tmp);
+                                               snprintf(tmp, 31, " %d", start);
+                                       
+                                       tmp_len = strlen(tmp);
+                                       sequence = g_realloc(sequence, seq_len+tmp_len+1);
+                                       strcpy(sequence+seq_len, tmp);
+                                       seq_len += tmp_len;
+
                                        start = end = -1;
                                }
                        }
                        cur = cur ? cur->next:NULL;
                } while (cur || (start > 0 && end > 0));
-               if (sequence && strlen(sequence)) {
-                       fprintf(mh_sequences_new_fp, "%s%s\n", 
-                                       get_unseen_seq_name(), sequence);
-                       debug_print("wrote unseen sequence: '%s%s'\n", 
+               if (sequence && *sequence) {
+                       if (fprintf(mh_sequences_new_fp, "%s%s\n", 
+                                       get_unseen_seq_name(), sequence) < 0)
+                               err = TRUE;
+                       else
+                               debug_print("wrote unseen sequence: '%s%s'\n", 
                                        get_unseen_seq_name(), sequence);
                }
                /* rewrite the rest of the file */
                if ((mh_sequences_old_fp = g_fopen(mh_sequences_old, "r+b")) != NULL) {
                        while (fgets(buf, sizeof(buf), mh_sequences_old_fp) != NULL) {
                                if (strncmp(buf, get_unseen_seq_name(), strlen(get_unseen_seq_name())))
-                                       fprintf(mh_sequences_new_fp, "%s", buf);
+                                       if (fprintf(mh_sequences_new_fp, "%s", buf) < 0) {
+                                               err = TRUE;
+                                               break;
+                                       }
                        }
                        fclose(mh_sequences_old_fp);
                }
                
-               fclose(mh_sequences_new_fp);
-               g_rename(mh_sequences_new, mh_sequences_old);
+               fflush(mh_sequences_new_fp);
+#if 0
+               fsync(fileno(mh_sequences_new_fp));
+#endif
+               if (fclose(mh_sequences_new_fp) == EOF)
+                       err = TRUE;
+
+               if (!err) {
+                       if (g_rename(mh_sequences_new, mh_sequences_old) < 0)
+                               FILE_OP_ERROR(mh_sequences_new, "rename");
+               }
                g_free(sequence);
                procmsg_msg_list_free(msglist);
        }
        g_free(mh_sequences_old);
        g_free(mh_sequences_new);
        g_free(path);
-/*
-       g_timer_stop(timer);
-       printf("mh_get_flags: %f secs\n", g_timer_elapsed(timer, NULL));
-       g_timer_destroy(timer);
-*/
+
+       END_TIMING();
 }
 
 static int mh_item_close(Folder *folder, FolderItem *item)
 {
-       mh_write_sequences(item);
+       time_t last_mtime = (time_t)0;
+       gboolean need_scan = mh_scan_required(item->folder, item);
+       last_mtime = item->mtime;
+
+       mh_write_sequences(item, FALSE);
+
+       if (item->mtime == last_mtime && !need_scan) {
+               mh_set_mtime(folder, item);
+       }
+
        return 0;
 }
+
+static void mh_set_mtime(Folder *folder, FolderItem *item)
+{
+       GStatBuf s;
+       gchar *path = folder_item_get_path(item);
+
+       cm_return_if_fail(path != NULL);
+
+       if (g_stat(path, &s) < 0) {
+               FILE_OP_ERROR(path, "stat");
+               g_free(path);
+               return;
+       }
+
+       item->mtime = s.st_mtime;
+       debug_print("MH: forced mtime of %s to %ld\n", item->name?item->name:"(null)", item->mtime);
+       g_free(path);
+}