Index: camel/camel-mime-filter-tohtml.c
===================================================================
--- camel/camel-mime-filter-tohtml.c	(revision 444)
+++ camel/camel-mime-filter-tohtml.c	(working copy)
@@ -47,12 +47,13 @@
 #define CONVERT_WEB_URLS  CAMEL_MIME_FILTER_TOHTML_CONVERT_URLS
 #define CONVERT_ADDRSPEC  CAMEL_MIME_FILTER_TOHTML_CONVERT_ADDRESSES
 
-static const struct {
-	const unsigned int mask;
-	const urlpattern_t pattern;
+static struct {
+	unsigned int mask;
+	urlpattern_t pattern;
 } patterns[] = {
 	{ CONVERT_WEB_URLS, { "file://",   "",        camel_url_file_start,     camel_url_file_end     } },
 	{ CONVERT_WEB_URLS, { "ftp://",    "",        camel_url_web_start,      camel_url_web_end      } },
+	{ CONVERT_WEB_URLS, { "sftp://",   "",        camel_url_web_start,      camel_url_web_end      } },
 	{ CONVERT_WEB_URLS, { "http://",   "",        camel_url_web_start,      camel_url_web_end      } },
 	{ CONVERT_WEB_URLS, { "https://",  "",        camel_url_web_start,      camel_url_web_end      } },
 	{ CONVERT_WEB_URLS, { "news://",   "",        camel_url_web_start,      camel_url_web_end      } },
@@ -164,13 +165,13 @@
 {
 	CamelMimeFilterToHTML *html = (CamelMimeFilterToHTML *) filter;
 	const char *inptr = in;
-
+	
 	while (inptr < inend) {
 		guint32 u;
-
+		
 		outptr = check_size (filter, outptr, outend, 16);
-
-		u = camel_utf8_getc_limit ((const unsigned char **) &inptr, inend);
+		
+		u = camel_utf8_getc_limit ((const unsigned char **) &inptr, (const unsigned char *) inend);
 		switch (u) {
 		case 0xffff:
 			g_warning("Truncated utf8 buffer");
Index: camel/camel-filter-search.c
===================================================================
--- camel/camel-filter-search.c	(revision 444)
+++ camel/camel-filter-search.c	(working copy)
@@ -22,9 +22,7 @@
  *
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 /* (from glibc headers:
    POSIX says that <sys/types.h> must be included (by the caller) before <regex.h>.  */
@@ -39,23 +37,26 @@
 #include <fcntl.h>
 #include <errno.h>
 
-#include <signal.h>
+#include <glib.h>
+
+#ifndef G_OS_WIN32
 #include <sys/wait.h>
+#endif
 
-#include <libedataserver/e-sexp.h>
-#include <libedataserver/e-iconv.h>
+#include "libedataserver/e-sexp.h"
+#include "libedataserver/e-iconv.h"
 
 #include "camel-debug.h"
+#include "camel-exception.h"
+#include "camel-filter-search.h"
+#include "camel-i18n.h"
 #include "camel-mime-message.h"
+#include "camel-multipart.h"
 #include "camel-provider.h"
+#include "camel-search-private.h"
 #include "camel-session.h"
-#include "camel-filter-search.h"
-#include "camel-exception.h"
-#include "camel-multipart.h"
+#include "camel-stream-fs.h"
 #include "camel-stream-mem.h"
-#include "camel-stream-fs.h"
-#include "camel-search-private.h"
-#include "camel-i18n.h"
 #include "camel-url.h"
 
 #define d(x)
@@ -155,11 +156,12 @@
 		if (g_ascii_strcasecmp(name, "x-camel-mlist") == 0) {
 			const char *list = camel_message_info_mlist(fms->info);
 
-			if (list)
+			if (list) {
 				for (i=1; i<argc && !matched; i++) {
 					if (argv[i]->type == ESEXP_RES_STRING)
 						matched = camel_search_header_match(list, argv[i]->value.string, how, CAMEL_SEARCH_TYPE_MLIST, NULL);
 				}
+			}
 		} else {
 			CamelMimeMessage *message = camel_filter_search_get_message (fms, f);
 			struct _camel_header_raw *header;
@@ -506,90 +508,106 @@
 	return r;
 }
 
+#ifndef G_OS_WIN32
+static void
+child_setup_func (gpointer user_data)
+{
+	setsid ();
+}
+#else
+#define child_setup_func NULL
+#endif
+
+typedef struct {
+	gint child_status;
+	GMainLoop *loop;
+} child_watch_data_t;
+
+static void
+child_watch (GPid     pid,
+	     gint     status,
+	     gpointer data)
+{
+	child_watch_data_t *child_watch_data = data;
+
+	g_spawn_close_pid (pid);
+
+	child_watch_data->child_status = status;
+
+	g_main_loop_quit (child_watch_data->loop);
+}
+
 static int
 run_command (struct _ESExp *f, int argc, struct _ESExpResult **argv, FilterMessageSearch *fms)
 {
 	CamelMimeMessage *message;
 	CamelStream *stream;
-	int result, status;
-	int in_fds[2];
-	pid_t pid;
+	int i;
+	int pipe_to_child;
+	GPid child_pid;
+	GError *error = NULL;
+	GPtrArray *args;
+	child_watch_data_t child_watch_data;
+	GSource *source;
 	
 	if (argc < 1 || argv[0]->value.string[0] == '\0')
 		return 0;
 	
-	if (pipe (in_fds) == -1) {
-		camel_exception_setv (fms->ex, CAMEL_EXCEPTION_SYSTEM,
-				      _("Failed to create pipe to '%s': %s"),
-				      argv[0]->value.string, g_strerror (errno));
-		return -1;
-	}
+	args = g_ptr_array_new ();
+	for (i = 0; i < argc; i++)
+		g_ptr_array_add (args, argv[i]->value.string);
+	g_ptr_array_add (args, NULL);
 	
-	if (!(pid = fork ())) {
-		/* child process */
-		GPtrArray *args;
-		int maxfd, fd, i;
-		
-		fd = open ("/dev/null", O_WRONLY);
-		
-		if (dup2 (in_fds[0], STDIN_FILENO) < 0 ||
-		    dup2 (fd, STDOUT_FILENO) < 0 ||
-		    dup2 (fd, STDERR_FILENO) < 0)
-			_exit (255);
-		
-		setsid ();
-		
-		maxfd = sysconf (_SC_OPEN_MAX);
-		for (fd = 3; fd < maxfd; fd++)
-			fcntl (fd, F_SETFD, FD_CLOEXEC);
-		
-		args = g_ptr_array_new ();
-		for (i = 0; i < argc; i++)
-			g_ptr_array_add (args, argv[i]->value.string);
-		g_ptr_array_add (args, NULL);
-		
-		execvp (argv[0]->value.string, (char **) args->pdata);
-		
+	if (!g_spawn_async_with_pipes (NULL,
+				       (gchar **) args->pdata,
+				       NULL,
+				       G_SPAWN_DO_NOT_REAP_CHILD |
+				       G_SPAWN_SEARCH_PATH |
+				       G_SPAWN_STDOUT_TO_DEV_NULL |
+				       G_SPAWN_STDERR_TO_DEV_NULL,
+				       child_setup_func,
+				       NULL,
+				       &child_pid,
+				       &pipe_to_child,
+				       NULL,
+				       NULL,
+				       &error)) {
 		g_ptr_array_free (args, TRUE);
-		
-		d(printf ("Could not execute %s: %s\n", argv[0]->value.string, g_strerror (errno)));
-		_exit (255);
-	} else if (pid < 0) {
+
 		camel_exception_setv (fms->ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Failed to create create child process '%s': %s"),
-				      argv[0]->value.string, g_strerror (errno));
+				      argv[0]->value.string, error->message);
+		g_error_free (error);
 		return -1;
 	}
 	
-	/* parent process */
-	close (in_fds[0]);
+	g_ptr_array_free (args, TRUE);
 	
 	message = camel_filter_search_get_message (fms, f);
 	
-	stream = camel_stream_fs_new_with_fd (in_fds[1]);
+	stream = camel_stream_fs_new_with_fd (pipe_to_child);
 	camel_data_wrapper_write_to_stream (CAMEL_DATA_WRAPPER (message), stream);
 	camel_stream_flush (stream);
 	camel_object_unref (stream);
 	
-	result = waitpid (pid, &status, 0);
-	
-	if (result == -1 && errno == EINTR) {
-		/* child process is hanging... */
-		kill (pid, SIGTERM);
-		sleep (1);
-		result = waitpid (pid, &status, WNOHANG);
-		if (result == 0) {
-			/* ...still hanging, set phasers to KILL */
-			kill (pid, SIGKILL);
-			sleep (1);
-			result = waitpid (pid, &status, WNOHANG);
-		}
-	}
-	
-	if (result != -1 && WIFEXITED (status))
-		return WEXITSTATUS (status);
+	child_watch_data.loop = g_main_loop_new (g_main_context_new (), FALSE);
+
+	source = g_child_watch_source_new (child_pid);
+	g_source_set_callback (source, (GSourceFunc) child_watch, &child_watch_data, NULL);
+	g_source_attach (source, g_main_loop_get_context (child_watch_data.loop));
+	g_source_unref (source);
+
+	g_main_loop_run (child_watch_data.loop);
+	g_main_loop_unref (child_watch_data.loop);
+
+#ifndef G_OS_WIN32
+	if (WIFEXITED (child_watch_data.child_status))
+		return WEXITSTATUS (child_watch_data.child_status);
 	else
 		return -1;
+#else
+	return child_watch_data.child_status;
+#endif
 }
 
 static ESExpResult *
Index: camel/camel-stream.c
===================================================================
--- camel/camel-stream.c	(revision 444)
+++ camel/camel-stream.c	(working copy)
@@ -28,6 +28,7 @@
 #endif
 
 #include <string.h>
+
 #include "camel-stream.h"
 
 static CamelObjectClass *parent_class = NULL;
Index: camel/camel-store.c
===================================================================
--- camel/camel-store.c	(revision 444)
+++ camel/camel-store.c	(working copy)
@@ -32,14 +32,13 @@
 #include <sys/stat.h>
 
 #include "camel-debug.h"
-
+#include "camel-exception.h"
+#include "camel-folder.h"
+#include "camel-i18n.h"
+#include "camel-private.h"
 #include "camel-session.h"
 #include "camel-store.h"
-#include "camel-folder.h"
 #include "camel-vtrash-folder.h"
-#include "camel-exception.h"
-#include "camel-private.h"
-#include "camel-i18n.h"
 
 #define d(x)
 #define w(x)
@@ -290,7 +289,7 @@
 	if (camel_debug_start(":store")) {
 		char *u = camel_url_to_string(((CamelService *)store)->url, CAMEL_URL_HIDE_PASSWORD);
 
-		printf("CamelStore('%s'):get_folder('%s', %d) = %p\n", u, folder_name, flags, folder);
+		printf("CamelStore('%s'):get_folder('%s', %u) = %p\n", u, folder_name, flags, folder);
 		if (ex && ex->id)
 			printf("  failed: '%s'\n", ex->desc);
 		g_free(u);
Index: camel/camel-transport.c
===================================================================
--- camel/camel-transport.c	(revision 444)
+++ camel/camel-transport.c	(working copy)
@@ -27,10 +27,10 @@
 #include <config.h>
 #endif
 
-#include "camel-transport.h"
 #include "camel-address.h"
 #include "camel-mime-message.h"
 #include "camel-private.h"
+#include "camel-transport.h"
 
 static CamelServiceClass *parent_class = NULL;
 
Index: camel/camel-mime-filter-pgp.c
===================================================================
--- camel/camel-mime-filter-pgp.c	(revision 444)
+++ camel/camel-mime-filter-pgp.c	(working copy)
@@ -3,6 +3,7 @@
  * Copyright (C) 2005 Matt Brown.
  *
  * Authors: Matt Brown <matt@mattb.net.nz>
+ *          Jeffrey Stedfast <fejj@novell.com>
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of version 2 of the GNU Lesser General Public
@@ -39,9 +40,10 @@
 static void reset (CamelMimeFilter *f);
 
 enum {
-	PGPF_HEADER,
-	PGPF_MESSAGE,
-	PGPF_FOOTER,
+	PGP_PREFACE,
+	PGP_HEADER,
+	PGP_MESSAGE,
+	PGP_FOOTER,
 };
 
 static void
@@ -60,7 +62,8 @@
 	static CamelType type = CAMEL_INVALID_TYPE;
 	
 	if (type == CAMEL_INVALID_TYPE) {
-		type = camel_type_register (camel_mime_filter_get_type(), "CamelMimeFilterPgp",
+		type = camel_type_register (camel_mime_filter_get_type (),
+					    "CamelMimeFilterPgp",
 					    sizeof (CamelMimeFilterPgp),
 					    sizeof (CamelMimeFilterPgpClass),
 					    (CamelObjectClassInitFunc) camel_mime_filter_pgp_class_init,
@@ -72,94 +75,103 @@
 	return type;
 }
 
+#define BEGIN_PGP_SIGNED_MESSAGE "-----BEGIN PGP SIGNED MESSAGE-----"
+#define BEGIN_PGP_SIGNATURE      "-----BEGIN PGP SIGNATURE-----"
+#define END_PGP_SIGNATURE        "-----END PGP SIGNATURE-----"
+
 static void
 filter_run(CamelMimeFilter *f, char *in, size_t len, size_t prespace, char **out, size_t *outlen, size_t *outprespace, int last)
 {
-	CamelMimeFilterPgp *pgpfilter = (CamelMimeFilterPgp *)f;
-	char *inptr, *inend;
+	CamelMimeFilterPgp *pgp = (CamelMimeFilterPgp *) f;
+	const char *start, *inend = in + len;
+	register const char *inptr = in;
 	register char *o;
-	char *start = in;
-	int tmplen;
 	
 	/* only need as much space as the input, we're stripping chars */
-	camel_mime_filter_set_size(f, len, FALSE);
-
+	camel_mime_filter_set_size (f, len, FALSE);
+	
 	o = f->outbuf;
-	inptr = in;
-	inend = in+len;
+	
 	while (inptr < inend) {
 		start = inptr;
-
+		
 		while (inptr < inend && *inptr != '\n')
 			inptr++;
-			
+		
 		if (inptr == inend) {
 			if (!last) {
-				camel_mime_filter_backup(f, start, inend-start);
+				camel_mime_filter_backup (f, start, inend - start);
 				inend = start;
 			}
 			break;
 		}
-
-		*inptr++ = 0;
 		
-		switch (pgpfilter->state) {
-		case PGPF_HEADER:
-			/* Wait for a blank line */
-			if (strlen(start)==0)
-				pgpfilter->state = PGPF_MESSAGE;
+		inptr++;
+		
+		switch (pgp->state) {
+		case PGP_PREFACE:
+			/* check for the beginning of the pgp block */
+			if (!strncmp (start, BEGIN_PGP_SIGNED_MESSAGE, sizeof (BEGIN_PGP_SIGNED_MESSAGE) - 1)) {
+				pgp->state++;
+				break;
+			}
+			
+			memcpy (o, start, inptr - start);
+			o += (inptr - start);
 			break;
-		case PGPF_MESSAGE:
-			/* In the message body, check for end of body */
-			if (strncmp(start, "-----", 5)==0) {
-				pgpfilter->state = PGPF_FOOTER;
+		case PGP_HEADER:
+			/* pgp headers (Hash: SHA1, etc) end with a blank line */
+			if ((inptr - start) == 1)
+				pgp->state++;
+			break;
+		case PGP_MESSAGE:
+			/* check for beginning of the pgp signature block */
+			if (!strncmp (start, BEGIN_PGP_SIGNATURE, sizeof (BEGIN_PGP_SIGNATURE) - 1)) {
+				pgp->state++;
 				break;
-			}			
+			}
+			
 			/* do dash decoding */
-			if (strncmp(start, "- ", 2)==0) {
+			if (!strncmp (start, "- ", 2)) {
 				/* Dash encoded line found, skip encoding */
-				start+=2;
+				start += 2;
 			}
-			tmplen=strlen(start)+1;
-			inptr[-1] = '\n';
-			strncpy(o, start, tmplen);
-			o+=tmplen;	
+			
+			memcpy (o, start, inptr - start);
+			o += (inptr - start);
 			break;
-		case PGPF_FOOTER:
-			/* After end of message, (ie signature or something) skip it */
+		case PGP_FOOTER:
+			if (!strncmp (start, END_PGP_SIGNATURE, sizeof (END_PGP_SIGNATURE) - 1))
+				pgp->state = PGP_PREFACE;
 			break;
 		}
-		inptr[-1] = '\n';
 	}
 	
 	*out = f->outbuf;
 	*outlen = o - f->outbuf;
 	*outprespace = f->outpre;
-	
 }
 
 static void
-filter(CamelMimeFilter *f, char *in, size_t len, size_t prespace, char **out, size_t *outlen, size_t *outprespace)
+filter (CamelMimeFilter *f, char *in, size_t len, size_t prespace, char **out, size_t *outlen, size_t *outprespace)
 {
-	filter_run(f, in, len, prespace, out, outlen, outprespace, FALSE);
+	filter_run (f, in, len, prespace, out, outlen, outprespace, FALSE);
 }
 
 static void 
-complete(CamelMimeFilter *f, char *in, size_t len, size_t prespace, char **out, size_t *outlen, size_t *outprespace)
+complete (CamelMimeFilter *f, char *in, size_t len, size_t prespace, char **out, size_t *outlen, size_t *outprespace)
 {
-	filter_run(f, in, len, prespace, out, outlen, outprespace, TRUE);
+	filter_run (f, in, len, prespace, out, outlen, outprespace, TRUE);
 }
 
 static void
 reset (CamelMimeFilter *f)
 {
-	/* no-op */
+	((CamelMimeFilterPgp *) f)->state = PGP_PREFACE;
 }
 
 CamelMimeFilter *
 camel_mime_filter_pgp_new(void)
 {
-	CamelMimeFilterPgp *pgpfilter = (CamelMimeFilterPgp *)camel_object_new (camel_mime_filter_pgp_get_type());
-
-	return (CamelMimeFilter *) pgpfilter;
+	return (CamelMimeFilter *) camel_object_new (camel_mime_filter_pgp_get_type ());
 }
Index: camel/camel-index.c
===================================================================
--- camel/camel-index.c	(revision 444)
+++ camel/camel-index.c	(working copy)
@@ -31,7 +31,7 @@
 #include <stdlib.h>
 
 #include "camel-index.h"
-#include "camel/camel-object.h"
+#include "camel-object.h"
 
 #define w(x)
 #define io(x)
Index: camel/camel-stream-process.c
===================================================================
--- camel/camel-stream-process.c	(revision 444)
+++ camel/camel-stream-process.c	(working copy)
@@ -39,8 +39,8 @@
 #include <fcntl.h>
 #include <errno.h>
 
+#include "camel-file-utils.h"
 #include "camel-stream-process.h"
-#include "camel-file-utils.h"
 
 extern int camel_verbose_debug;
 
Index: camel/providers/nntp/ChangeLog
===================================================================
--- camel/providers/nntp/ChangeLog	(revision 444)
+++ camel/providers/nntp/ChangeLog	(working copy)
@@ -1,3 +1,43 @@
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-nntp-store.c: 
+	* camel-nntp-folder.c: 
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
+2006-06-15  Andre Klapper <a9016009@gmx.de>
+
+	* addressbook/libebook/e-book.c:
+	* camel/camel-folder.c:
+	* camel/providers/nntp/camel-nntp-folder.c:
+	* camel/providers/pop3/camel-pop3-folder.c:
+	changing "uri" to "URI" in user-visible strings.
+	Fixes bug #342161.
+
+2006-06-09  Chris Heath  <chris@heathens.co.nz>
+
+	* camel-nntp-summary.c (message_info_new_from_header): Fix memory leak.
+	Fixes bug #335423.
+
+2005-12-13  Tor Lillqvist  <tml@novell.com>
+
+	* camel-nntp-grouplist.c
+	* camel-nntp-newsrc.c: Use gstdio wrappers.
+
+2005-11-30  Tor Lillqvist  <tml@novell.com>
+
+	* camel-nntp-folder.c
+	* camel-nntp-store.c: Remove some unneeded headers.
+
+2005-09-16  Tor Lillqvist  <tml@novell.com>
+
+	* camel-nntp-stream.c: If no ECONNRESET (Win32), use EIO instead.
+
+	* camel-nntp-utils.c: Use g_ascii_strcasecmp() instead of the
+	deprecated g_strcasecmp(). The strings we are comparing are just
+	ASCII anyway, so spell it out that we really do need ASCII
+	casefolding only.
+
 2005-08-22  Not Zed  <NotZed@Ximian.com>
 
 	* camel-nntp-stream.c (stream_read): cast print args to int.
Index: camel/providers/nntp/camel-nntp-folder.c
===================================================================
--- camel/providers/nntp/camel-nntp-folder.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-folder.c	(working copy)
@@ -28,12 +28,10 @@
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
-#include <sys/stat.h>
-#include <dirent.h>
 #include <unistd.h>
-#include <fcntl.h>
 #include <errno.h>
 
+#include <libedataserver/e-data-server-util.h>
 #include "camel/camel-file-utils.h"
 #include "camel/camel-stream-mem.h"
 #include "camel/camel-data-wrapper.h"
@@ -154,7 +152,7 @@
 	
  fail:
 	if (errno == EINTR)
-		camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+		camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 	else
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot get message %s: %s"), msgid, g_strerror (errno));
 	
@@ -174,7 +172,7 @@
 	msgid = strchr(article, ',');
 	if (!msgid) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
-				      _("Internal error: uid in invalid format: %s"), uid);
+				      _("Internal error: UID in invalid format: %s"), uid);
 		return;
 	}
 	*msgid++ = 0;
@@ -206,7 +204,7 @@
 	msgid = strchr (article, ',');
 	if (msgid == NULL) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
-				      _("Internal error: uid in invalid format: %s"), uid);
+				      _("Internal error: UID in invalid format: %s"), uid);
 		return NULL;
 	}
 	*msgid++ = 0;
@@ -230,7 +228,7 @@
 	message = camel_mime_message_new ();
 	if (camel_data_wrapper_construct_from_stream ((CamelDataWrapper *) message, stream) == -1) {
 		if (errno == EINTR)
-			camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+			camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot get message %s: %s"), uid, g_strerror (errno));
 		camel_object_unref(message);
@@ -369,7 +367,7 @@
 	    || camel_stream_write (stream, "\r\n.\r\n", 5) == -1
 	    || (ret = camel_nntp_stream_line (nntp_store->stream, (unsigned char **)&line, &u)) == -1) {
 		if (errno == EINTR)
-			camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+			camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM, _("Posting failed: %s"), g_strerror (errno));
 	} else if (atoi(line) != 240) {
@@ -494,7 +492,7 @@
 		return NULL;
 	
 	/* If this doesn't work, stuff wont save, but let it continue anyway */
-	camel_mkdir (root, 0777);
+	e_util_mkdir_hier (root, 0777);
 	
 	folder = (CamelFolder *) camel_object_new (CAMEL_NNTP_FOLDER_TYPE);
 	nntp_folder = (CamelNNTPFolder *)folder;
Index: camel/providers/nntp/camel-nntp-store-summary.c
===================================================================
--- camel/providers/nntp/camel-nntp-store-summary.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-store-summary.c	(working copy)
@@ -209,7 +209,7 @@
 char *
 camel_nntp_store_summary_path_to_full (CamelNNTPStoreSummary *s, const char *path, char dir_sep)
 {
-	unsigned char *full, *f;
+	char *full, *f;
 	guint32 c, v = 0;
 	const char *p;
 	int state=0;
Index: camel/providers/nntp/camel-nntp-grouplist.c
===================================================================
--- camel/providers/nntp/camel-nntp-grouplist.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-grouplist.c	(working copy)
@@ -25,7 +25,11 @@
 #include <errno.h>
 #include <string.h>
 
-#include "camel-exception.h"
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include "camel/camel-exception.h"
+
 #include "camel-nntp-grouplist.h"
 #include "camel-nntp-resp-codes.h"
 
@@ -89,7 +93,7 @@
 	unsigned long time;
 
 	g_free (root_dir);
-	fp = fopen (grouplist_file, "r");
+	fp = g_fopen (grouplist_file, "r");
 	g_free (grouplist_file);
 
 	if (fp == NULL) {
@@ -149,7 +153,7 @@
 	gchar *grouplist_file = g_strdup_printf ("%s/grouplist", root_dir);
 
 	g_free (root_dir);
-	fp = fopen (grouplist_file, "w");
+	fp = g_fopen (grouplist_file, "w");
 	g_free (grouplist_file);
 
 	if (fp == NULL) {
Index: camel/providers/nntp/camel-nntp-provider.c
===================================================================
--- camel/providers/nntp/camel-nntp-provider.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-provider.c	(working copy)
@@ -37,7 +37,7 @@
 static gint check_equal (char *s1, char *s2);
 static gint nntp_url_equal (gconstpointer a, gconstpointer b);
 
-CamelProviderConfEntry nntp_conf_entries[] = {
+static CamelProviderConfEntry nntp_conf_entries[] = {
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "folders", NULL,
 	  N_("Folders") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "show_short_notation", NULL,
Index: camel/providers/nntp/camel-nntp-stream.c
===================================================================
--- camel/providers/nntp/camel-nntp-stream.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-stream.c	(working copy)
@@ -36,6 +36,10 @@
 
 #define dd(x) (camel_debug("nntp:stream")?(x):0)
 
+#ifndef ECONNRESET
+#define ECONNRESET EIO
+#endif
+
 static CamelObjectClass *parent_class = NULL;
 
 /* Returns the class for a CamelStream */
Index: camel/providers/nntp/camel-nntp-store.c
===================================================================
--- camel/providers/nntp/camel-nntp-store.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-store.c	(working copy)
@@ -30,7 +30,6 @@
 #include <string.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <dirent.h>
 #include <errno.h>
 
 #include <camel/camel-url.h>
@@ -169,7 +168,6 @@
 	gboolean retval = FALSE;
 	unsigned char *buf;
 	unsigned int len;
-	int ret;
 	char *path;
 	
 	CAMEL_SERVICE_LOCK(store, connect_lock);
@@ -192,10 +190,10 @@
 		tcp_stream = camel_tcp_stream_raw_new ();
 	}
 	
-	if ((ret = camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai)) == -1) {
+	if (camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai) == -1) {
 		if (errno == EINTR)
 			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-					     _("Connection cancelled"));
+					     _("Connection canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 					      _("Could not connect to %s: %s"),
@@ -214,7 +212,7 @@
 	if (camel_nntp_stream_line (store->stream, &buf, &len) == -1) {
 		if (errno == EINTR)
 			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-					     _("Connection cancelled"));
+					     _("Connection canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 					      _("Could not read greeting from %s: %s"),
@@ -562,7 +560,7 @@
 		}
 	}
 
-	printf("store info update '%s' first '%d' last '%d'\n", line, first, last);
+	printf("store info update '%s' first '%u' last '%u'\n", line, first, last);
 
 	if (si->last) {
 		if (last > si->last)
@@ -1270,7 +1268,7 @@
 
 ioerror:
 	if (errno == EINTR)
-		camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled."));
+		camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled."));
 	else
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM, _("NNTP Command failed: %s"), g_strerror(errno));
 	return -1;
Index: camel/providers/nntp/camel-nntp-summary.c
===================================================================
--- camel/providers/nntp/camel-nntp-summary.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-summary.c	(working copy)
@@ -150,7 +150,8 @@
 
 	mi = (CamelMessageInfoBase *)((CamelFolderSummaryClass *)camel_nntp_summary_parent)->message_info_new_from_header(s, h);
 	if (mi) {
-		mi->uid = g_strdup(cns->priv->uid);
+		g_free(mi->uid);
+		mi->uid = cns->priv->uid;
 		cns->priv->uid = NULL;
 	}
 	
@@ -161,18 +162,23 @@
 summary_header_load(CamelFolderSummary *s, FILE *in)
 {
 	CamelNNTPSummary *cns = CAMEL_NNTP_SUMMARY(s);
+	gint32 *ptr32 = s->filepos;
+	unsigned char *ptrchr = s->filepos;
 
 	if (((CamelFolderSummaryClass *)camel_nntp_summary_parent)->summary_header_load(s, in) == -1)
 		return -1;
 
 	/* Legacy version */
 	if (s->version == 0x20c) {
-		camel_file_util_decode_fixed_int32(in, &cns->high);
-		return camel_file_util_decode_fixed_int32(in, &cns->low);
+		cns->high = g_ntohl (*ptr32); ptr32++;
+		cns->low = g_ntohl (*ptr32); ptr32++;
+		s->filepos = ptr32;
+
+		return 0;
 	}
 
-	if (camel_file_util_decode_fixed_int32(in, &cns->version) == -1)
-		return -1;
+	cns->version = g_ntohl (*ptr32); ptr32++;
+	s->filepos = ptr32;
 
 	if (cns->version > CAMEL_NNTP_SUMMARY_VERSION) {
 		g_warning("Unknown NNTP summary version");
@@ -180,10 +186,11 @@
 		return -1;
 	}
 
-	if (camel_file_util_decode_fixed_int32(in, &cns->high) == -1
-	    || camel_file_util_decode_fixed_int32(in, &cns->low) == -1)
-		return -1;
+	cns->high = g_ntohl (*ptr32); ptr32++;
+	cns->low = g_ntohl (*ptr32); ptr32++;
 
+	s->filepos = ptr32;
+
 	return 0;
 }
 
@@ -303,9 +310,9 @@
 add_range_head(CamelNNTPSummary *cns, CamelNNTPStore *store, unsigned int high, unsigned int low, CamelFolderChangeInfo *changes, CamelException *ex)
 {
 	CamelFolderSummary *s;
-	int i, ret = -1;
+	int ret = -1;
 	char *line, *msgid;
-	unsigned int n, count, total;
+	unsigned int i, n, count, total;
 	CamelMessageInfo *mi;
 	CamelMimeParser *mp;
 
@@ -333,7 +340,7 @@
 		line += 3;
 		n = strtoul(line, &line, 10);
 		if (n != i)
-			g_warning("retrieved message '%d' when i expected '%d'?\n", n, i);
+			g_warning("retrieved message '%u' when i expected '%u'?\n", n, i);
 		
 		/* FIXME: use camel-mime-utils.c function for parsing msgid? */
 		if ((msgid = strchr(line, '<')) && (line = strchr(msgid+1, '>'))){
Index: camel/providers/nntp/camel-nntp-utils.c
===================================================================
--- camel/providers/nntp/camel-nntp-utils.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-utils.c	(working copy)
@@ -185,17 +185,17 @@
 
 			for (h = 0; h < header_array->len; h ++) {
 				Rfc822Header *header = &((Rfc822Header*)header_array->data)[h];
-				if (!g_strcasecmp(header->name, "From"))
+				if (!g_ascii_strcasecmp(header->name, "From"))
 					new_info->from = g_strdup(header->value);
-				else if (!g_strcasecmp(header->name, "To"))
+				else if (!g_ascii_strcasecmp(header->name, "To"))
 					new_info->to = g_strdup(header->value);
-				else if (!g_strcasecmp(header->name, "Subject"))
+				else if (!g_ascii_strcasecmp(header->name, "Subject"))
 					new_info->subject = g_strdup(header->value);
-				else if (!g_strcasecmp(header->name, "Message-ID")) {
+				else if (!g_ascii_strcasecmp(header->name, "Message-ID")) {
 					new_info->uid = g_strdup_printf("%d,%s", i, header->value);
 					new_info->message_id = g_strdup(header->value);
 				}
-				else if (!g_strcasecmp(header->name, "Date")) {
+				else if (!g_ascii_strcasecmp(header->name, "Date")) {
 					new_info->date_sent = camel_header_decode_date (header->value);
 #if 0
 					new_info->date_sent = g_strdup(header->value);
Index: camel/providers/nntp/camel-nntp-newsrc.c
===================================================================
--- camel/providers/nntp/camel-nntp-newsrc.c	(revision 444)
+++ camel/providers/nntp/camel-nntp-newsrc.c	(working copy)
@@ -20,13 +20,8 @@
  *
  */
 
-
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
-#include <glib.h>
-
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
@@ -35,8 +30,12 @@
 #include <fcntl.h>
 #include <errno.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include "camel/camel-folder-summary.h"
+
 #include "camel-nntp-newsrc.h"
-#include <camel/camel-folder-summary.h>
 
 #define NEWSRC_LOCK(f, l) (g_mutex_lock(((CamelNNTPNewsrc *)f)->l))
 #define NEWSRC_UNLOCK(f, l) (g_mutex_unlock(((CamelNNTPNewsrc *)f)->l))
@@ -485,7 +484,7 @@
 		return;
 	}
 
-	if ((fp = fopen(newsrc->filename, "w")) == NULL) {
+	if ((fp = g_fopen(newsrc->filename, "w")) == NULL) {
 		g_warning ("Couldn't open newsrc file '%s'.\n", newsrc->filename);
 		NEWSRC_UNLOCK(newsrc, lock);
 		return;
@@ -614,7 +613,7 @@
 	newsrc->groups = g_hash_table_new (g_str_hash, g_str_equal);
 	newsrc->lock = g_mutex_new();
 	
-	if ((fd = open(filename, O_RDONLY)) == -1) {
+	if ((fd = g_open(filename, O_RDONLY, 0)) == -1) {
 		g_warning ("~/.newsrc-%s not present.\n", server);
 		return newsrc;
 	}
Index: camel/providers/pop3/camel-pop3-engine.c
===================================================================
--- camel/providers/pop3/camel-pop3-engine.c	(revision 444)
+++ camel/providers/pop3/camel-pop3-engine.c	(working copy)
@@ -74,6 +74,10 @@
 
 	if (pe->stream)
 		camel_object_unref(pe->stream);
+	
+	g_list_free(pe->auth);
+	if (pe->apop)
+		g_free(pe->apop);
 }
 
 CamelType
@@ -170,7 +174,7 @@
 
 /* TODO: read implementation too?
    etc? */
-struct {
+static struct {
 	char *cap;
 	guint32 flag;
 } capa[] = {
Index: camel/providers/pop3/ChangeLog
===================================================================
--- camel/providers/pop3/ChangeLog	(revision 444)
+++ camel/providers/pop3/ChangeLog	(working copy)
@@ -1,3 +1,41 @@
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-pop3-store.c: 
+	* camel-pop3-folder.c: 
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
+2006-06-15  Andre Klapper <a9016009@gmx.de>
+
+	* addressbook/libebook/e-book.c:
+	* camel/camel-folder.c:
+	* camel/providers/nntp/camel-nntp-folder.c:
+	* camel/providers/pop3/camel-pop3-folder.c:
+	changing "uri" to "URI" in user-visible strings.
+	Fixes bug #342161.
+
+2006-06-09  Chris Heath  <chris@heathens.co.nz>
+
+	* camel-pop3-engine.c (camel_pop3_engine_finalise): Fix memory leak.
+	Fixes bug #335423.
+
+2006-05-31  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-pop3-store.c (connect_to_server): Fix a few of the TLS
+	error strings to be more informative. Fixes the confusion in bug
+	#342001.
+
+2006-04-21  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-pop3-store.c (connect_to_server_wrapper): Don't do
+	fallback for SSL/TLS. Fixes bug #321797.
+
+2005-09-16  Tor Lillqvist  <tml@novell.com>
+
+	* camel-pop3-folder.c: Use g_ascii_strcasecmp() instead of
+	strcasecmp(). The strings we are comparing are just ASCII anyway,
+	so spell it out that we really do need ASCII casefolding only.
+
 2005-08-22  Not Zed  <NotZed@Ximian.com>
 
 	* camel-pop3-stream.c: fix some debug printfs to use
Index: camel/providers/pop3/camel-pop3-provider.c
===================================================================
--- camel/providers/pop3/camel-pop3-provider.c	(revision 444)
+++ camel/providers/pop3/camel-pop3-provider.c	(working copy)
@@ -34,7 +34,8 @@
 #include "camel-sasl.h"
 #include "camel-i18n.h"
 
-CamelProviderConfEntry pop3_conf_entries[] = {
+
+static CamelProviderConfEntry pop3_conf_entries[] = {
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "storage", NULL,
 	  N_("Message storage") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "keep_on_server", NULL,
Index: camel/providers/pop3/camel-pop3-folder.c
===================================================================
--- camel/providers/pop3/camel-pop3-folder.c	(revision 444)
+++ camel/providers/pop3/camel-pop3-folder.c	(working copy)
@@ -162,8 +162,8 @@
 	case CAMEL_MIME_PARSER_STATE_MULTIPART:
 		h = camel_mime_parser_headers_raw(mp);
 		while (h) {
-			if (strcasecmp(h->name, "status") != 0
-			    && strcasecmp(h->name, "x-status") != 0) {
+			if (g_ascii_strcasecmp(h->name, "status") != 0
+			    && g_ascii_strcasecmp(h->name, "x-status") != 0) {
 				md5_update(&md5, h->name, strlen(h->name));
 				md5_update(&md5, h->value, strlen(h->value));
 			}
@@ -260,7 +260,7 @@
 
 	if (i == -1) {
 		if (errno == EINTR)
-			camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+			camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 					      _("Cannot get POP summary: %s"),
@@ -396,13 +396,13 @@
 	CamelPOP3Command *pcr;
 	CamelPOP3FolderInfo *fi;
 	char buffer[1];
-	int ok, i, last;
+	int i, last;
 	CamelStream *stream = NULL;
 
 	fi = g_hash_table_lookup(pop3_folder->uids_uid, uid);
 	if (fi == NULL) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_FOLDER_INVALID_UID,
-				      _("No message with uid %s"), uid);
+				      _("No message with UID %s"), uid);
 		return NULL;
 	}
 
@@ -422,13 +422,13 @@
 			fi->err = errno;
 
 		/* getting error code? */
-		ok = fi->cmd->state == CAMEL_POP3_COMMAND_DATA;
+		/*g_assert (fi->cmd->state == CAMEL_POP3_COMMAND_DATA);*/
 		camel_pop3_engine_command_free(pop3_store->engine, fi->cmd);
 		fi->cmd = NULL;
 
 		if (fi->err != 0) {
 			if (fi->err == EINTR)
-				camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+				camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 			else
 				camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 						      _("Cannot get message %s: %s"),
@@ -482,14 +482,14 @@
 			fi->err = errno;
 
 		/* getting error code? */
-		ok = pcr->state == CAMEL_POP3_COMMAND_DATA;
+		/*g_assert (pcr->state == CAMEL_POP3_COMMAND_DATA);*/
 		camel_pop3_engine_command_free(pop3_store->engine, pcr);
 		camel_stream_reset(stream);
 
 		/* Check to see we have safely written flag set */
 		if (fi->err != 0) {
 			if (fi->err == EINTR)
-				camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+				camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 			else
 				camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 						      _("Cannot get message %s: %s"),
@@ -507,7 +507,7 @@
 	message = camel_mime_message_new ();
 	if (camel_data_wrapper_construct_from_stream((CamelDataWrapper *)message, stream) == -1) {
 		if (errno == EINTR)
-			camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+			camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 					      _("Cannot get message %s: %s"),
Index: camel/providers/pop3/camel-pop3-store.c
===================================================================
--- camel/providers/pop3/camel-pop3-store.c	(revision 444)
+++ camel/providers/pop3/camel-pop3-store.c	(working copy)
@@ -176,7 +176,7 @@
 	if ((ret = camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai)) == -1) {
 		if (errno == EINTR)
 			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-					     _("Connection cancelled"));
+					     _("Connection canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 					      _("Could not connect to %s: %s"),
@@ -214,7 +214,7 @@
 	if (!(store->engine->capa & CAMEL_POP3_CAP_STLS)) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Failed to connect to POP server %s in secure mode: %s"),
-				      service->url->host, _("STLS not supported"));
+				      service->url->host, _("STLS not supported by server"));
 		goto stls_exception;
 	}
 	
@@ -241,13 +241,13 @@
 	if (ret == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Failed to connect to POP server %s in secure mode: %s"),
-				      service->url->host, _("SSL negotiations failed"));
+				      service->url->host, _("TLS negotiations failed"));
 		goto stls_exception;
 	}
 #else
 	camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 			      _("Failed to connect to POP server %s in secure mode: %s"),
-			      service->url->host, _("SSL is not available in this build"));
+			      service->url->host, _("TLS is not available in this build"));
 	goto stls_exception;
 #endif /* HAVE_SSL */
 	
@@ -324,16 +324,11 @@
 		camel_exception_clear (ex);
 		ai = camel_getaddrinfo(service->url->host, port, &hints, ex);
 	}
+	
 	if (ai == NULL)
 		return FALSE;
 	
-	if (!(ret = connect_to_server (service, ai, mode, ex)) && mode == MODE_SSL) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (service, ai, MODE_TLS, ex);
-	} else if (!ret && mode == MODE_TLS) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (service, ai, MODE_CLEAR, ex);
-	}
+	ret = connect_to_server (service, ai, mode, ex);
 	
 	camel_freeaddrinfo (ai);
 	
@@ -443,7 +438,7 @@
 	
  ioerror:
 	if (errno == EINTR) {
-		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled"));
+		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled"));
 	} else {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Failed to authenticate on POP server %s: %s"),
@@ -524,7 +519,7 @@
 	
 	if (status == -1) {
 		if (errno == EINTR) {
-			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled"));
+			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled"));
 		} else {
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 					      _("Unable to connect to POP server %s.\n"
Index: camel/providers/smtp/ChangeLog
===================================================================
--- camel/providers/smtp/ChangeLog	(revision 444)
+++ camel/providers/smtp/ChangeLog	(working copy)
@@ -1,3 +1,29 @@
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-smtp-transport.c: 
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
+2006-05-10  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-smtp-transport.c (smtp_helo): Implement the correct fix.
+
+2006-05-09  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-smtp-transport.c (smtp_helo): Reverted. David Woodhouse
+	can fix his own damn server since he configured it to be broken.
+
+2006-04-21  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-smtp-transport.c (connect_to_server_wrapper): Don't do
+	fallback for SSL/TLS. Fixes bug #321797.
+
+2006-04-18  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-smtp-transport.c (smtp_helo): If the hostname isn't valid
+	(contains invalid chars, etc), then fallback to numeric host
+	address. Fixes bug #336035. Based on a patch by David Woodhouse.
+
 2005-08-12  Tor Lillqvist  <tml@novell.com>
 
 	* Makefile.am: Use NO_UNDEFINED. Link with libcamel-provider,
Index: camel/providers/smtp/camel-smtp-transport.c
===================================================================
--- camel/providers/smtp/camel-smtp-transport.c	(revision 444)
+++ camel/providers/smtp/camel-smtp-transport.c	(working copy)
@@ -263,7 +263,7 @@
 	if ((ret = camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai)) == -1) {
 		if (errno == EINTR)
 			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-					     _("Connection cancelled"));
+					     _("Connection canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 					      _("Could not connect to %s: %s"),
@@ -431,16 +431,11 @@
 		camel_exception_clear (ex);
 		ai = camel_getaddrinfo(service->url->host, port, &hints, ex);
 	}
+	
 	if (ai == NULL)
 		return FALSE;
 	
-	if (!(ret = connect_to_server (service, ai, mode, ex)) && mode == MODE_SSL) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (service, ai, MODE_TLS, ex);
-	} else if (!ret && mode == MODE_TLS) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (service, ai, MODE_CLEAR, ex);
-	}
+	ret = connect_to_server (service, ai, mode, ex);
 	
 	camel_freeaddrinfo (ai);
 	
@@ -875,9 +870,10 @@
 static gboolean
 smtp_helo (CamelSmtpTransport *transport, CamelException *ex)
 {
-	/* say hello to the server */
 	char *name = NULL, *cmdbuf = NULL, *respbuf = NULL;
 	const char *token, *numeric = NULL;
+	struct sockaddr *addr;
+	socklen_t addrlen;
 	
 	/* these are flags that we set, so unset them in case we
 	   are being called a second time (ie, after a STARTTLS) */
@@ -892,20 +888,19 @@
 	}
 	
 	camel_operation_start_transient (NULL, _("SMTP Greeting"));
-
-	/* force name resolution first, fallback to numerical, we need to know when it falls back */
-	if (camel_getnameinfo(transport->localaddr, transport->localaddrlen, &name, NULL, NI_NAMEREQD, NULL) != 0) {
-		if (camel_getnameinfo(transport->localaddr, transport->localaddrlen, &name, NULL, NI_NUMERICHOST, NULL) != 0)
-			name = g_strdup("localhost.localdomain");
-		else {
-			if (transport->localaddr->sa_family == AF_INET6)
-				numeric = "IPv6:";
-			else
-				numeric = "";
-		}
+	
+	addr = transport->localaddr;
+	addrlen = transport->localaddrlen;
+	
+	if (camel_getnameinfo (addr, addrlen, &name, NULL, NI_NUMERICHOST, NULL) != 0) {
+		name = g_strdup ("localhost.localdomain");
+	} else {
+		if (addr->sa_family == AF_INET6)
+			numeric = "IPv6:";
+		else
+			numeric = "";
 	}
 	
-	/* hiya server! how are you today? */
 	token = (transport->flags & CAMEL_SMTP_TRANSPORT_IS_ESMTP) ? "EHLO" : "HELO";
 	if (numeric)
 		cmdbuf = g_strdup_printf("%s [%s%s]\r\n", token, numeric, name);
Index: camel/providers/groupwise/camel-groupwise-summary.c
===================================================================
--- camel/providers/groupwise/camel-groupwise-summary.c	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-summary.c	(working copy)
@@ -34,8 +34,10 @@
 #include <stdlib.h>
 
 #include "camel-groupwise-summary.h"
+#include "camel-groupwise-folder.h"
 #include "camel-file-utils.h"
 #include <camel/camel-folder.h>
+#include <camel/camel-data-cache.h>
 
 #define CAMEL_GW_SUMMARY_VERSION (1)
 
@@ -154,16 +156,23 @@
 gw_summary_header_load (CamelFolderSummary *s, FILE *in)
 {
 	CamelGroupwiseSummary *ims = CAMEL_GROUPWISE_SUMMARY (s);
+	gint32 *ptr32 = s->filepos;
+	unsigned char *ptrchr;
+	gint len;
 
 	if (camel_groupwise_summary_parent->summary_header_load (s, in) == -1)
 		return -1 ;
 
-	if (camel_file_util_decode_fixed_int32(in, &ims->version) == -1
-			|| camel_file_util_decode_fixed_int32(in, &ims->validity) == -1)
-		return -1;
-	
-	if (camel_file_util_decode_string (in, &ims->time_string) == -1)
-		return -1;
+	ims->version = g_ntohl (*ptr32); ptr32++;
+	ims->validity = g_ntohl (*ptr32); ptr32++;
+	ptrchr = (unsigned char*)ptr32;
+
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (len) ims->time_string = (const char*)ptrchr;
+	ptrchr += len;
+		
+	s->filepos = ptrchr;
+
 	return 0 ;
 }
 
@@ -189,18 +198,16 @@
 	CamelMessageInfo *info ;
 	CamelGroupwiseMessageInfo *gw_info ;
 
-
 	info = camel_groupwise_summary_parent->message_info_load(s,in) ;
 	if (info) {
+		unsigned char *ptrchr = s->filepos;
 		gw_info = (CamelGroupwiseMessageInfo*) info ;
-		if (camel_file_util_decode_uint32 (in, &gw_info->server_flags) == -1)
-			goto error ;
+
+		ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &gw_info->server_flags, FALSE);
+		s->filepos = ptrchr;
 	}
 
 	return info ;
-error:
-	camel_message_info_free (info) ;
-	return NULL ;
 }
 
 
@@ -307,6 +314,7 @@
 
 	mi->info.size = camel_message_info_size(info);
 	mi->info.uid = g_strdup (uid);
+	mi->info.uid_needs_free = TRUE;
 
 	camel_folder_summary_add (summary, (CamelMessageInfo *)mi);
 
@@ -319,6 +327,39 @@
 
 	mi = camel_message_info_clone(info);
 	mi->info.uid = g_strdup(uid);
+	mi->info.uid_needs_free = TRUE;
+
 	camel_folder_summary_add (summary, (CamelMessageInfo *)mi);
 }
 
+void
+groupwise_summary_clear (CamelFolderSummary *summary, gboolean uncache)
+{
+	CamelFolderChangeInfo *changes;
+	CamelMessageInfo *info;
+	int i, count;
+	const char *uid;
+
+	changes = camel_folder_change_info_new ();
+	count = camel_folder_summary_count (summary);
+	for (i = 0; i < count; i++) {
+		if (!(info = camel_folder_summary_index (summary, i)))
+			continue;
+  		
+		uid = camel_message_info_uid (info);
+		camel_folder_change_info_remove_uid (changes, uid);
+		camel_folder_summary_remove_uid (summary, uid);
+		camel_message_info_free(info);
+	}
+
+	camel_folder_summary_clear (summary);
+	camel_folder_summary_save (summary);
+
+	if (uncache)
+		camel_data_cache_clear (((CamelGroupwiseFolder *) summary->folder)->cache, "cache", NULL);
+
+	if (camel_folder_change_info_changed (changes))
+		camel_object_trigger_event (summary->folder, "folder_changed", changes);
+	camel_folder_change_info_free (changes);
+}
+
Index: camel/providers/groupwise/camel-groupwise-utils.c
===================================================================
--- camel/providers/groupwise/camel-groupwise-utils.c	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-utils.c	(working copy)
@@ -21,24 +21,30 @@
 #include <config.h>
 
 #include <sys/types.h>
-#include <dirent.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <unistd.h>
+
 #include <glib.h>
+#include <glib/gstdio.h>
+
 #include <libsoup/soup-misc.h>
+
+#include "camel/camel-address.h"
+#include "camel/camel-mime-message.h"
+#include "camel/camel-multipart.h"
+#include "camel/camel-service.h"
+#include "camel/camel-stream-mem.h"
+#include "camel/camel-stream-filter.h"
+#include "camel/camel-mime-filter-charset.h"
+
 #include "camel-groupwise-utils.h"
 
-#include <camel/camel-service.h>
-#include <camel/camel-multipart.h>
-#include <camel/camel-stream-mem.h>
-#include <camel/camel-address.h>
-#include <camel/camel-mime-message.h>
-
 #define SUBFOLDER_DIR_NAME     "subfolders"
 #define SUBFOLDER_DIR_NAME_LEN 10
 #define RFC_822	"message/rfc822"
 
+static void do_multipart (EGwConnection *cnc, EGwItem *item, CamelMultipart *mp, GSList **attach_list);
 /**
  * e_path_to_physical:
  * @prefix: a prefix to prepend to the path, or %NULL
@@ -134,7 +140,7 @@
 find_folders_recursive (const char *physical_path, const char *path,
 			EPathFindFoldersCallback callback, gpointer data)
 {
-	DIR *dir;
+	GDir *dir;
 	char *subfolder_directory_path;
 	gboolean ok;
 
@@ -152,7 +158,7 @@
 	}
 
 	/* Now scan the subfolders and load them. */
-	dir = opendir (subfolder_directory_path);
+	dir = g_dir_open (subfolder_directory_path, 0, NULL);
 	if (dir == NULL) {
 		g_free (subfolder_directory_path);
 		return TRUE;
@@ -161,27 +167,23 @@
 	ok = TRUE;
 	while (ok) {
 		struct stat file_stat;
-		struct dirent *dirent;
+		const char *dirent;
 		char *file_path;
 		char *new_path;
 
-		dirent = readdir (dir);
+		dirent = g_dir_read_name (dir);
 		if (dirent == NULL)
 			break;
 
-		if (strcmp (dirent->d_name, ".") == 0 || strcmp (dirent->d_name, "..") == 0)
-			continue;
+		file_path = g_strdup_printf ("%s/%s", subfolder_directory_path, dirent);
 
-		file_path = g_strdup_printf ("%s/%s", subfolder_directory_path,
-					     dirent->d_name);
-
-		if (stat (file_path, &file_stat) < 0 ||
+		if (g_stat (file_path, &file_stat) < 0 ||
 		    ! S_ISDIR (file_stat.st_mode)) {
 			g_free (file_path);
 			continue;
 		}
 
-		new_path = g_strdup_printf ("%s/%s", path, dirent->d_name);
+		new_path = g_strdup_printf ("%s/%s", path, dirent);
 
 		ok = find_folders_recursive (file_path, new_path, callback, data);
 
@@ -189,7 +191,7 @@
 		g_free (new_path);
 	}
 
-	closedir (dir);
+	g_dir_close (dir);
 	g_free (subfolder_directory_path);
 
 	return ok;
@@ -235,7 +237,7 @@
 
 	/* Remove the directory itself */
 	physical_path = e_path_to_physical (prefix, vpath);
-	if (rmdir (physical_path) == -1) {
+	if (g_rmdir (physical_path) == -1) {
 		g_free (physical_path);
 		return -1;
 	}
@@ -256,12 +258,12 @@
 		return 0;
 	}
 
-	rmdir (physical_path);
+	g_rmdir (physical_path);
 	g_free (physical_path);
 	return 0;
 }
 
-GSList *
+static GSList *
 add_recipients(GSList *recipient_list, CamelAddress *recipients, int recipient_type)
 {
 	int total_add,i;
@@ -278,31 +280,31 @@
 			recipient->display_name = g_strdup (name);
 			recipient->type = recipient_type;
 			recipient->status = E_GW_ITEM_STAT_NONE;
-			recipient_list= g_slist_append (recipient_list, recipient);
+			recipient_list = g_slist_prepend (recipient_list, recipient);
 		}
 	}
 	return recipient_list;
 }
 
 static void 
-send_as_attachment (EGwConnection *cnc, EGwItem *item, CamelStreamMem *content, char *buffer, CamelContentType *type, CamelDataWrapper *dw, const char *filename, GSList **attach_list)
+send_as_attachment (EGwConnection *cnc, EGwItem *item, CamelStreamMem *content, CamelContentType *type, CamelDataWrapper *dw, const char *filename, const char *cid, GSList **attach_list)
 {
 	EGwItemLinkInfo *info = NULL;
 	EGwConnectionStatus status;
 	EGwItemAttachment *attachment;
 	EGwItem *temp_item;
-
-	int len;
-	len = content->buffer->len;
-
+	
 	attachment = g_new0 (EGwItemAttachment, 1);
-	attachment->contentType = g_strdup_printf ("%s/%s", type->type, type->subtype);
-
+	attachment->contentType = camel_content_type_simple (type);
+	
+	if (cid)
+		attachment->contentid = camel_header_contentid_decode (cid);
+	
 	if (filename) {
-		if (!strcmp (attachment->contentType, "application/pgp-signature")) {
+		if (camel_content_type_is (type, "application", "pgp-signature")) {
 			char *temp_str;
 			int temp_len;
-			temp_str = soup_base64_encode (buffer, len);
+			temp_str = soup_base64_encode (content->buffer->data, content->buffer->len);
 			temp_len = strlen (temp_str);
 			attachment->data = g_strdup (temp_str);
 			attachment->size = temp_len;
@@ -310,45 +312,59 @@
 			temp_str = NULL;
 			temp_len = 0;
 		} else {
-			attachment->data = g_malloc0 (content->buffer->len+1);
-			attachment->data = memcpy (attachment->data, 
-					content->buffer->data, 
-					content->buffer->len);
-			attachment->size = content->buffer->len;
+			attachment->data = soup_base64_encode(content->buffer->data, content->buffer->len);
+			attachment->size = strlen (attachment->data);
 		}
 	} else {
 		char *temp_str;
 		int temp_len;
-		temp_str = soup_base64_encode (buffer, len);
-		temp_len = strlen (temp_str);
-		attachment->data = g_strdup (temp_str);
-		attachment->size = temp_len;
-		g_free (temp_str);
-		temp_str = NULL;
-		temp_len = 0;
+		if (!strcmp (attachment->contentType, "multipart/digest")) {
+			/* FIXME? */
+		} else {
+			temp_str = soup_base64_encode (content->buffer->data, content->buffer->len);
+			temp_len = strlen (temp_str);
+			attachment->data = g_strdup (temp_str);
+			attachment->size = temp_len;
+			g_free (temp_str);
+			temp_str = NULL;
+			temp_len = 0;
+		}
 	}
 	
-	if (!strcmp (attachment->contentType, "text/html") || !(strcmp (attachment->contentType, "multipart/alternative"))) {
-		filename = "text.htm";
-		if (!(strcmp (attachment->contentType, "multipart/alternative"))) {
+	if (camel_content_type_is (type, "text", "html") || camel_content_type_is (type, "multipart", "alternative")) {
+		if (!filename)
+			filename = "text.htm";
+		if (camel_content_type_is (type, "multipart", "alternative")) {
+			/* FIXME: this just feels so wrong... */
 			g_free (attachment->contentType);
 			attachment->contentType = g_strdup ("text/html");
 		}
 	}
 
 	attachment->name = g_strdup (filename ? filename : "");
-	if (!g_ascii_strncasecmp (attachment->contentType, RFC_822, strlen (RFC_822))) {
-		char *temp_id = NULL, *id = NULL;
-		temp_id = (char *)camel_medium_get_header (CAMEL_MEDIUM ((CamelMimeMessage *)dw), "Message-Id");
-		int len = strlen (temp_id);
+	if (camel_content_type_is (type, "message", "rfc822")) {
+		const char *message_id;
+		char *msgid;
+		int len;
+		
+		message_id = camel_medium_get_header (CAMEL_MEDIUM (dw), "Message-Id");
+		/*
+		 * XXX: The following code piece is a screwed up way of doing stuff.
+		 * But we dont have much choice. Do not use 'camel_header_msgid_decode'
+		 * since it removes the container id portion from the id and which the
+		 * groupwise server needs.
+		 */
+		
+		len = strlen (message_id);
+		msgid = (char *)g_malloc0 (len-1);
+		msgid = memcpy(msgid, message_id+2, len-3);
 
-		id = (char *)g_malloc0 (len-1);
-		id = memcpy(id, temp_id+2, len-3);
-
-		status = e_gw_connection_forward_item (cnc, id, "message", TRUE, &temp_item);
-		if (status != E_GW_CONNECTION_STATUS_OK) 
+		status = e_gw_connection_forward_item (cnc, msgid, NULL, TRUE, &temp_item);
+		g_free (msgid);
+		
+		if (status != E_GW_CONNECTION_STATUS_OK) {
 			g_warning ("Could not send a forwardRequest...continuing without!!\n");
-		else {
+		} else {
 			GSList *attach_list = e_gw_item_get_attach_id_list (temp_item);
 			EGwItemAttachment *temp_attach = (EGwItemAttachment *)attach_list->data;
 			attachment->id = g_strdup (temp_attach->id);
@@ -363,41 +379,36 @@
 			info = e_gw_item_get_link_info (temp_item);
 			e_gw_item_set_link_info (item, info);
 		}
-		g_free (id);
 	}
 
 	*attach_list = g_slist_append (*attach_list, attachment);
 }
 
 EGwItem *
-camel_groupwise_util_item_from_message (EGwConnection *cnc, CamelMimeMessage *message, CamelAddress *from, CamelAddress *recipients)
+camel_groupwise_util_item_from_message (EGwConnection *cnc, CamelMimeMessage *message, CamelAddress *from)
 {
 	EGwItem *item;
 	EGwItemOrganizer *org = g_new0 (EGwItemOrganizer, 1);
-
 	const char *display_name = NULL, *email = NULL;
 	char *send_options = NULL;
 	CamelMultipart *mp;
-	GSList *recipient_list = NULL, *attach_list = NULL; 
-	int i;
+	GSList *recipient_list = NULL, *attach_list = NULL;
+	CamelAddress *recipients;
 
 	/*Egroupwise item*/
 	item = e_gw_item_new_empty ();
 	
 	/*populate recipient list*/
-	camel_address_remove(recipients,-1);
-	camel_address_cat (recipients, CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_TO)));
+	recipients = CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_TO));
 	recipient_list=add_recipients(recipient_list,recipients,E_GW_ITEM_RECIPIENT_TO);
-
-	camel_address_remove(recipients,-1);
-	camel_address_cat (recipients, CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_CC)));
+	
+	recipients = CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_CC));
 	recipient_list=add_recipients(recipient_list,recipients,E_GW_ITEM_RECIPIENT_CC);
 	
-	camel_address_remove(recipients,-1);
-	camel_address_cat (recipients, CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_BCC)));
+	recipients = CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_BCC));
 	recipient_list=add_recipients(recipient_list,recipients,E_GW_ITEM_RECIPIENT_BC);
-
-
+	recipient_list = g_slist_reverse (recipient_list);
+	
 	/** Get the mime parts from CamelMimemessge **/
 	mp = (CamelMultipart *)camel_medium_get_content_object (CAMEL_MEDIUM (message));
 	if(!mp) {
@@ -408,92 +419,49 @@
 
 	if (CAMEL_IS_MULTIPART (mp)) {
 		/*contains multiple parts*/
-		guint part_count;
-		
-		part_count = camel_multipart_get_number (mp);
-		for ( i=0 ; i<part_count ; i++) {
-			CamelContentType *type;
-			CamelMimePart *part;
-			CamelStreamMem *content = (CamelStreamMem *)camel_stream_mem_new ();
-			CamelDataWrapper *dw = camel_data_wrapper_new ();
-			const char *disposition, *filename;
-			char *buffer = NULL;
-			char *mime_type = NULL;
-			gboolean is_alternative = FALSE;
-			/*
-			 * XXX:
-			 * Assuming the first part always is the actual message
-			 * and an attachment otherwise.....
-			 */
-			part = camel_multipart_get_part (mp, i);
-			type = camel_mime_part_get_content_type(part);
-			dw = camel_medium_get_content_object (CAMEL_MEDIUM (part));
-			if (type->subtype && !strcmp (type->subtype, "alternative")) {
-				CamelMimePart *temp_part;
-				CamelStreamMem *temp_content = (CamelStreamMem *)camel_stream_mem_new ();
-				temp_part = camel_multipart_get_part ((CamelMultipart *)dw, 1);
-				CamelDataWrapper *temp_dw = camel_data_wrapper_new ();
-				if (temp_part) {
-					is_alternative = TRUE;
-					temp_dw = camel_medium_get_content_object (CAMEL_MEDIUM (temp_part));
-					camel_data_wrapper_write_to_stream(temp_dw, (CamelStream *)temp_content);
-					buffer = g_malloc0 (temp_content->buffer->len+1);
-					buffer = memcpy (buffer, temp_content->buffer->data, temp_content->buffer->len);
-					filename = camel_mime_part_get_filename (temp_part);
-					disposition = camel_mime_part_get_disposition (temp_part);
-					mime_type = camel_data_wrapper_get_mime_type (temp_dw);
-					send_as_attachment (cnc, item, temp_content, buffer, type, temp_dw, filename, &attach_list);
-					g_free (buffer);
-					g_free (mime_type);
-				}
-				camel_object_unref (temp_content);
-				camel_object_unref (temp_dw);
-				camel_object_unref (dw);
-				continue;
-			} 
-			
-			camel_data_wrapper_write_to_stream(dw, (CamelStream *)content);
-			buffer = g_malloc0 (content->buffer->len+1);
-			buffer = memcpy (buffer, content->buffer->data, content->buffer->len);
-			filename = camel_mime_part_get_filename (part);
-			disposition = camel_mime_part_get_disposition (part);
-			mime_type = camel_data_wrapper_get_mime_type (dw);
-
-			if (i == 0 && !strcmp (mime_type, "text/plain") ) {
-				e_gw_item_set_content_type (item, mime_type);
-				e_gw_item_set_message (item, buffer);
-			} else 
-				send_as_attachment (cnc, item, content, buffer, type, dw, filename, &attach_list);
-
-			g_free (buffer);
-			g_free (mime_type);
-			camel_object_unref (content);
-			camel_object_unref (dw);
-		} /*end of for*/
-		
+		do_multipart (cnc, item, mp, &attach_list);
 	} else {
 		/*only message*/
 		CamelStreamMem *content = (CamelStreamMem *)camel_stream_mem_new ();
-		CamelDataWrapper *dw = camel_data_wrapper_new ();
+		CamelDataWrapper *dw = NULL;
 		CamelContentType *type;
-		char *buffer = NULL;
-		char *content_type = NULL;
-			
+		
 		dw = camel_medium_get_content_object (CAMEL_MEDIUM (message));
 		type = camel_mime_part_get_content_type((CamelMimePart *)message);
-		content_type = g_strdup_printf ("%s/%s", type->type, type->subtype);
-		camel_data_wrapper_write_to_stream(dw, (CamelStream *)content);
-		buffer = g_malloc0 (content->buffer->len+1);
-		buffer = memcpy (buffer, content->buffer->data, content->buffer->len);
 		
-		if (!strcmp(content_type, "text/plain")) {
-			e_gw_item_set_content_type (item, content_type);				
-			e_gw_item_set_message (item, buffer);
-		} else
-			send_as_attachment (cnc, item, content, buffer, type, dw, NULL, &attach_list);	
-
-		g_free (buffer);
-		g_free (content_type);
+		if (camel_content_type_is (type, "text", "plain")) {
+			CamelStream *filtered_stream;
+			CamelMimeFilter *filter;
+			const char *charset;
+			char *content_type;
+			
+			content_type = camel_content_type_simple (type);
+			e_gw_item_set_content_type (item, content_type);
+			g_free (content_type);
+			
+			charset = camel_content_type_param (type, "charset");
+			if (charset && g_ascii_strcasecmp (charset, "US-ASCII") && g_ascii_strcasecmp (charset, "UTF-8")) {
+				filter = camel_mime_filter_charset_new_convert (charset, "UTF-8");
+				filtered_stream = camel_stream_filter_new_with_stream ((CamelStream *) content);
+				camel_stream_filter_add ((CamelStreamFilter *) filtered_stream, filter);
+				camel_object_unref (filter);
+			} else {
+				/* US-ASCII or UTF-8 */
+				filtered_stream = (CamelStream *) content;
+				camel_object_ref (content);
+			}
+			
+			camel_data_wrapper_decode_to_stream (dw, filtered_stream);
+			camel_stream_flush (filtered_stream);
+			camel_object_unref (filtered_stream);
+			
+			camel_stream_write ((CamelStream *) content, "", 1);
+			e_gw_item_set_message (item, (const char *)content->buffer->data);
+		} else {
+			camel_data_wrapper_decode_to_stream (dw, (CamelStream *) content);
+			send_as_attachment (cnc, item, content, type, dw, NULL, NULL, &attach_list);	
+		}
+		
 		camel_object_unref (content);
 	}
 	/*Populate EGwItem*/
@@ -602,3 +570,108 @@
 		return g_strdup_printf ("%s%c%s", prefix, '/', suffix);
 }
 
+void
+strip_lt_gt (char **string, int s_offset, int e_offset)
+{
+	char *temp = NULL;
+	int len;
+	
+	temp = g_strdup (*string);
+	len = strlen (*string);
+
+	*string = (char *)g_malloc0 (len-1);
+	*string = memcpy(*string, temp+s_offset, len-e_offset);
+	g_free (temp);
+}
+
+static void
+do_multipart (EGwConnection *cnc, EGwItem *item, CamelMultipart *mp, GSList **attach_list)
+{
+	/*contains multiple parts*/
+	guint part_count;
+	int i;
+
+	part_count = camel_multipart_get_number (mp);
+	for ( i=0 ; i<part_count ; i++) {
+		CamelContentType *type;
+		CamelMimePart *part;
+		CamelStreamMem *content = (CamelStreamMem *)camel_stream_mem_new ();
+		CamelDataWrapper *dw = NULL;
+		const char *disposition, *filename;
+		const char *content_id = NULL;
+		gboolean is_alternative = FALSE;
+		/*
+		 * XXX:
+		 * Assuming the first part always is the actual message
+		 * and an attachment otherwise.....
+		 */
+		part = camel_multipart_get_part (mp, i);
+		type = camel_mime_part_get_content_type(part);
+		dw = camel_medium_get_content_object (CAMEL_MEDIUM (part));
+		
+		if (CAMEL_IS_MULTIPART (dw)) {
+			do_multipart (cnc, item, (CamelMultipart *) camel_medium_get_content_object ((CamelMedium *) part), attach_list);
+			continue;
+		}
+		
+		if (type->subtype && !strcmp (type->subtype, "alternative")) {
+			/* eh... I don't think this code will ever get hit? */
+			CamelMimePart *temp_part;
+			const char *cid = NULL;
+			CamelStreamMem *temp_content = (CamelStreamMem *)camel_stream_mem_new ();
+			temp_part = camel_multipart_get_part ((CamelMultipart *)dw, 1);
+			CamelDataWrapper *temp_dw = NULL;
+			
+			if (temp_part) {
+				is_alternative = TRUE;
+				temp_dw = camel_medium_get_content_object (CAMEL_MEDIUM (temp_part));
+				camel_data_wrapper_write_to_stream(temp_dw, (CamelStream *)temp_content);
+				filename = camel_mime_part_get_filename (temp_part);
+				disposition = camel_mime_part_get_disposition (temp_part);
+				cid = camel_mime_part_get_content_id (temp_part);
+				send_as_attachment (cnc, item, temp_content, type, temp_dw, filename, cid, attach_list);
+			}
+			camel_object_unref (temp_content);
+			continue;
+		} 
+		
+		if (i == 0 && camel_content_type_is (type, "text", "plain")) {
+			CamelStream *filtered_stream;
+			CamelMimeFilter *filter;
+			const char *charset;
+			char *content_type;
+			
+			content_type = camel_content_type_simple (type);
+			e_gw_item_set_content_type (item, content_type);
+			g_free (content_type);
+			
+			charset = camel_content_type_param (type, "charset");
+			if (charset && g_ascii_strcasecmp (charset, "US-ASCII") && g_ascii_strcasecmp (charset, "UTF-8")) {
+				filter = camel_mime_filter_charset_new_convert (charset, "UTF-8");
+				filtered_stream = camel_stream_filter_new_with_stream ((CamelStream *) content);
+				camel_stream_filter_add ((CamelStreamFilter *) filtered_stream, filter);
+				camel_object_unref (filter);
+			} else {
+				/* US-ASCII or UTF-8 */
+				filtered_stream = (CamelStream *) content;
+				camel_object_ref (content);
+			}
+			
+			camel_data_wrapper_decode_to_stream (dw, filtered_stream);
+			camel_stream_flush (filtered_stream);
+			camel_object_unref (filtered_stream);
+			
+			camel_stream_write ((CamelStream *) content, "", 1);
+			e_gw_item_set_message (item, (const char *)content->buffer->data);
+		} else {
+			filename = camel_mime_part_get_filename (part);
+			disposition = camel_mime_part_get_disposition (part);
+			content_id = camel_mime_part_get_content_id (part);
+			
+			camel_data_wrapper_decode_to_stream (dw, (CamelStream *) content);
+			send_as_attachment (cnc, item, content, type, dw, filename, content_id, attach_list);
+		}
+		
+		camel_object_unref (content);
+	} /*end of for*/
+}
Index: camel/providers/groupwise/camel-groupwise-store.h
===================================================================
--- camel/providers/groupwise/camel-groupwise-store.h	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-store.h	(working copy)
@@ -61,7 +61,7 @@
 	/* the parameters field is not to be included not. probably for 2.6*/
 	/*guint32 parameters;*/
 	time_t refresh_stamp;
-	guint list_loaded:1;
+	guint list_loaded;
 };
 
 
@@ -82,6 +82,7 @@
 const char *groupwise_base_url_lookup (CamelGroupwiseStorePrivate *priv);
 CamelFolderInfo * create_junk_folder (CamelStore *store);
 gboolean camel_groupwise_store_connected (CamelGroupwiseStore *store, CamelException *ex);
+void gw_store_reload_folder (CamelGroupwiseStore *store, CamelFolder *folder, guint32 flags, CamelException *ex);
 
 #ifdef __cplusplus
 }
Index: camel/providers/groupwise/camel-groupwise-summary.h
===================================================================
--- camel/providers/groupwise/camel-groupwise-summary.h	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-summary.h	(working copy)
@@ -75,4 +75,5 @@
 void camel_gw_summary_add_offline (CamelFolderSummary *summary, const char *uid, CamelMimeMessage *messgae, const CamelMessageInfo *info) ;
 
 void camel_gw_summary_add_offline_uncached (CamelFolderSummary *summary, const char *uid, const CamelMessageInfo *info) ;
+void groupwise_summary_clear (CamelFolderSummary *summary, gboolean uncache);
 #endif /*_CAMEL_GW_SUMMARY_H*/
Index: camel/providers/groupwise/camel-groupwise-utils.h
===================================================================
--- camel/providers/groupwise/camel-groupwise-utils.h	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-utils.h	(working copy)
@@ -71,8 +71,9 @@
 int      e_path_rmdir        (const char *prefix, const char *vpath);
 
 
-EGwItem *camel_groupwise_util_item_from_message (EGwConnection *cnc, CamelMimeMessage *message, CamelAddress *from, CamelAddress *recipients);
+EGwItem *camel_groupwise_util_item_from_message (EGwConnection *cnc, CamelMimeMessage *message, CamelAddress *from);
+
 void do_flags_diff (flags_diff_t *diff, guint32 old, guint32 _new);
-GSList *add_recipients(GSList *recipient_list, CamelAddress *recipients, int recipient_type);
 char *gw_concat ( const char *prefix, const char *suffix);
+void strip_lt_gt (char **string, int s_offset, int e_offset);
 #endif
Index: camel/providers/groupwise/ChangeLog
===================================================================
--- camel/providers/groupwise/ChangeLog	(revision 444)
+++ camel/providers/groupwise/ChangeLog	(working copy)
@@ -1,19 +1,417 @@
+2006-07-06  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-transport.c: (groupwise_send_to):
+	check if you have a valid transport. For those wierd times
+	when you have everything screwed up
+
+2006-07-05  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-utils.c: (camel_groupwise_util_item_from_message):
+	fix compiler warnings
+
+2006-07-05  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** Fixes bug #165728 on novell bugzilla
+	* camel-groupwise-store.[ch]:
+	(groupwise_store_construct): initialize list loaded to 3
+	(groupwise_get_folder_info): update only once from the server
+	and from then on - just use the cache.
+
+2006-07-05  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** Fixes bug #165922 on novell bugzilla.
+	* camel-groupwise-folder.[ch]: 
+	(groupwise_folder_item_to_msg): use Mime.822 whenever it is available
+
+
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-groupwise-folder.c: 
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
+2006-06-13  Andre Klapper <a9016009@gmx.de>
+
+	* camel-groupwise-store.c:
+	changing "couldn't", "can't" and "didn't" to proper
+	English. Fixes bug #342160.
+
+2006-06-13  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	Fixes bug #167517 on bnc
+
+	* camel-groupwise-utils.c: (send_as_attachment):
+	revert a part of fejjs patch. We need the message id
+	with the container in it. We cant use the camel_header_msgid_decode
+	method since it would normalise anything after ':'. 
+	Henceforth the forwardrequest would get the complete id of the message
+	and the link info is sent correctly.
+
+	* camel-groupwise-store.c:
+	* camel-groupwise-folder.c: 
+	(gw_update_cache):
+	(gw_update_summary): use the hasAttachments element to
+	check if a mail has attachments or not.
+	
+2006-06-12  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	Fixes bug #166265 on bnc
+	
+	* camel-groupwise-folder.c: call purgeRequest when
+	deleting on Trash folder
+
+2006-06-09  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c:
+	Fixes the problem of email id appearing twice
+	
+2006-06-09  Chris Heath  <chris@heathens.co.nz>
+
+	* camel-groupwise-journal.c (update_cache): Fix memory leak.
+	Fixes bug #335423.
+
+2006-06-06  Jeffrey Stedfast  <fejj@novell.com>
+
+	Fixes for Novell bug #173454
+
+	* camel-groupwise-utils.c (add_recipients): Changed to be an
+	internal function.
+	(send_as_attachment): No longer takes 'buffer' nor 'encoding'
+	arguments. Changed the code to use the camel content-id/message-id
+	parsers rather than home-brew blocks of code to do it. Instead of
+	strcmp'ing mime types, use the camel_content_type_is() function
+	which simplifies things a bit.
+	(camel_groupwise_util_item_from_message): No longer takes a
+	recipients list argument as this function extracted that info from
+	the CamelMimeMessage object anyway. Do charset conversion for
+	text/plain parts.
+
+	* camel-groupwise-folder.c (groupwise_append_message): Don't pass
+	to/cc/bcc recpients to camel_groupwise_util_item_from_message() as
+	it no longer takes those arguments.
+
+	* camel-groupwise-transport.c (groupwise_send_to): Same.
+
+2006-05-23  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c: (groupwise_refresh_folder)
+	Uses readCursor on trash so that we get all items
+
+2006-05-17  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c:
+	Notify the user if the Trash is overflowing
+
+2006-04-28  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c:
+        Initialize a pointer to NULL so that we wont
+	have any dangling reference to be freed
+
+2006-04-24  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c: 
+	Removes multiple items by a single call instead
+	of deleting one-by-one.
+
+2006-04-22  Sankar P  <psankar@novell.com>
+ 
+ 	* camel-groupwise-store.c: (convert_to_folder_info):
+ 	No need to get the unread count for Sent Items folder. 
+ 	All will be read by default.
+ 	
+2006-04-20  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 167640 on bnc
+	* camel-groupwise-store.c: Add space at the end of a string.
+
+2006-04-20  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-summary.c : (groupwise_summary_clear):
+	Removes from summary based on uid instead of info.
+	This will avoid double-free crash of info.
+	
+2006-04-18  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c: (groupwise_sync):
+	Corrected an erroneous commit.
+	
+2006-04-17  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c: (groupwise_refresh_folder)
+	Sync up the flags before updating the changes.
+
+2006-04-06 Parthasarathi Susarla  <sparthasarathi@novell.com>
+
+	* camel-groupwise-folder.c : (gw_update_cache)
+	Store the flags to the summary so that the markRead doesnot 
+	get called every time
+	
+2006-04-06  Parthasarathi  Susarla <sparthasarathi@novell.com>
+
+	* camel-groupwise-store.c :
+	Sync up changes before gettting the folder-list
+
+2006-04-03  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c: (update_junk_list)
+	(gw_update_summary)(gw_update_cache):
+	Stores the name as well as the email address so
+	that the (un)junk operations will work.
+	
+2006-04-03  Sankar P  <psankar@novell.com>
+	
+	* camel-groupwise-folder.c: (groupwise_refresh_folder):
+	Added code for getting deltas for Proxy accounts, 
+	instead of downloading everything everytime.
+		
+2006-03-24  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c: (groupwise_item_folder_to_msg):
+	Set content type, so that it does not crash
+	
+2006-03-23  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c:
+	(groupwise_refresh_folder):
+	Sync up externally deleted items only on arrival of New items 
+
+2006-03-23  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c: 
+	(groupwise_sync): removed a double free and a crash
+	(gw_update_cache): Do not clone messageinfo. jus work on
+	the original message info
+	* camel-groupwise-store.c: (groupwise_folders_sync):
+	sync up the current folder whenever the folder list is 
+	being refreshed.
+	
+2006-03-21  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-utils.c: (do_multipart):
+	Remove unrefs which are actually not needed for a Datawrapper got
+	from camel_medium_get_content_object()
+
+2006-03-20  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c:(gw_udpate_cache):
+	Sync up changes made in the server with the local data, mainly
+	the read and unread data.
+
+2006-03-17  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c:
+	(groupwise_folder_item_to_msg): If the message-body/attachment 
+	is larger than 1MB, have to get it in chunks(streaming).
+
+2006-03-15  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c:
+	(gw_update_cache) (update_update)
+	(groupwise_refresh_folder) (gw_update_all_items):
+	- Use read_cursor ALL for identifying new messages and 
+	avoids getQM for getting new items. 
+	- Altered the code which keeps Evolution stay in sync,
+	with the rest of the clients by deleting 
+	externally deleted items 
+	
+2006-03-13  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* Fixes bug 137357 & 156823
+	
+	* camel-groupwise-store.c:
+	(groupwise_auth_loop): 
+	(groupwise_connect): 
+	Ignore Offline status when service status is
+	Disconnected.
+
+2006-03-13  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* Fixes bug 152355
+
+	* camel-groupwise-folder.c: 
+	(groupwise_refresh_info): If the summary is corrupt, or is not
+	present, rebuild the summary again.
+	* camel-groupwise-store.[ch]:
+	(gw_store_reload_folder): This method rebuilds the folder summary
+	it the summary is somehow corrupted.
+
+2006-03-11  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-folder.c:
+	Changed the way in which UIDs are handled. Reduces a lot of 
+	coslty String and List operations. Should make GroupWise provider 
+	run fast and shutdown faster. Reduces CPU and memory usage too.
+	
+2006-03-11  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c: (groupwise_refresh_info):
+	reload folder if there is no content in it.
+
+	* camel-groupwise-store.c: 
+	(groupwise_connect): Dont check for disconnected state while 
+	connecting.
+	(groupwise_get_folder): set the correct total count so that 
+	we get the actual progress on each folder when downloading 
+	mail headers the first time.	
+
+2006-03-09  parthasarathi susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-store.c: 
+	(camel_groupwise_store_connected):
+	(check_for_connection):
+	check if the status is online before trying to connect
+	to server. 
+
+	* camel-groupwise-folder.c: (gw_update_cache):
+	assert lock, before continuing further.
+
+2006-01-31  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 329214
+	
+	* camel-groupwise-utils.c:
+	(send_as_attachment): use text.htm for text files only
+	if there is no file name.
+
+2006-01-24  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c: 
+	(groupwise_sync):
+	(groupwise_transfer_messages_to):
+	(groupwise_append_message):
+	lookup for CNC only if we are connected.
+	
+	* camel-groupwise-store.c:
+	(groupwise_auth_loop):
+	(groupwise_connect):
+	lookup for CNC only if we are connected
+	(groupwise_disconnect_cleanup): cleanup the priv
+	structure whenever we disconnect
+
+2006-01-23  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c:
+	(update_junk_list): do not contact the server each time we 
+	add junk, just once, while marking not junk.
+	(groupwise_transfer_messages_to): fix a crash, have to use
+	destination->summary instead of destination. 
+	
+	** See bug 327376
+	* camel-groupwise-transport.c: (groupwise_send_to):
+	set the link info to NULL. Fixes a crash.
+	* camel-groupwise-utils.c: (send_as_attachment):
+	Based on encoding, check if we are sending non base64 data
+	to the server, if we are, do a base64 encode first.
+
+2006-01-19  Andre Klapper <a9016009@gmx.de>
+
+	* camel-groupwise-transport.c: fixed a typo and improved an
+	error message. Fixes bug 325657.
+
+2006-01-12  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c:
+	(groupwise_populate_details_from_item):
+	(gw_update_cache):
+	(gw_update_summary):
+	put the created date, in case of missing delivered date
+
+	** See bug 314841
+	(gw_update_summary): dont bold trash folder with number of
+	messsages
+
+	* camel-groupwise-storec.:(groupwise_get_folder):
+	request for created date too
+
+	** See bug 323570
+	
+	* camel-groupwise-utils.c: 
+	(do_multipart): a part can further be a multipart so have a
+	recurssive function
+
+2006-01-04  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c:
+	(groupwise_sync_summary): saves the summary to the disk
+	(groupwise_sync): remove a lot of junk code
+	(groupwise_folder_item_to_msg): fixes the html with embedded
+	images issue. See bug 320898
+	* camel-groupwise-store.c: remove printfs everywhere
+	* camel-groupwise-utils.c: 
+	(strip_lt_gt): strips the < and > characters based on the
+	given offsets
+
+
 2005-12-14  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 317794
+	* camel-groupwise-store-summary.c:
+	(camel_groupwise_store_summary_full_to_path):
+	(camel_groupwise_store_summary_path_to_full):
+	Do not convert folder names here, there are already converted
 
-       ** See bug 317794
-       * camel-groupwise-store-summary.c:
-       (camel_groupwise_store_summary_full_to_path):
-       (camel_groupwise_store_summary_path_to_full):
-       Do not convert folder names here, there are already converted
+2005-12-13  Tor Lillqvist  <tml@novell.com>
 
+	* camel-groupwise-store.c
+	* camel-groupwise-utils.c: Use gstdio wrappers. Use GDir instead
+	of dirent API.
 
+2005-12-09  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 321830
+	
+	* camel-groupwise-folder.c: (gw_update_cache): Do not skip 
+	caching sent items, they dont get displayed otherwise.
+	
+2005-11-09  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-groupwise-folder.c:
+	(groupwise_sync): initialise mi and free some stuff
+	(groupwise_expunge): clear summary and cache and emptying trash
+	Fixes bug **320095
+	
+	* camel-groupwise-store.c:
+	(groupwise_connect): do not attempt to connect when the service is 
+	disconnected and the network is unavailable.
+	(groupwise_disconnect): check if priv is indeed available. Prevents
+	a violation
+	(groupwise_get_trash): fix up the state of the folder. Fixes the bug
+	**320095
+
+	* camel-groupwise-summary.[ch]:
+	(groupwise_summary_clear): clears the summary and cache of a groupwise
+	folder.
+
+2005-11-09  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-transport.c (groupwise_send_to):
+	Changed the string so as to be consistent with Win32 client error messages.
+	
+2005-11-09  Shreyas Srinivasan <sshreyas@novell.com>
+
+	* camel-groupwise-store.c (groupwise_connect): Uncomment
+	code which previously fixed offlining code.
+	
+2005-11-09  Sankar P  <psankar@novell.com>
+
+	* camel-groupwise-transport.c (groupwise_send_to):
+	Added code to handle the Quota errors.
+	Fixes #314476
+	
 2005-11-07  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
 	** See bug #320736
 	* camel-groupwise-folder.c: (groupwise_folder_item_to_msg):
-	Check if the attachment is indeed a valid string. Prevents
-	a crash.
+	Check if the attachment buffer is indeed valid. Prevents a possible
+	segment violation.
 
+2005-10-21  Shreyas Srinivasan <sshreyas@novell.com>
+
+	* camel-groupwise-store.c:(groupwise_connect): Connect if store->state
+	is CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL and not if 
+	CAMEL_OFFLINE_STORE_NETWORK_AVAIL
+
 2005-10-19 Vivek Jain <jvivek@novell.com>
 	
 	**See bug #319045
@@ -25,11 +423,7 @@
 	
 	* camel-groupwise-folder.c: (transfer_messages_to):
 	set the flags correctly for GW_JUNK
-
-2005-10-03  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
-	* reverting commits made for JUNK folder type
-
 2005-10-03  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
 	** See bug 314751
@@ -42,7 +436,7 @@
 2005-09-30 Vivek Jain <jvivek@novell.com>
 	
 	* camel-groupwise-store.c: (get_folder_info)
-	remove env chceck GROUPWISE_SHARED_FOLDER
+	remove env check GROUPWISE_SHARED_FOLDER
 	to enable shared folder functionality
 
 2005-09-28  Sankar P  <psankar@novell.com>
@@ -51,13 +445,21 @@
 	Added peek to the view so that the unread status of mails doesnt get 
 	changed during a proxy access.
 	Fixes #309993
-
+	
+2005-09-26  Veerapuram Varadhan <vvaradhan@novell.com>
+	* camel-groupwise-folder.c: (camel_gw_folder_new)
+	Memory leak fixes.
+	
+	* camel-groupwise-store.c: (groupwise_store_construct)
+	  (camel_groupwise_store_finalize): Memory leak fixes, use
+	  g_hash_table_new_full instead of g_hash_table_new.
+	
 2005-09-26 Vivek Jain <jvivek@novell.com>
-
+	
 	* camel-groupwise-folder.c :(update_junk_list)
 	initialize variables email and from.
 	**Fixes #314942
-			
+
 2005-09-18  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
 	* camel-groupwise-folder.c: (groupwise_refresh_info):
Index: camel/providers/groupwise/camel-groupwise-journal.c
===================================================================
--- camel/providers/groupwise/camel-groupwise-journal.c	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-journal.c	(working copy)
@@ -372,6 +372,7 @@
 	camel_object_unref (cache);
 	
 	info = camel_folder_summary_info_new_from_message (folder->summary, message);
+	g_free(info->uid);
 	info->uid = g_strdup (uid);
 	
 	gw_message_info_dup_to ((CamelMessageInfoBase *) info, (CamelMessageInfoBase *) mi);
Index: camel/providers/groupwise/camel-groupwise-folder.c
===================================================================
--- camel/providers/groupwise/camel-groupwise-folder.c	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-folder.c	(working copy)
@@ -49,6 +49,8 @@
 #include <e-gw-connection.h>
 #include <e-gw-item.h>
 
+#include <libsoup/soup-misc.h>
+
 #include <string.h>
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -58,6 +60,8 @@
 #define REMOVE_JUNK_ENTRY -1
 #define JUNK_FOLDER "Junk Mail"
 #define READ_CURSOR_MAX_IDS 500
+#define MAX_ATTACHMENT_SIZE 1*1024*1024   /*In bytes*/
+#define GROUPWISE_BULK_DELETE_LIMIT 100
 
 static CamelOfflineFolderClass *parent_class = NULL;
 
@@ -71,30 +75,22 @@
 };
 
 /*prototypes*/
-static void groupwise_transfer_messages_to (CamelFolder *source, 
-					    GPtrArray *uids, 
-					    CamelFolder *destination, 
-					    GPtrArray **transferred_uids, 
-					    gboolean delete_originals, 
-					    CamelException *ex);
-
+static void groupwise_transfer_messages_to (CamelFolder *source, GPtrArray *uids, CamelFolder *destination, GPtrArray **transferred_uids, gboolean delete_originals, CamelException *ex);
 static int gw_getv (CamelObject *object, CamelException *ex, CamelArgGetV *args);
 void convert_to_calendar (EGwItem *item, char **str, int *len);
 static void convert_to_task (EGwItem *item, char **str, int *len);
-static void gw_update_all_items ( CamelFolder *folder, GSList *item_list, CamelException *ex);
+static void gw_update_all_items ( CamelFolder *folder, GList *item_list, CamelException *ex);
 static void groupwise_populate_details_from_item (CamelMimeMessage *msg, EGwItem *item);
 static void groupwise_populate_msg_body_from_item (EGwConnection *cnc, CamelMultipart *multipart, EGwItem *item, char *body);
 static void groupwise_msg_set_recipient_list (CamelMimeMessage *msg, EGwItem *item);
-static void gw_update_cache ( CamelFolder *folder, GList *item_list,CamelException *ex);
-static CamelMimeMessage *groupwise_folder_item_to_msg ( CamelFolder *folder, EGwItem *item,	CamelException *ex );
+static void gw_update_cache ( CamelFolder *folder, GList *item_list, CamelException *ex, gboolean uid_flag);
+static CamelMimeMessage *groupwise_folder_item_to_msg ( CamelFolder *folder, EGwItem *item, CamelException *ex );
 
 
-#define d(x) x
+#define d(x) 
 
 static CamelMimeMessage *
-groupwise_folder_get_message( CamelFolder *folder,
-		const char *uid,
-		CamelException *ex )
+groupwise_folder_get_message( CamelFolder *folder, const char *uid, CamelException *ex )
 {
 	CamelMimeMessage *msg = NULL;
 	CamelGroupwiseFolder *gw_folder = CAMEL_GROUPWISE_FOLDER(folder);
@@ -107,7 +103,7 @@
 	EGwItem *item;
 	CamelStream *stream, *cache_stream;
 	int errno;
-	
+
 	/* see if it is there in cache */
 
 	mi = (CamelGroupwiseMessageInfo *) camel_folder_summary_uid (folder->summary, uid);
@@ -125,7 +121,7 @@
 		camel_stream_reset (stream);
 		if (camel_data_wrapper_construct_from_stream ((CamelDataWrapper *) msg, stream) == -1) {
 			if (errno == EINTR) {
-				camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+				camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 				camel_object_unref (msg);
 				camel_object_unref (cache_stream);
 				camel_object_unref (stream);
@@ -146,14 +142,14 @@
 		camel_message_info_free (&mi->info);
 		return msg;
 	}
-	
+
 	if (((CamelOfflineStore *) gw_store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL) {
 		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 				_("This message is not available in offline mode."));
 		camel_message_info_free (&mi->info);
 		return NULL;
 	}
-	
+
 	/* Check if we are really offline */
 	if (!camel_groupwise_store_connected (gw_store, ex)) {
 		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
@@ -178,7 +174,7 @@
 		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Could not get message"));
 		g_free (container_id);
 		camel_message_info_free (&mi->info);
-		
+
 		return NULL;
 	}
 
@@ -198,7 +194,7 @@
 	}
 
 	CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
-	
+
 end:
 	camel_message_info_free (&mi->info);
 	g_free (container_id);
@@ -214,16 +210,23 @@
 	temp_str = (char *)e_gw_item_get_subject(item);
 	if(temp_str)
 		camel_mime_message_set_subject (msg, temp_str);
-	dtstring = e_gw_item_get_creation_date (item);
+	dtstring = e_gw_item_get_delivered_date (item);
 	if(dtstring) {
 		int offset = 0;
 		time_t time = e_gw_connection_get_date_from_string (dtstring);
 		time_t actual_time = camel_header_decode_date (ctime(&time), &offset);
 		camel_mime_message_set_date (msg, actual_time, offset);
+	} else {
+		time_t time;
+		time_t actual_time;
+		int offset = 0;
+		dtstring = e_gw_item_get_creation_date (item);
+		time = e_gw_connection_get_date_from_string (dtstring);
+		actual_time = camel_header_decode_date (ctime(&time), NULL);
+		camel_mime_message_set_date (msg, actual_time, offset);
 	}
 }
 
-
 static void
 groupwise_populate_msg_body_from_item (EGwConnection *cnc, CamelMultipart *multipart, EGwItem *item, char *body)
 {
@@ -267,19 +270,19 @@
 		case E_GW_ITEM_TYPE_NOTIFICATION:
 		case E_GW_ITEM_TYPE_MAIL:
 		case E_GW_ITEM_TYPE_NOTE:
-				if (body) 
-					camel_mime_part_set_content(part, body, strlen(body), "text/html");
-				 else if (temp_body)
-					camel_mime_part_set_content(part, temp_body, strlen(temp_body), e_gw_item_get_msg_content_type (item));
-				else
-					camel_mime_part_set_content(part, " ", strlen(" "), "text/html");
+			if (body) 
+				camel_mime_part_set_content(part, body, strlen(body), "text/html");
+			else if (temp_body)
+				camel_mime_part_set_content(part, temp_body, strlen(temp_body), e_gw_item_get_msg_content_type (item));
+			else
+				camel_mime_part_set_content(part, " ", strlen(" "), "text/html");
 			break;
 
 		default:
 			break;
 
 	}
-	
+
 	camel_multipart_set_boundary (multipart, NULL);
 	camel_multipart_add_part (multipart, part);
 	camel_object_unref (part);
@@ -301,7 +304,7 @@
 		GSList *rl;
 		char *status_opt = NULL;
 		gboolean enabled;
-		
+
 		for (rl = recipient_list ; rl != NULL ; rl = rl->next) {
 			EGwItemRecipient *recp = (EGwItemRecipient *) rl->data;
 			enabled = recp->status_enabled;
@@ -311,7 +314,7 @@
 			} else {
 				ha=camel_header_address_new_name(recp->display_name,recp->email);
 			}
-			
+
 			if (recp->type == E_GW_ITEM_RECIPIENT_TO) {
 				if (recp->status_enabled) 
 					status_opt = g_strconcat (status_opt ? status_opt : "" , "TO", ";",NULL);
@@ -320,7 +323,7 @@
 				if (recp->status_enabled) 
 					status_opt = g_strconcat (status_opt ? status_opt : "", "CC", ";",NULL);
 				camel_header_address_list_append(&cc_list,ha);
-				
+
 			} else if (recp->type == E_GW_ITEM_RECIPIENT_BC) {
 				if (recp->status_enabled) 
 					status_opt = g_strconcat (status_opt ? status_opt : "", "BCC", ";",NULL);
@@ -330,17 +333,17 @@
 			}
 			if (recp->status_enabled) {
 				status_opt = g_strconcat (status_opt, 
-						      recp->display_name,";",
-						      recp->email,";",
-						      recp->delivered_date ? recp->delivered_date :  "", ";",
-						      recp->opened_date ? recp->opened_date : "", ";", 
-						      recp->accepted_date ? recp->accepted_date : "", ";",
-						      recp->deleted_date ? recp->deleted_date : "", ";", 
-						      recp->declined_date ? recp->declined_date : "", ";",
-						      recp->completed_date ? recp->completed_date : "", ";",
-						      recp->undelivered_date ? recp->undelivered_date : "", ";", 
-						      "::", NULL);
-				
+						recp->display_name,";",
+						recp->email,";",
+						recp->delivered_date ? recp->delivered_date :  "", ";",
+						recp->opened_date ? recp->opened_date : "", ";", 
+						recp->accepted_date ? recp->accepted_date : "", ";",
+						recp->deleted_date ? recp->deleted_date : "", ";", 
+						recp->declined_date ? recp->declined_date : "", ";",
+						recp->completed_date ? recp->completed_date : "", ";",
+						recp->undelivered_date ? recp->undelivered_date : "", ";", 
+						"::", NULL);
+
 			}
 		}
 		if (enabled) {
@@ -371,11 +374,19 @@
 	}
 
 	if (org) {
-		if (org->display_name && org->email) {
-			ha=camel_header_address_new_name(org->display_name,org->email);
-		} else {
+		if (org->display_name && org->display_name[0] && org->email != NULL && org->email[0] != '\0') {
+				int i;
+				for (i = 0; org->display_name[i] != '<' && 
+						org->display_name[i] != '\0';
+						i++);
+
+				org->display_name[i] = '\0';
+		}
+		if (org->display_name && org->email) 
+			ha=camel_header_address_new_name(org->display_name, org->email);
+		else if (org->display_name)
 			ha=camel_header_address_new_group(org->display_name);
-		}
+
 		subs_email=camel_header_address_list_encode(ha);	
 		camel_medium_set_header( CAMEL_MEDIUM(msg), "From", subs_email);
 		camel_header_address_unref(ha);
@@ -383,7 +394,6 @@
 	}
 }
 
-
 static void
 groupwise_folder_rename (CamelFolder *folder, const char *new)
 {
@@ -421,12 +431,12 @@
 {
 	CamelGroupwiseFolder *gw_folder = CAMEL_GROUPWISE_FOLDER(folder);
 	GPtrArray *matches;
-	
+
 	CAMEL_GROUPWISE_FOLDER_LOCK(folder, search_lock);
 	camel_folder_search_set_folder (gw_folder->search, folder);
 	matches = camel_folder_search_search(gw_folder->search, expression, NULL, ex);
 	CAMEL_GROUPWISE_FOLDER_UNLOCK(gw_folder, search_lock);
-	
+
 	return matches;
 }
 
@@ -438,7 +448,7 @@
 
 	if (uids->len == 0)
 		return g_ptr_array_new();
-	
+
 	CAMEL_GROUPWISE_FOLDER_LOCK(folder, search_lock);
 
 	camel_folder_search_set_folder(gw_folder->search, folder);
@@ -453,7 +463,7 @@
 groupwise_folder_search_free (CamelFolder *folder, GPtrArray *uids)
 {
 	CamelGroupwiseFolder *gw_folder = CAMEL_GROUPWISE_FOLDER(folder);
-	
+
 	g_return_if_fail (gw_folder->search);
 
 	CAMEL_GROUPWISE_FOLDER_LOCK(folder, search_lock);
@@ -461,7 +471,7 @@
 	camel_folder_search_free_result (gw_folder->search, uids);
 
 	CAMEL_GROUPWISE_FOLDER_UNLOCK(gw_folder, search_lock);
-	
+
 }
 
 /******************* functions specific to Junk Mail Handling**************/
@@ -481,8 +491,6 @@
 static void
 update_junk_list (CamelStore *store, CamelMessageInfo *info, int flag)
 {
-	GList *list = NULL;
-	EGwJunkEntry *entry;
 	gchar **email = NULL, *from = NULL;	
 	CamelGroupwiseStore *gw_store= CAMEL_GROUPWISE_STORE(store);
 	CamelGroupwiseStorePrivate  *priv = gw_store->priv;
@@ -492,25 +500,25 @@
 		goto error;
 
 	email = g_strsplit_set (from, "<>", -1);
-	if (!email[1])
+
+	if (!email || !email[1])
 		goto error;
 
-	if (e_gw_connection_get_junk_entries (cnc, &list)== E_GW_CONNECTION_STATUS_OK){
-		while (list) {
-			entry = list->data;
-			if (!g_ascii_strcasecmp (entry->match, email[1])) { 
-				if (flag == ADD_JUNK_ENTRY) /*if already there then don't add*/
-					break;
-				else if (flag == REMOVE_JUNK_ENTRY){
+	if (flag == ADD_JUNK_ENTRY)
+		e_gw_connection_create_junk_entry (cnc, email[1], "email", "junk");
+	else if (flag == REMOVE_JUNK_ENTRY) {
+		GList *list = NULL;
+		EGwJunkEntry *entry;
+		if (e_gw_connection_get_junk_entries (cnc, &list)== E_GW_CONNECTION_STATUS_OK){
+			while (list) {
+				entry = list->data;
+				if (!g_ascii_strcasecmp (entry->match, email[1])) { 
 					e_gw_connection_remove_junk_entry (cnc, entry->id);
-					break;
 				}
+				list = list->next;
 			}
-			list = list->next;
+			g_list_foreach (list, (GFunc) free_node, NULL);
 		}
-		if (!list && flag == ADD_JUNK_ENTRY) /*no entry found just create a new entry if asked to*/
-			if (e_gw_connection_create_junk_entry (cnc, email[1], "email", "junk") == E_GW_CONNECTION_STATUS_OK);
-		g_list_foreach (list, (GFunc) free_node, NULL);
 	}
 
 error:
@@ -524,10 +532,10 @@
 	CamelFolder *dest;
 	GPtrArray *uids;
 	const char *uid = camel_message_info_uid (info);
-	
+
 	uids = g_ptr_array_new ();
 	g_ptr_array_add (uids, (gpointer) uid);
-	
+
 	dest = camel_store_get_folder (folder->parent_store, "Mailbox", 0, ex);
 	if (dest)
 		groupwise_transfer_messages_to (folder, uids, dest, NULL, TRUE, ex);
@@ -544,10 +552,10 @@
 	CamelFolderInfo *fi;
 	GPtrArray *uids;
 	const char *uid = camel_message_info_uid (info);
-	
+
 	uids = g_ptr_array_new ();
 	g_ptr_array_add (uids, (gpointer) uid);
- 	
+
 	dest = camel_store_get_folder (folder->parent_store, JUNK_FOLDER, 0, ex);
 	if (dest)
 		groupwise_transfer_messages_to (folder, uids, dest, NULL, TRUE, ex);
@@ -559,31 +567,46 @@
 		else
 			groupwise_transfer_messages_to (folder, uids, dest, NULL, TRUE, ex);
 	}
-	
+
 	update_junk_list (folder->parent_store, info, ADD_JUNK_ENTRY);
-	
+
 }
 
 /********************* back to folder functions*************************/
 
+static void 
+groupwise_sync_summary (CamelFolder *folder, CamelException *ex)
+{
+	camel_folder_summary_save (folder->summary);
+	camel_store_summary_save ((CamelStoreSummary *)((CamelGroupwiseStore *)folder->parent_store)->summary);
+}
+
 static void
 groupwise_sync (CamelFolder *folder, gboolean expunge, CamelException *ex)
 {
 	CamelGroupwiseStore *gw_store = CAMEL_GROUPWISE_STORE (folder->parent_store);
 	CamelGroupwiseFolder *gw_folder = CAMEL_GROUPWISE_FOLDER (folder);
 	CamelGroupwiseStorePrivate *priv = gw_store->priv;
-	CamelMessageInfo *info;
+	CamelMessageInfo *info = NULL;
 	CamelGroupwiseMessageInfo *gw_info;
-	GList *read_items = NULL, *deleted_items = NULL;
+	GList *read_items = NULL;
 	flags_diff_t diff;
 	const char *container_id;
 	EGwConnectionStatus status;
-	EGwConnection *cnc = cnc_lookup (priv);
+	EGwConnection *cnc;
 	int count, i;
 
-	if (((CamelOfflineStore *) gw_store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL) 
+	GList *deleted_items, *deleted_head;
+
+	deleted_items = deleted_head = NULL;
+
+	if (((CamelOfflineStore *) gw_store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL || 
+			((CamelService *)gw_store)->status == CAMEL_SERVICE_DISCONNECTED) {
+		groupwise_sync_summary (folder, ex);
 		return;
-	
+	}
+	cnc = cnc_lookup (priv);
+
 	container_id =  camel_groupwise_store_container_id_lookup (gw_store, folder->full_name) ;
 
 	CAMEL_SERVICE_LOCK (gw_store, connect_lock);
@@ -596,11 +619,11 @@
 
 	count = camel_folder_summary_count (folder->summary);
 	CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
-	for (i=0 ; i <count ; i++) {
+	for (i=0 ; i < count ; i++) {
 		guint32 flags = 0;
 		info = camel_folder_summary_index (folder->summary, i);
 		gw_info = (CamelGroupwiseMessageInfo *) info;
-		
+
 		/**Junk Mail handling**/
 		if(!info)
 			continue;
@@ -608,6 +631,7 @@
 
 		if ((flags & CAMEL_MESSAGE_JUNK) && !(flags & CAMEL_GW_MESSAGE_JUNK)) /*marked a message junk*/
 			move_to_junk (folder, info, ex);
+
 		else if ((flags & CAMEL_MESSAGE_JUNK) && (flags & CAMEL_GW_MESSAGE_JUNK)) /*message was marked as junk, now unjunk*/ 
 			move_to_mailbox (folder, info, ex);
 
@@ -616,64 +640,91 @@
 			diff.changed &= folder->permanent_flags;
 
 			/* weed out flag changes that we can't sync to the server */
-			if (!diff.changed)
+			if (!diff.changed) {
 				camel_message_info_free(info);
-			else {
+				continue;
+			} else {
+				gw_info->server_flags = gw_info->info.flags;
 				const char *uid = camel_message_info_uid (info);
 				if (diff.changed & CAMEL_MESSAGE_SEEN)
 					read_items = g_list_append (read_items, (char *)uid);
 				if (diff.changed & CAMEL_MESSAGE_DELETED) {
-					/*deleted_items = g_list_append (deleted_items, (char *)uid);*/
-					CAMEL_SERVICE_LOCK (gw_store, connect_lock);
-					status = e_gw_connection_remove_item (cnc, container_id, uid);
-					if (status == E_GW_CONNECTION_STATUS_OK) {
-						CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
-						camel_folder_summary_remove (folder->summary, info);
-						camel_data_cache_remove(gw_folder->cache, "cache", uid, ex);
-						CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
-						i--; count--;
+					if (deleted_items)
+						deleted_items = g_list_prepend (deleted_items, (char *)camel_message_info_uid (info));
+					else {
+						g_list_free (deleted_head);
+						deleted_head = NULL;
+						deleted_head = deleted_items = g_list_prepend (deleted_items, (char *)camel_message_info_uid (info));
 					}
-					CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+
+					if (g_list_length (deleted_items) == GROUPWISE_BULK_DELETE_LIMIT ) {
+						CAMEL_SERVICE_LOCK (gw_store, connect_lock);
+						status = e_gw_connection_remove_items (cnc, container_id, deleted_items);
+						CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+						if (status == E_GW_CONNECTION_STATUS_OK) {
+							char *uid;
+							while (deleted_items) {
+								uid = (char *)deleted_items->data;
+								CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
+								camel_folder_summary_remove_uid (folder->summary, uid);
+								camel_data_cache_remove(gw_folder->cache, "cache", uid, ex);
+								CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
+								deleted_items = g_list_next (deleted_items);
+								count -= GROUPWISE_BULK_DELETE_LIMIT;
+								i -= GROUPWISE_BULK_DELETE_LIMIT;
+							}
+						}
+					}
 				}
 			}
 		}
 		camel_message_info_free (info);
-		info = NULL;
 	}
 	CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
+	if (deleted_items) {
+		CAMEL_SERVICE_LOCK (gw_store, connect_lock);
+		if (!strcmp (folder->full_name, "Trash")) {
+			status = e_gw_connection_purge_selected_items (cnc, deleted_items);
+		} else {
+			status = e_gw_connection_remove_items (cnc, container_id, deleted_items);
+		}
+		CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+		if (status == E_GW_CONNECTION_STATUS_OK) {
+			char *uid;
+			while (deleted_items) {
+				uid = (char *)deleted_items->data;
+				CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
+				camel_folder_summary_remove_uid (folder->summary, uid);
+				camel_data_cache_remove(gw_folder->cache, "cache", uid, ex);
+				CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
+				deleted_items = g_list_next (deleted_items);
+				count -= GROUPWISE_BULK_DELETE_LIMIT;
+				i -= GROUPWISE_BULK_DELETE_LIMIT;
+			}
+		}
+		g_list_free (deleted_head);
+	}
 
 	if (read_items && g_list_length (read_items)) {
 		CAMEL_SERVICE_LOCK (gw_store, connect_lock);
 		e_gw_connection_mark_read (cnc, read_items);
 		CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
 	}
-	if (deleted_items) {
-	/*	status = e_gw_connection_remove_items (cnc, container_id, deleted_items);
-		if (status == E_GW_CONNECTION_STATUS_OK) {
-			GList *temp_list = deleted_items;
-			int len = g_list_length (deleted_items);
-			int i;
-			for (i=0 ; i<len ; i++) {
-				camel_folder_summary_remove_uid(folder->summary, (const char *)temp_list->data);
-				camel_data_cache_remove (gw_folder->cache, "cache", (const char *)temp_list->data, ex);
-				temp_list = g_list_next (deleted_items);
-			}
-		}*/
-	}
 
 	if (expunge) {
 		CAMEL_SERVICE_LOCK (gw_store, connect_lock);
 		status = e_gw_connection_purge_deleted_items (cnc);
 		if (status == E_GW_CONNECTION_STATUS_OK) {
+			g_message ("Purged deleted items in %s", folder->name);
 		}
 		CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
 	}
-	
-	camel_folder_summary_save (folder->summary);
+
+	CAMEL_SERVICE_LOCK (gw_store, connect_lock);
+	groupwise_sync_summary (folder, ex);
+	CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
 }
 
-
-
 CamelFolder *
 camel_gw_folder_new(CamelStore *store, const char *folder_name, const char *folder_dir, CamelException *ex) 
 {
@@ -699,11 +750,11 @@
 	if (!folder->summary) {
 		camel_object_unref (CAMEL_OBJECT (folder));
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
-				      _("Could not load summary for %s"),
-				      folder_name);
+				_("Could not load summary for %s"),
+				folder_name);
 		return NULL;
 	}
-	
+
 	/* set/load persistent state */
 	state_file = g_strdup_printf ("%s/cmeta", folder_dir);
 	camel_object_set(folder, NULL, CAMEL_OBJECT_STATE_FILE, state_file, NULL);
@@ -718,6 +769,7 @@
 
 	journal_file = g_strdup_printf ("%s/journal",folder_dir);
 	gw_folder->journal = camel_groupwise_journal_new (gw_folder, journal_file);
+	g_free (journal_file);
 	if (!gw_folder->journal) {
 		camel_object_unref (folder);
 		return NULL;
@@ -727,13 +779,13 @@
 		if (camel_url_get_param (((CamelService *) store)->url, "filter"))
 			folder->folder_flags |= CAMEL_FOLDER_FILTER_RECENT;
 	}
-	
+
 	gw_folder->search = camel_folder_search_new ();
 	if (!gw_folder->search) {
 		camel_object_unref (folder);
 		return NULL;
 	}
-	
+
 	return folder;
 }
 
@@ -747,7 +799,6 @@
 	GSList *slist;
 };
 
-
 static void
 update_update (CamelSession *session, CamelSessionThreadMsg *msg)
 {
@@ -755,7 +806,7 @@
 	EGwConnectionStatus status;
 	CamelException *ex = NULL;
 
-	GList *item_list;
+	GList *item_list, *items_full_list = NULL, *last_element=NULL;
 	int cursor = 0;
 	const char *position = E_GW_CURSOR_POSITION_END;
 	gboolean done;
@@ -777,20 +828,48 @@
 			e_gw_connection_destroy_cursor (m->cnc, m->container_id, cursor);
 			return;
 		}
-		
+
 		if (!item_list  || g_list_length (item_list) == 0)
 			done = TRUE;
 		else {
-			for (;item_list; item_list = g_list_next (item_list)) {
-				m->slist = g_slist_prepend (m->slist, (char *)item_list->data);
+
+			/* item_list is prepended to items_full_list and not the other way
+			   because when we have a large number of items say 50000, 
+			   for each iteration there will be more elements in items_full_list 
+			   and less elements in item_list */
+
+			last_element = g_list_last (item_list);
+			if (items_full_list) {
+				last_element->next = items_full_list;
+				items_full_list->prev = last_element;
 			}
+			items_full_list = item_list;
 		}
-		g_list_free (item_list);
 		position = E_GW_CURSOR_POSITION_CURRENT;
 	}
 	e_gw_connection_destroy_cursor (m->cnc, m->container_id, cursor);
 
-	gw_update_all_items (m->folder, m->slist, ex);
+	/* Take out only the first part in the list until the @ since it is guaranteed
+	   to be unique only until that symbol */
+
+	/*if (items_full_list) {
+	  int i;
+	  item_list = items_full_list;
+
+	  while (item_list->next) {
+	  i = 0;
+	  while (((const char *)item_list->data)[i++]!='@');
+	  ((char *)item_list->data)[i-1] = '\0';
+	  item_list = item_list->next;
+	  }
+
+	  i = 0;	
+	  while (((const char *)item_list->data)[i++]!='@');
+	  ((char *)item_list->data)[i-1] = '\0';
+	  }*/
+
+	g_print ("\nNumber of items in the folder: %d \n", g_list_length(items_full_list));
+	gw_update_all_items (m->folder, items_full_list, ex);
 }
 
 static void
@@ -818,6 +897,7 @@
 	CamelGroupwiseSummary *summary;
 	CamelStoreInfo *si;
 	summary = (CamelGroupwiseSummary *) folder->summary;
+	CamelGroupwiseStore *gw_store = CAMEL_GROUPWISE_STORE (folder->parent_store);
 	/*
 	 * Checking for the summary->time_string here since the first the a
 	 * user views a folder, the read cursor is in progress, and the getQM
@@ -838,6 +918,12 @@
 		}
 		camel_folder_summary_save (folder->summary);
 		camel_store_summary_save ((CamelStoreSummary *)((CamelGroupwiseStore *)folder->parent_store)->summary);
+	} else {
+		/* We probably could not get the messages the first time. (get_folder) failed???!
+		 * so do a get_folder again. And hope that it works
+		 */
+		g_print("Reloading folder...something wrong with the summary....\n");
+		gw_store_reload_folder (gw_store, folder, 0, ex);
 	}
 }
 
@@ -858,7 +944,12 @@
 	char *container_id = NULL;
 	char *time_string = NULL, *t_str = NULL;
 	struct _folder_update_msg *msg;
+	gboolean check_all = FALSE;
 
+	/* Sync-up the (un)read changes before getting updates,
+	so that the getFolderList will reflect the most recent changes too */
+	groupwise_sync (folder, FALSE, ex);
+
 	if (((CamelOfflineStore *) gw_store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL) {
 		g_warning ("In offline mode. Cannot refresh!!!\n");
 		return;
@@ -871,20 +962,26 @@
 		return;
 	}
 
+	if (!cnc) 
+		return;
+
 	if (camel_folder_is_frozen (folder) ) {
 		gw_folder->need_refresh = TRUE;
 	}
-	
+
 	CAMEL_SERVICE_LOCK (gw_store, connect_lock);
 
 	if (!camel_groupwise_store_connected (gw_store, ex)) 
 		goto end1;
 
-	if (!strcmp (folder->full_name, "Trash") || is_proxy) {
-		status = e_gw_connection_get_items (cnc, container_id, "peek recipient distribution created attachments subject status size", NULL, &list);
+	if (!strcmp (folder->full_name, "Trash")) {
+#if 0
+		status = e_gw_connection_get_items (cnc, container_id, "peek recipient distribution created delivered attachments subject status size", NULL, &list);
 		if (status != E_GW_CONNECTION_STATUS_OK) {
 			if (status ==E_GW_CONNECTION_STATUS_OTHER) {
 				g_warning ("Trash full....Empty Trash!!!!\n");
+				camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Trash Folder Full. Please Empty."));
+				goto end1;
 				/*groupwise_expunge (folder, ex);*/
 			} else
 				camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
@@ -898,62 +995,87 @@
 			list = NULL;
 		}
 		goto end1;
+#endif
+		is_proxy = TRUE;
 	}
 
 	time_string =  g_strdup (((CamelGroupwiseSummary *) folder->summary)->time_string);
 	t_str = g_strdup (time_string); 
+
 	/*Get the New Items*/
-	status = e_gw_connection_get_quick_messages (cnc, container_id,
-			"peek id",
-			&t_str, "New", NULL, NULL, -1, &slist);
-	if (status != E_GW_CONNECTION_STATUS_OK) {
-		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
-		goto end2;
-	}
+	if (!is_proxy) {
+		status = e_gw_connection_get_quick_messages (cnc, container_id,
+				"peek id",
+				&t_str, "New", NULL, NULL, -1, &slist);
+		if (status != E_GW_CONNECTION_STATUS_OK) {
+			camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
+			goto end2;
+		}
 
-	/*
-	 * The value in t_str is the one that has to be used for the next set of calls. 
-	 * so store this value in the summary.
-	 */
-	if (summary->time_string)
-		g_free (summary->time_string);
-	summary->time_string = g_strdup (t_str);
-	g_free (t_str);	
-	t_str = NULL;
+		/*
+		 * The value in t_str is the one that has to be used for the next set of calls. 
+		 * so store this value in the summary.
+		 */
+		if (summary->time_string)
+			g_free (summary->time_string);
 
-	for ( sl = slist ; sl != NULL; sl = sl->next) 
-		list = g_list_append (list, sl->data);
 
-	g_slist_free (slist);
-	slist = NULL;
+		//summary->time_string = g_strdup (t_str);
+		((CamelGroupwiseSummary *) folder->summary)->time_string = g_strdup (t_str);
+		camel_folder_summary_touch (folder->summary);
+		groupwise_sync_summary (folder, ex);
+		g_free (t_str);	
+		t_str = NULL;
 
-	t_str = g_strdup (time_string);
+		/*
+		   for ( sl = slist ; sl != NULL; sl = sl->next) 
+		   list = g_list_append (list, sl->data);*/
 
-	/*Get those items which have been modifed*/
-	status = e_gw_connection_get_quick_messages (cnc, container_id,
-			"peek id",
-			&t_str, "Modified", NULL, NULL, -1, &slist);
-	g_free (t_str), t_str = NULL;
-	if (status != E_GW_CONNECTION_STATUS_OK) {
-		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
-		goto end3;
-	}
-	
-	for ( sl = slist ; sl != NULL; sl = sl->next) 
-		list = g_list_append (list, sl->data);
+		if (slist && g_slist_length(slist) != 0)
+			check_all = TRUE;
 
-	g_slist_free (slist);
-	slist = NULL;
+		g_slist_free (slist);
+		slist = NULL;
 
-	if (gw_store->current_folder != folder) {
-		gw_store->current_folder = folder;
+		t_str = g_strdup (time_string);
+
+		/*Get those items which have been modifed*/
+
+		status = e_gw_connection_get_quick_messages (cnc, container_id,
+				"peek id",
+				&t_str, "Modified", NULL, NULL, -1, &slist);
+
+		if (status != E_GW_CONNECTION_STATUS_OK) {
+			camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
+			goto end3;
+		}
+
+		/* The storing of time-stamp to summary code below should be commented if the 
+		   above commented code is uncommented */
+
+		/*	if (summary->time_string)
+			g_free (summary->time_string);
+
+			summary->time_string = g_strdup (t_str);
+
+			g_free (t_str), t_str = NULL;*/
+
+		for ( sl = slist ; sl != NULL; sl = sl->next) 
+			list = g_list_prepend (list, sl->data);
+
+		g_slist_free (slist);
+		slist = NULL;
+
+		if (gw_store->current_folder != folder) {
+			gw_store->current_folder = folder;
+		}
+
+		if (list) {
+			gw_update_cache (folder, list, ex, FALSE);
+		}
 	}
 
-	if (list) {
-		gw_update_cache (folder, list, ex);
-	}
-	
- 
+
 	CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
 	is_locked = FALSE;
 
@@ -964,17 +1086,18 @@
 	 * this folder, and update the summary.
 	 */
 	/*create a new session thread for the update all operation*/
-	msg = camel_session_thread_msg_new (session, &update_ops, sizeof(*msg));
-	msg->cnc = cnc;
-	msg->t_str = g_strdup (time_string);
-	msg->container_id = g_strdup (container_id);
-	msg->folder = folder;
-	camel_object_ref (folder);
-	camel_folder_freeze (folder);
-	camel_session_thread_queue (session, &msg->msg, 0);
-	/*thread creation and queueing done*/
+	if (check_all || is_proxy) {
+		msg = camel_session_thread_msg_new (session, &update_ops, sizeof(*msg));
+		msg->cnc = cnc;
+		msg->t_str = g_strdup (time_string);
+		msg->container_id = g_strdup (container_id);
+		msg->folder = folder;
+		camel_object_ref (folder);
+		camel_folder_freeze (folder);
+		camel_session_thread_queue (session, &msg->msg, 0);
+		/*thread creation and queueing done*/
+	}
 
-
 end3: 
 	g_list_foreach (list, (GFunc) g_object_unref, NULL);
 	g_list_free (list);
@@ -989,10 +1112,11 @@
 	return;
 }
 
-void
-gw_update_cache ( CamelFolder *folder, GList *list, CamelException *ex) 
+static void
+gw_update_cache (CamelFolder *folder, GList *list, CamelException *ex, gboolean uid_flag) 
 {
 	CamelGroupwiseMessageInfo *mi = NULL;
+	CamelMessageInfo *pmi = NULL;
 	CamelGroupwiseStore *gw_store = CAMEL_GROUPWISE_STORE (folder->parent_store);
 	CamelGroupwiseFolder *gw_folder = CAMEL_GROUPWISE_FOLDER(folder);
 	CamelGroupwiseStorePrivate *priv = gw_store->priv;
@@ -1008,8 +1132,9 @@
 	EGwItemStatus status;
 	GList *item_list = list;
 	int total_items = g_list_length (item_list), i=0;
-	
-	/*Assert lock*/
+
+	CAMEL_SERVICE_ASSERT_LOCKED (gw_store, connect_lock);
+
 	changes = camel_folder_change_info_new ();
 	container_id = g_strdup (camel_groupwise_store_container_id_lookup (gw_store, folder->full_name));
 	if (!container_id) {
@@ -1017,15 +1142,15 @@
 		camel_folder_change_info_free (changes);
 		return;
 	}
-	
+
 	if (!strcmp (folder->full_name, JUNK_FOLDER)) {
 		is_junk = TRUE;
 	}
 
-	camel_operation_start (NULL, _("Fetching summary information for new messages"));
+	camel_operation_start (NULL, _("Fetching summary information for new messages in %s"), folder->name);
 
 	for ( ; item_list != NULL ; item_list = g_list_next (item_list) ) {
-		EGwItem *temp_item = (EGwItem *)item_list->data;
+		EGwItem *temp_item ;
 		EGwItem *item;
 		EGwItemType type = E_GW_ITEM_TYPE_UNKNOWN;
 		EGwItemOrganizer *org;
@@ -1033,32 +1158,34 @@
 		const char *id;
 		GSList *recp_list = NULL;
 		status_flags = 0;
-		CamelStream *cache_stream;
+		CamelStream *cache_stream, *t_cache_stream;
 		CamelMimeMessage *mail_msg = NULL;
+		gboolean is_sent_folder = FALSE;
 
-		id = e_gw_item_get_id (temp_item);
+		exists = FALSE;
 
+		if (uid_flag == FALSE) {
+			temp_item = (EGwItem *)item_list->data;
+			id = e_gw_item_get_id (temp_item);
+		} else 
+			id = (char *) item_list->data;
+
 		camel_operation_progress (NULL, (100*i)/total_items);
-		cache_stream  = camel_data_cache_get (gw_folder->cache, "cache", id, ex);
-		if (cache_stream) {
-			camel_object_unref (cache_stream);
-			cache_stream = NULL;
-			i++;
-			//g_print ("*** Exists in cache, continuing....%s\n", id);
-			continue;
-		} 
 
-		status = e_gw_connection_get_item (cnc, container_id, id, "peek default distribution recipient message attachments subject notification created recipientStatus status", &item);
+		status = e_gw_connection_get_item (cnc, container_id, id, "peek default distribution recipient message attachments subject notification created recipientStatus status hasAttachment size", &item);
 		if (status != E_GW_CONNECTION_STATUS_OK) {
 			i++;
 			continue;
 		}
 
 		/************************ First populate summary *************************/
-		mi = (CamelGroupwiseMessageInfo *)camel_folder_summary_uid (folder->summary, id);
-		if (mi) {
+		mi = NULL;
+		pmi = NULL;
+		pmi = camel_folder_summary_uid (folder->summary, id);
+		if (pmi) {
 			exists = TRUE;
-			camel_message_info_free (&mi->info);
+			camel_message_info_ref (pmi);
+			mi = (CamelGroupwiseMessageInfo *)pmi;
 		}
 
 		if (!exists) {
@@ -1068,7 +1195,7 @@
 				continue;
 			}
 
-			mi = camel_message_info_new (folder->summary); 
+			mi = (CamelGroupwiseMessageInfo *)camel_message_info_new (folder->summary); 
 			if (mi->info.content == NULL) {
 				mi->info.content = camel_folder_summary_content_info_new (folder->summary);
 				mi->info.content->type = camel_content_type_new ("multipart", "mixed");
@@ -1082,35 +1209,47 @@
 		item_status = e_gw_item_get_item_status (item);
 		if (item_status & E_GW_ITEM_STAT_READ)
 			status_flags |= CAMEL_MESSAGE_SEEN;
-		/*if (item_status & E_GW_ITEM_STAT_DELETED)
-		  status_flags |= CAMEL_MESSAGE_DELETED;*/
+		else 
+			mi->info.flags &= ~CAMEL_MESSAGE_SEEN;
+
 		if (item_status & E_GW_ITEM_STAT_REPLIED)
 			status_flags |= CAMEL_MESSAGE_ANSWERED;
-		mi->info.flags |= status_flags;
+		if (exists) 
+			mi->info.flags |= status_flags;
+		else 
+			mi->info.flags = status_flags;
 
 		priority = e_gw_item_get_priority (item);
 		if (priority && !(g_ascii_strcasecmp (priority,"High"))) {
 			mi->info.flags |= CAMEL_MESSAGE_FLAGGED;
 		}
 
-		attach_list = e_gw_item_get_attach_id_list (item);
-		if (attach_list)  {
-			GSList *al = attach_list;
-			gboolean has_attachments = TRUE;
-			EGwItemAttachment *attach = (EGwItemAttachment *)al->data;
+		mi->server_flags = mi->info.flags;
+		
+		if (e_gw_item_has_attachment (item))
+			mi->info.flags |= CAMEL_MESSAGE_ATTACHMENTS;
 
-			if (!g_ascii_strcasecmp (attach->name, "Mime.822") ||
-			    !g_ascii_strcasecmp (attach->name, "TEXT.htm")) 
-				has_attachments = FALSE;
-
-			if (has_attachments)
-				mi->info.flags |= CAMEL_MESSAGE_ATTACHMENTS;
-		}
-
 		org = e_gw_item_get_organizer (item); 
 		if (org) {
-			g_string_append_printf (str, "%s <%s>",org->display_name, org->email);
+			GString *str;
+			int i;
+			str = g_string_new ("");
+			if (org->display_name && org->display_name[0] && org->email != NULL && org->email[0] != '\0') {
+				for (i = 0; org->display_name[i] != '<' && 
+						org->display_name[i] != '\0';
+						i++);
+
+				org->display_name[i] = '\0';
+				str = g_string_append (str, org->display_name);
+				str = g_string_append (str, " ");
+			}
+			if (org->email && org->email[0]) { 
+				g_string_append (str, "<");
+				str = g_string_append (str, org->email);
+				g_string_append (str, ">");
+			}
 			mi->info.from = camel_pstring_strdup (str->str);
+			g_string_free (str, TRUE);
 		}
 		g_string_truncate (str, 0);
 		recp_list = e_gw_item_get_recipient_list (item);
@@ -1126,13 +1265,15 @@
 					i++;
 				}
 			}
+			if (exists)
+				camel_pstring_free(mi->info.to);
 			mi->info.to = camel_pstring_strdup (str->str);
 			g_string_truncate (str, 0);
 		}
-		
+
 		if (type == E_GW_ITEM_TYPE_APPOINTMENT
-		    || type ==  E_GW_ITEM_TYPE_NOTE 
-		    || type ==  E_GW_ITEM_TYPE_TASK ) {
+				|| type ==  E_GW_ITEM_TYPE_NOTE 
+				|| type ==  E_GW_ITEM_TYPE_TASK ) {
 			temp_date = e_gw_item_get_start_date (item);
 			if (temp_date) {
 				time_t time = e_gw_connection_get_date_from_string (temp_date);
@@ -1140,38 +1281,52 @@
 				mi->info.date_sent = mi->info.date_received = actual_time;
 			}
 		} else {
-			temp_date = e_gw_item_get_creation_date(item);
+			temp_date = e_gw_item_get_delivered_date(item);
 			if (temp_date) {
 				time_t time = e_gw_connection_get_date_from_string (temp_date);
 				time_t actual_time = camel_header_decode_date (ctime(&time), NULL);
 				mi->info.date_sent = mi->info.date_received = actual_time;
+			} else {
+				time_t time;
+				time_t actual_time;
+				temp_date = e_gw_item_get_creation_date (item);
+				time = e_gw_connection_get_date_from_string (temp_date);
+				actual_time = camel_header_decode_date (ctime(&time), NULL);
+				mi->info.date_sent = mi->info.date_received = actual_time;
 			}
 		}
 
-		mi->info.uid = g_strdup(e_gw_item_get_id(item));
-		if (!exists)
+		if (!exists) {
+			mi->info.uid = g_strdup (e_gw_item_get_id(item));
 			mi->info.size = e_gw_item_get_mail_size (item);	
-		mi->info.subject = camel_pstring_strdup(e_gw_item_get_subject(item));
-		
-		if (exists) 
-			camel_folder_change_info_change_uid (changes, e_gw_item_get_id (item));
-		else {
+			mi->info.subject = camel_pstring_strdup(e_gw_item_get_subject(item));
+		}
+
+		if (exists) {
+			camel_folder_change_info_change_uid (changes, mi->info.uid);
+			camel_message_info_free (pmi);
+		} else {
 			camel_folder_summary_add (folder->summary,(CamelMessageInfo *)mi);
 			camel_folder_change_info_add_uid (changes, mi->info.uid);
 			camel_folder_change_info_recent_uid (changes, mi->info.uid);
 		}
 
-		/********************* Summary Stuff ends *************************/
-		exists = FALSE;
-		if (!strcmp (folder->full_name, "Junk Mail")|| !strcmp (folder->full_name, "Sent Items"))
+		/********************* Summary ends *************************/
+		if (!strcmp (folder->full_name, "Junk Mail"))
 			continue;
 
+		if (!strcmp (folder->full_name, "Sent Items"))
+			is_sent_folder = TRUE;
 		/******************** Begine Caching ************************/
-		mail_msg = groupwise_folder_item_to_msg (folder, item, ex);
-		if (mail_msg)
-			camel_medium_set_header (CAMEL_MEDIUM (mail_msg), "X-Evolution-Source", groupwise_base_url_lookup (priv));
 		/* add to cache if its a new message*/
-		if (!exists) {
+		t_cache_stream  = camel_data_cache_get (gw_folder->cache, "cache", id, ex);
+		if (t_cache_stream && !is_sent_folder) {
+			camel_object_unref (t_cache_stream);
+
+			mail_msg = groupwise_folder_item_to_msg (folder, item, ex);
+			if (mail_msg)
+				camel_medium_set_header (CAMEL_MEDIUM (mail_msg), "X-Evolution-Source", groupwise_base_url_lookup (priv));
+
 			CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
 			if ((cache_stream = camel_data_cache_add (gw_folder->cache, "cache", id, NULL))) {
 				if (camel_data_wrapper_write_to_stream ((CamelDataWrapper *) mail_msg, 	cache_stream) == -1 || camel_stream_flush (cache_stream) == -1)
@@ -1207,7 +1362,7 @@
 	char *container_id = NULL;
 	gboolean is_junk = FALSE;
 	GList *item_list = list;
-	
+
 	/*Assert lock???*/
 	changes = camel_folder_change_info_new ();
 	container_id = g_strdup (camel_groupwise_store_container_id_lookup (gw_store, folder->full_name));
@@ -1216,7 +1371,7 @@
 		camel_folder_change_info_free (changes);
 		return;
 	}
-	
+
 	if (!strcmp (folder->full_name, JUNK_FOLDER)) {
 		is_junk = TRUE;
 	}
@@ -1231,12 +1386,10 @@
 		status_flags = 0;
 
 		id = e_gw_item_get_id (item);
-		
+
 		mi = (CamelGroupwiseMessageInfo *)camel_folder_summary_uid (folder->summary, id);
-		if (mi) {
+		if (mi) 
 			exists = TRUE;
-			camel_message_info_free (&mi->info);
-		}
 
 		if (!exists) {
 			type = e_gw_item_get_item_type (item);
@@ -1259,35 +1412,44 @@
 		item_status = e_gw_item_get_item_status (item);
 		if (item_status & E_GW_ITEM_STAT_READ)
 			status_flags |= CAMEL_MESSAGE_SEEN;
-		/*if (item_status & E_GW_ITEM_STAT_DELETED)
-		  status_flags |= CAMEL_MESSAGE_DELETED;*/
 		if (item_status & E_GW_ITEM_STAT_REPLIED)
 			status_flags |= CAMEL_MESSAGE_ANSWERED;
+
+		if (!strcmp (folder->full_name, "Trash"))
+			status_flags |= CAMEL_MESSAGE_SEEN;
+
 		mi->info.flags |= status_flags;
 
+
 		priority = e_gw_item_get_priority (item);
 		if (priority && !(g_ascii_strcasecmp (priority,"High"))) {
 			mi->info.flags |= CAMEL_MESSAGE_FLAGGED;
 		}
+		
+		if (e_gw_item_has_attachment (item))
+			mi->info.flags |= CAMEL_MESSAGE_ATTACHMENTS;
 
-		attach_list = e_gw_item_get_attach_id_list (item);
-		if (attach_list)  {
-			GSList *al = attach_list;
-			gboolean has_attachments = TRUE;
-			EGwItemAttachment *attach = (EGwItemAttachment *)al->data;
-
-			if (!g_ascii_strcasecmp (attach->name, "Mime.822") ||
-			    !g_ascii_strcasecmp (attach->name, "TEXT.htm")) 
-				has_attachments = FALSE;
-
-			if (has_attachments)
-				mi->info.flags |= CAMEL_MESSAGE_ATTACHMENTS;
-		}
-
 		org = e_gw_item_get_organizer (item); 
 		if (org) {
-			g_string_append_printf (str, "%s <%s>",org->display_name, org->email);
+			GString *str;
+			int i;
+			str = g_string_new ("");
+			if (org->display_name && org->display_name[0] && org->email != NULL && org->email[0] != '\0') {
+				for (i = 0; org->display_name[i] != '<' && 
+						org->display_name[i] != '\0'; 
+						i++);
+
+				org->display_name[i] = '\0';
+				str = g_string_append (str, org->display_name);
+				str = g_string_append (str, " ");
+			}
+			if (org->email && org->email[0]) { 
+				g_string_append (str, "<");
+				str = g_string_append (str, org->email);
+				g_string_append (str, ">");
+			}
 			mi->info.from = camel_pstring_strdup (str->str);
+			g_string_free (str, TRUE);
 		}
 		g_string_truncate (str, 0);
 		recp_list = e_gw_item_get_recipient_list (item);
@@ -1306,10 +1468,10 @@
 			mi->info.to = camel_pstring_strdup (str->str);
 			g_string_truncate (str, 0);
 		}
-		
-		if (type == E_GW_ITEM_TYPE_APPOINTMENT
-		    || type ==  E_GW_ITEM_TYPE_NOTE 
-		    || type ==  E_GW_ITEM_TYPE_TASK ) {
+
+		if (type == E_GW_ITEM_TYPE_APPOINTMENT ||
+		    type ==  E_GW_ITEM_TYPE_NOTE ||
+		    type ==  E_GW_ITEM_TYPE_TASK ) {
 			temp_date = e_gw_item_get_start_date (item);
 			if (temp_date) {
 				time_t time = e_gw_connection_get_date_from_string (temp_date);
@@ -1317,11 +1479,18 @@
 				mi->info.date_sent = mi->info.date_received = actual_time;
 			} 
 		} else {
-			temp_date = e_gw_item_get_creation_date(item);
+			temp_date = e_gw_item_get_delivered_date(item);
 			if (temp_date) {
 				time_t time = e_gw_connection_get_date_from_string (temp_date);
 				time_t actual_time = camel_header_decode_date (ctime(&time), NULL);
 				mi->info.date_sent = mi->info.date_received = actual_time;
+			} else {
+				time_t time;
+				time_t actual_time;
+				temp_date = e_gw_item_get_creation_date (item);
+				time = e_gw_connection_get_date_from_string (temp_date);
+				actual_time = camel_header_decode_date (ctime(&time), NULL);
+				mi->info.date_sent = mi->info.date_received = actual_time;
 			}
 		}
 
@@ -1329,10 +1498,11 @@
 		if (!exists)
 			mi->info.size = e_gw_item_get_mail_size (item);	
 		mi->info.subject = camel_pstring_strdup(e_gw_item_get_subject(item));
-		
-		if (exists) 
+
+		if (exists) {
 			camel_folder_change_info_change_uid (changes, e_gw_item_get_id (item));
-		else {
+			camel_message_info_free (&mi->info);
+		} else {
 			camel_folder_summary_add (folder->summary,(CamelMessageInfo *)mi);
 			camel_folder_change_info_add_uid (changes, mi->info.uid);
 			camel_folder_change_info_recent_uid (changes, mi->info.uid);
@@ -1363,8 +1533,13 @@
 	CamelMultipart *multipart;
 	int errno;
 	char *body = NULL;
+	int body_len = 0;
 	const char *uid = NULL;
-	
+	gboolean is_text_html = FALSE;
+	gboolean has_mime_822 = FALSE;
+	gboolean is_text_html_embed = FALSE;
+	gboolean is_base64_encoded = FALSE;
+	CamelStream *temp_stream;
 
 	uid = e_gw_item_get_id(item);
 	cnc = cnc_lookup (priv);
@@ -1378,9 +1553,9 @@
 		char *attachment = NULL;
 		int len = 0;
 
-		if (!g_ascii_strcasecmp (attach->name, "Mime.822") ||
-		    !g_ascii_strcasecmp (attach->name, "TEXT.htm")) {
-			
+		if (!g_ascii_strcasecmp (attach->name, "Text.htm") ||
+		    !g_ascii_strcasecmp (attach->name, "Header")) {
+
 			status = e_gw_connection_get_attachment (cnc,
 					attach->id, 0, -1,
 					(const char **)&attachment, &len);
@@ -1393,14 +1568,70 @@
 				if (!g_ascii_strcasecmp (attach->name, "TEXT.htm")) {
 					body = g_strdup (attachment);
 					g_free (attachment);
+					is_text_html = TRUE;
 				} 
 			}//if attachment and len
 		} // if Mime.822 or TEXT.htm
+
+		for (al = attach_list ; al != NULL ; al = al->next) {
+			EGwItemAttachment *attach = (EGwItemAttachment *)al->data;
+			if (!g_ascii_strcasecmp (attach->name, "Mime.822")) {
+				if (attach->size > MAX_ATTACHMENT_SIZE) {
+					long count = 0;
+					int i, t_len=0, offset=0, t_offset=0;
+					char *t_attach = NULL;
+					GString *gstr = g_string_new (NULL);
+
+					count = (attach->size)/(1024*1024);
+					count++;
+					len = 0;
+					for (i = 0; i<count; i++) {
+						status = e_gw_connection_get_attachment_base64 (cnc, 
+								attach->id, t_offset, MAX_ATTACHMENT_SIZE, 
+								(const char **)&t_attach, &t_len, &offset);
+						if (status == E_GW_CONNECTION_STATUS_OK) {
+							gstr = g_string_append (gstr, t_attach);
+							t_offset = offset;
+							g_free (t_attach);
+							t_attach = NULL;
+							t_len = 0;
+						}
+					}
+					body = soup_base64_decode (gstr->str, &len);
+					body_len = len;
+					g_string_free (gstr, TRUE);
+				} else {
+					status = e_gw_connection_get_attachment (cnc, 
+							attach->id, 0, -1, 
+							(const char **)&attachment, &len);
+					if (status != E_GW_CONNECTION_STATUS_OK) {
+						g_warning ("Could not get attachment\n");
+						camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Could not get message"));
+						return NULL;
+					}
+					body = g_strdup (attachment);
+					body_len = len;
+					g_free (attachment);
+				}
+				has_mime_822 = TRUE;
+			} 
+		}
+
 	}//if attach_list
 
 
 	msg = camel_mime_message_new ();
-	multipart = camel_multipart_new ();
+	if (has_mime_822) {
+		temp_stream = camel_stream_mem_new_with_buffer (body, body_len);
+		if (camel_data_wrapper_construct_from_stream ((CamelDataWrapper *) msg, temp_stream) == -1) {
+			camel_object_unref (msg);
+			camel_object_unref (temp_stream);
+			msg = NULL;
+			goto end;
+		}
+	} else {
+		multipart = camel_multipart_new ();
+	}
 
 	camel_mime_message_set_message_id (msg, uid);
 	type = e_gw_item_get_item_type (item);
@@ -1432,9 +1663,11 @@
 			g_free (value);
 		}
 	}
-
-	groupwise_populate_msg_body_from_item (cnc, multipart, item, body);
 	
+	if (has_mime_822)
+		goto end;
+	else
+		groupwise_populate_msg_body_from_item (cnc, multipart, item, body);
 	/*Set recipient details*/
 	groupwise_msg_set_recipient_list (msg, item);
 	groupwise_populate_details_from_item (msg, item);
@@ -1449,11 +1682,15 @@
 			int len = 0;
 			CamelMimePart *part;
 			EGwItem *temp_item;
+			is_base64_encoded = FALSE;
 
+			if (attach->contentid && (is_text_html_embed != TRUE))
+				is_text_html_embed = TRUE;
 			if ( !g_ascii_strcasecmp (attach->name, "TEXT.htm") ||
-			     !g_ascii_strcasecmp (attach->name, "Mime.822"))
+			     !g_ascii_strcasecmp (attach->name, "Mime.822") ||
+			     !g_ascii_strcasecmp (attach->name, "Header"))
 				continue;
-			
+
 			if ( (attach->item_reference) && (!g_ascii_strcasecmp (attach->item_reference, "1")) ) {
 				CamelMimeMessage *temp_msg = NULL;
 				status = e_gw_connection_get_item (cnc, container_id, attach->id, "default distribution recipient message attachments subject notification created recipientStatus status startDate", &temp_item);
@@ -1468,129 +1705,152 @@
 					camel_data_wrapper_set_mime_type_field(CAMEL_DATA_WRAPPER (temp_msg), ct);
 					camel_content_type_unref(ct);
 					camel_medium_set_content_object ( CAMEL_MEDIUM (part),CAMEL_DATA_WRAPPER(temp_msg));
+					
 					camel_multipart_add_part (multipart,part);
 					camel_object_unref (temp_msg);
 					camel_object_unref (part);
 				}
 				g_object_unref (temp_item);
 			} else {
-				status = e_gw_connection_get_attachment (cnc, 
-						attach->id, 0, -1, 
-						(const char **)&attachment, &len);
+				if (attach->size > MAX_ATTACHMENT_SIZE) {
+					long count = 0;
+					int i, t_len=0, offset=0, t_offset=0;
+					char *t_attach = NULL;
+					GString *gstr = g_string_new (NULL);
+
+					count = (attach->size)/(1024*1024);
+					count++;
+					len = 0;
+					for (i = 0; i<count; i++) {
+						status = e_gw_connection_get_attachment_base64 (cnc, 
+								attach->id, t_offset, MAX_ATTACHMENT_SIZE, 
+								(const char **)&t_attach, &t_len, &offset);
+						if (status == E_GW_CONNECTION_STATUS_OK) {
+							gstr = g_string_append (gstr, t_attach);
+							t_offset = offset;
+							g_free (t_attach);
+							t_attach = NULL;
+							t_len = 0;
+						}
+					}
+					attachment = soup_base64_decode (gstr->str, &len);
+					g_string_free (gstr, TRUE);
+					is_base64_encoded = FALSE;
+				} else {
+					status = e_gw_connection_get_attachment (cnc, 
+							attach->id, 0, -1, 
+							(const char **)&attachment, &len);
+				}
 				if (status != E_GW_CONNECTION_STATUS_OK) {
 					g_warning ("Could not get attachment\n");
 					continue;
 				}
 				if (attachment && (len !=0) ) {
 					part = camel_mime_part_new ();
-					if (attach->contentType) {	
-						if (!strcmp (attach->contentType, "application/pgp-signature")) {
-							camel_mime_part_set_filename(part, g_strdup(attach->name));
-							camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart), "multipart/signed");
-							has_boundary = TRUE;
-							camel_content_type_set_param(CAMEL_DATA_WRAPPER (multipart)->mime_type, "protocol", attach->contentType);
-						} else if (!strcmp (attach->contentType, "application/pgp-encrypted")) {
-							camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart), "multipart/encrypted");
-							has_boundary = TRUE;
-							camel_content_type_set_param(CAMEL_DATA_WRAPPER (multipart)->mime_type, "protocol", attach->contentType);
-						} else if ( !strcmp (attach->name, "encrypted.asc") &&
-								!strcmp (attach->contentType, "application/octet-stream")) {
-							camel_mime_part_set_filename(part, g_strdup(attach->name));
-							camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart), "multipart/encrypted");
-							has_boundary = TRUE;
-							camel_content_type_set_param(CAMEL_DATA_WRAPPER (multipart)->mime_type, "protocol", "application/pgp-encrypted");
-						} else {
-							camel_mime_part_set_filename(part, g_strdup(attach->name));
-							camel_mime_part_set_content_id (part, attach->id);
-							if (!has_boundary)
-								camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart), "multipart/digest");
+					/*multiparts*/
+					if (is_text_html_embed) {
+						camel_mime_part_set_filename(part, g_strdup(attach->name));
+						camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart), "multipart/related");
+						has_boundary = TRUE;
+						camel_content_type_set_param(CAMEL_DATA_WRAPPER (multipart)->mime_type, "type", "multipart/alternative");
+						if (attach->contentid) {
+							gchar **t;
+							t= g_strsplit_set (attach->contentid, "<>", -1);
+							if (!t[1]) 
+								camel_mime_part_set_content_id (part, attach->contentid);
+							else 
+								camel_mime_part_set_content_id (part, t[1]);
+							g_strfreev (t);
+							camel_mime_part_set_content_location (part, attach->name);
 						}
 					} else {
 						camel_mime_part_set_filename(part, g_strdup(attach->name));
-						camel_mime_part_set_content_id (part, attach->id);
-						if (!has_boundary)
-							camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart), "multipart/digest");
+						camel_mime_part_set_content_id (part, attach->contentid);
 					}
 
-					camel_multipart_set_boundary(multipart, NULL);
-
 					//camel_mime_part_set_filename(part, g_strdup(attach->name));
-					camel_mime_part_set_content(part, attachment, len, attach->contentType);
+					if (attach->contentType) {
+						if (is_base64_encoded)
+							camel_mime_part_set_encoding (part, CAMEL_TRANSFER_ENCODING_BASE64);
+						camel_mime_part_set_content(part, attachment, len, attach->contentType);
+						camel_content_type_set_param (((CamelDataWrapper *) part)->mime_type, "name", attach->name);
+					} else {
+							camel_mime_part_set_content(part, attachment, len, "text/plain");
+					}
+					if (!has_boundary)
+						camel_data_wrapper_set_mime_type(CAMEL_DATA_WRAPPER (multipart),"multipart/digest");
 
+					camel_multipart_set_boundary(multipart, NULL);
 					camel_multipart_add_part (multipart, part);
 
 					camel_object_unref (part);
 					g_free (attachment);
-				}
+				} /* if attachment */
 			}
-		}
+		} /* end of for*/
 
-
-	}
+	}/* if attach_list */
 	/********************/
 
 	camel_medium_set_content_object(CAMEL_MEDIUM (msg), CAMEL_DATA_WRAPPER(multipart));
-
 	camel_object_unref (multipart);
 
+end:
 	if (body)
 		g_free (body);
 
 	return msg;
 }
 
-static gint 
-string_cmp(gconstpointer a, gconstpointer b)
-{
-	int ret;
-	char **tmp1, **tmp2;
-	
-	tmp1 = g_strsplit ((const char *)a, "@", -1);
-	tmp2 = g_strsplit ((const char *)b, "@", -1);
-/*	g_print ("************\n");
-	g_print ("%s\n%s\n",tmp1[0], tmp2[0]);
-	g_print ("************\n");*/
-	ret = strcmp (tmp1[0], tmp2[0]);
-	g_strfreev (tmp1);
-	g_strfreev (tmp2);
-	return ret;
-}
-
 static void
-gw_update_all_items ( CamelFolder *folder, GSList *item_list, CamelException *ex) 
+gw_update_all_items (CamelFolder *folder, GList *item_list, CamelException *ex) 
 {
 	CamelGroupwiseFolder *gw_folder = CAMEL_GROUPWISE_FOLDER (folder);
-	GPtrArray *summary = camel_folder_get_summary (folder);
+	GPtrArray *summary = NULL;
 	int index = 0;
-	GSList *item_ids = NULL, *l = NULL;
+	GList *temp;
 	CamelFolderChangeInfo *changes = NULL;
+	CamelMessageInfo *info; 
+	changes = camel_folder_change_info_new ();
 
-	changes = camel_folder_change_info_new ();
+	item_list = g_list_reverse (item_list);
+
+	summary = camel_folder_get_summary (folder);
 	/*item_ids : List of ids from the summary*/
 	while (index < summary->len) {
-		CamelMessageInfo *info = g_ptr_array_index (summary, index);
-		item_ids = g_slist_append (item_ids, info->uid);
-		index ++;
-	}
-	l = item_ids;
+		info = g_ptr_array_index (summary, index);
+		temp = NULL; 
 
-	/*item_list : List of ids from the server*/
-	for (; item_ids != NULL ; item_ids = g_slist_next (item_ids)) {
-		GSList *temp = NULL;
-		temp = g_slist_find_custom (item_list, (const char *)item_ids->data, (GCompareFunc) string_cmp);
+		if (item_list) {
+			temp = g_list_find_custom (item_list, (const char *)info->uid, (GCompareFunc) strcmp);
+		}
+
 		if (!temp) {
-			//g_print ("Deleting:%s\n", (const char *)item_ids->data);
 			CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
-			camel_folder_summary_remove_uid (folder->summary, (const char *)item_ids->data);
-			camel_data_cache_remove(gw_folder->cache, "cache", (const char *)item_ids->data, ex);
-			camel_folder_change_info_remove_uid(changes, (const char *)item_ids->data);
+			camel_folder_summary_remove_uid (folder->summary, info->uid);
+			camel_data_cache_remove (gw_folder->cache, "cache", info->uid, ex);
+			camel_folder_change_info_remove_uid (changes, info->uid);
 			CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
-		} 
+		} else { 
+			item_list = g_list_delete_link (item_list, temp);
+		}
+		index ++;
 	}
+
 	camel_object_trigger_event (folder, "folder_changed", changes);
 
+	if (item_list) {
+		CamelGroupwiseStore *gw_store = CAMEL_GROUPWISE_STORE (folder->parent_store);
+
+		CAMEL_SERVICE_LOCK (gw_store, connect_lock);
+		gw_update_cache (folder, item_list, ex, TRUE);	
+		CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+
+		g_list_foreach (item_list, (GFunc)g_free, NULL);	
+		g_list_free (item_list);
+	}
+
 	camel_folder_free_summary (folder, summary);
-	g_slist_free (l);
 }
 
 static void
@@ -1602,13 +1862,12 @@
 	CamelGroupwiseStore *gw_store= CAMEL_GROUPWISE_STORE(folder->parent_store);
 	CamelGroupwiseStorePrivate  *priv = gw_store->priv;
 	CamelOfflineStore *offline = (CamelOfflineStore *) folder->parent_store;
-	CamelAddress *recipients;
 	EGwConnectionStatus status;
-	EGwConnection *cnc = cnc_lookup (priv);
+	EGwConnection *cnc;
 	EGwItem *item;
 	char *id;
 	gboolean is_ok = FALSE;
-	
+
 	if (!strcmp (folder->name, RECEIVED))
 		is_ok = TRUE;
 	if(!strcmp (folder->name, SENT))
@@ -1624,33 +1883,29 @@
 		camel_groupwise_journal_append ((CamelGroupwiseJournal *) ((CamelGroupwiseFolder *)folder)->journal, message, info, appended_uid, ex);
 		return;
 	}
+	cnc = cnc_lookup (priv);
+
 	CAMEL_SERVICE_LOCK (folder->parent_store, connect_lock);
 	/*Get the container id*/
 	container_id = camel_groupwise_store_container_id_lookup (gw_store, folder->full_name) ;
-
-	/* FIXME Separate To/CC/BCC? */
-	recipients = CAMEL_ADDRESS (camel_internet_address_new ());
-	camel_address_cat (recipients, CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_TO)));
-	camel_address_cat (recipients, CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_CC)));
-	camel_address_cat (recipients, CAMEL_ADDRESS (camel_mime_message_get_recipients (message, CAMEL_RECIPIENT_TYPE_BCC)));
-
-	item = camel_groupwise_util_item_from_message (cnc, message, CAMEL_ADDRESS (message->from), recipients);
+	
+	item = camel_groupwise_util_item_from_message (cnc, message, CAMEL_ADDRESS (message->from));
 	/*Set the source*/
 	if (!strcmp (folder->name, RECEIVED))
-			e_gw_item_set_source (item, "received");
+		e_gw_item_set_source (item, "received");
 	if (!strcmp (folder->name, SENT))
-			e_gw_item_set_source (item, "sent");
+		e_gw_item_set_source (item, "sent");
 	if (!strcmp (folder->name, DRAFT))
-			e_gw_item_set_source (item, "draft");
+		e_gw_item_set_source (item, "draft");
 	if (!strcmp (folder->name, PERSONAL))
-			e_gw_item_set_source (item, "personal");
+		e_gw_item_set_source (item, "personal");
 	/*set container id*/
 	e_gw_item_set_container_id (item, container_id);
 
 	status = e_gw_connection_create_item (cnc, item, &id);
 	if (status != E_GW_CONNECTION_STATUS_OK) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create message: %s"),
-				      e_gw_connection_get_error_message (status));
+				e_gw_connection_get_error_message (status));
 
 		if (appended_uid)
 			*appended_uid = NULL;
@@ -1662,7 +1917,7 @@
 	g_message ("Adding %s to %s", id, container_id);
 	if (status != E_GW_CONNECTION_STATUS_OK) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot append message to folder `%s': %s"),
-				      folder->full_name, e_gw_connection_get_error_message (status));
+				folder->full_name, e_gw_connection_get_error_message (status));
 
 		if (appended_uid)
 			*appended_uid = NULL;
@@ -1695,8 +1950,8 @@
 
 static void
 groupwise_transfer_messages_to (CamelFolder *source, GPtrArray *uids, 
-				CamelFolder *destination, GPtrArray **transferred_uids, 
-				gboolean delete_originals, CamelException *ex)
+		CamelFolder *destination, GPtrArray **transferred_uids, 
+		gboolean delete_originals, CamelException *ex)
 {
 	int count, index = 0;
 	GList *item_ids = NULL;
@@ -1705,10 +1960,10 @@
 	CamelOfflineStore *offline = (CamelOfflineStore *) destination->parent_store;
 	CamelGroupwiseStorePrivate  *priv = gw_store->priv;
 	EGwConnectionStatus status;
-	EGwConnection *cnc = cnc_lookup (priv);
+	EGwConnection *cnc;
 
- 	count = camel_folder_summary_count (destination->summary);
- 	qsort (uids->pdata, uids->len, sizeof (void *), uid_compar);
+	count = camel_folder_summary_count (destination->summary);
+	qsort (uids->pdata, uids->len, sizeof (void *), uid_compar);
 
 	while (index < uids->len) {
 		item_ids = g_list_append (item_ids, g_ptr_array_index (uids, index));
@@ -1723,7 +1978,7 @@
 	else
 		source_container_id = NULL;
 	dest_container_id = camel_groupwise_store_container_id_lookup (gw_store, destination->full_name) ;
-	
+
 	CAMEL_SERVICE_LOCK (source->parent_store, connect_lock);
 	/* check for offline operation */
 	if (offline->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL) {
@@ -1731,33 +1986,37 @@
 		CamelMimeMessage *message;
 		GList *l;
 		int i;
-		
+
 		for (l = item_ids, i = 0; l; l = l->next, i++) {
 			CamelMessageInfo *info;
 
 			if (!(info = camel_folder_summary_uid (source->summary, uids->pdata[i])))
 				continue;
-			
+
 			if (!(message = groupwise_folder_get_message (source, camel_message_info_uid (info), ex)))
 				break;
-			
+
 			camel_groupwise_journal_transfer (journal, (CamelGroupwiseFolder *)source, message, info, uids->pdata[i], NULL, ex);
 			camel_object_unref (message);
-			
+
 			if (camel_exception_is_set (ex))
 				break;
-			
+
 			if (delete_originals)
-				camel_folder_set_message_flags (source, camel_message_info_uid (info),
-								CAMEL_MESSAGE_DELETED, CAMEL_MESSAGE_DELETED);
+				camel_folder_delete_message(source, camel_message_info_uid (info));
 		}
 
 		CAMEL_SERVICE_UNLOCK (source->parent_store, connect_lock);
 		return;
 	}
-	
+
+	cnc = cnc_lookup (priv);
+
 	index = 0;
 	while (index < uids->len) {
+		int count;
+		count = camel_folder_summary_count (destination->summary);
+
 		if (delete_originals) 
 			status = e_gw_connection_move_item (cnc, (const char *)uids->pdata[index], 
 					dest_container_id, source_container_id);
@@ -1765,35 +2024,18 @@
 			status = e_gw_connection_move_item (cnc, (const char *)uids->pdata[index], 
 					dest_container_id, NULL);
 		if (status == E_GW_CONNECTION_STATUS_OK) {
-			const char *old_uid = (const char*)uids->pdata[index];
-			char **tmp;
-			guint32 temp_flags = 0;
-			CamelGroupwiseMessageInfo *src_info = (CamelGroupwiseMessageInfo *)camel_folder_summary_uid (source->summary, (const char*)uids->pdata[index]);
-			
-			/* we don't want to blindly copy the info: reset some flags not suitable for destination*/
-			if (!strcmp(source->full_name, JUNK_FOLDER))
-				camel_folder_set_message_flags (source, old_uid, CAMEL_GW_MESSAGE_JUNK|CAMEL_MESSAGE_JUNK|CAMEL_MESSAGE_JUNK_LEARN, 0);
-			else if (!strcmp(destination->full_name, JUNK_FOLDER))
-				camel_folder_set_message_flags (source, old_uid, CAMEL_MESSAGE_JUNK|CAMEL_GW_MESSAGE_JUNK, CAMEL_GW_MESSAGE_JUNK);
-
-			CamelGroupwiseMessageInfo *dest_info = (CamelGroupwiseMessageInfo *)camel_message_info_clone((CamelMessageInfo *)src_info);
-			tmp = g_strsplit (old_uid, ":", -1);
-			dest_info->info.uid = g_strdup_printf ("%s:%s",tmp[0], dest_container_id);
-			temp_flags = camel_folder_get_message_flags (source, (const char *)uids->pdata[index]);
-			camel_folder_set_message_flags (destination, (const char *)dest_info->info.uid, temp_flags, temp_flags);
-			camel_folder_summary_add (destination->summary, (CamelMessageInfo *)dest_info);
-			//camel_message_info_free(dest_info);
-			g_strfreev (tmp);
-			if (delete_originals) {
-				camel_folder_set_message_flags (source, (const char *)uids->pdata[index],
-						CAMEL_MESSAGE_DELETED, CAMEL_MESSAGE_DELETED);
-
-			}
+			if (delete_originals) 
+				camel_folder_delete_message(source, uids->pdata[index]);
 		} else {
 			g_warning ("Warning!! Could not move item : %s\n", (char *)uids->pdata[index]);
 		}
 		index ++;
 	}
+	/* Refresh the destination folder, if its not refreshed already */
+	if (gw_store->current_folder != destination || 
+			camel_folder_summary_count (destination->summary) == count)
+		camel_folder_refresh_info (destination, ex);
+
 	camel_folder_summary_touch (source->summary);
 	camel_folder_summary_touch (destination->summary);
 
@@ -1816,8 +2058,10 @@
 	CamelFolderChangeInfo *changes;
 	int i, max;
 	gboolean delete = FALSE;
+	GList *deleted_items, *deleted_head;
 	
-	
+
+	deleted_items = deleted_head = NULL;
 	cnc = cnc_lookup (priv);
 	if (!cnc)
 		return;
@@ -1826,16 +2070,17 @@
 		CAMEL_SERVICE_LOCK (groupwise_store, connect_lock);
 		status = e_gw_connection_purge_deleted_items (cnc);
 		if (status == E_GW_CONNECTION_STATUS_OK) {
-			camel_folder_summary_clear (folder->summary);
-			camel_folder_summary_save (folder->summary);
+			camel_folder_freeze (folder);
+			groupwise_summary_clear (folder->summary, TRUE);
+			camel_folder_thaw (folder);
 		} else
 			g_warning ("Could not Empty Trash\n");
 		CAMEL_SERVICE_UNLOCK (groupwise_store, connect_lock);
 		return;
 	}
-	
+
 	changes = camel_folder_change_info_new ();
-	
+
 	container_id =  g_strdup (camel_groupwise_store_container_id_lookup (groupwise_store, folder->full_name)) ;
 
 	max = camel_folder_summary_count (folder->summary);
@@ -1843,39 +2088,74 @@
 		info = camel_folder_summary_index (folder->summary, i);
 		ginfo = (CamelGroupwiseMessageInfo *) info;
 		if (ginfo && (ginfo->info.flags & CAMEL_MESSAGE_DELETED)) {
-			const char *uid = camel_message_info_uid (info);
-			CAMEL_SERVICE_LOCK (groupwise_store, connect_lock);
-			status = e_gw_connection_remove_item (cnc, container_id, uid);
-			if (status == E_GW_CONNECTION_STATUS_OK) {
+
+			if (deleted_items)
+				deleted_items = g_list_prepend (deleted_items, (char *)camel_message_info_uid (info));
+			else {
+				g_list_free (deleted_head);
+				deleted_head = NULL;
+				deleted_head = deleted_items = g_list_prepend (deleted_items, (char *)camel_message_info_uid (info));
+			}
+			if (g_list_length (deleted_items) == GROUPWISE_BULK_DELETE_LIMIT ) {
+				/* Read the FIXME below */
+				CAMEL_SERVICE_LOCK (groupwise_store, connect_lock);
+				status = e_gw_connection_remove_items (cnc, container_id, deleted_items);
+				CAMEL_SERVICE_UNLOCK (groupwise_store, connect_lock);
+				if (status == E_GW_CONNECTION_STATUS_OK) {
+					char *uid;
+					while (deleted_items) {
+						uid = (char *)deleted_items->data;
+						CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
+						camel_folder_change_info_remove_uid (changes, uid);
+						camel_folder_summary_remove_uid (folder->summary, uid);
+						camel_data_cache_remove(gw_folder->cache, "cache", uid, ex);
+						CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
+						deleted_items = g_list_next (deleted_items);
+						max -= GROUPWISE_BULK_DELETE_LIMIT;
+						i -= GROUPWISE_BULK_DELETE_LIMIT;
+					}
+				}
+				delete = TRUE;
+			}
+		}
+		camel_message_info_free (info);
+	}
+
+	if (deleted_items) {
+		/* FIXME: Put these in a function and reuse it inside the above loop, here and in groupwise_sync*/
+		CAMEL_SERVICE_LOCK (groupwise_store, connect_lock);
+		status = e_gw_connection_remove_items (cnc, container_id, deleted_items);
+		CAMEL_SERVICE_UNLOCK (groupwise_store, connect_lock);
+		if (status == E_GW_CONNECTION_STATUS_OK) {
+			char *uid;
+			while (deleted_items) {
+				uid = (char *)deleted_items->data;
 				CAMEL_GROUPWISE_FOLDER_LOCK (folder, cache_lock);
-				camel_folder_change_info_remove_uid (changes, (char *) uid);
-				camel_folder_summary_remove (folder->summary, info);
+				camel_folder_change_info_remove_uid (changes, uid);
+				camel_folder_summary_remove_uid (folder->summary, uid);
 				camel_data_cache_remove(gw_folder->cache, "cache", uid, ex);
 				CAMEL_GROUPWISE_FOLDER_UNLOCK (folder, cache_lock);
-				delete = TRUE;
-				i--;  max--;
+				deleted_items = g_list_next (deleted_items);
 			}
-			CAMEL_SERVICE_UNLOCK (groupwise_store, connect_lock);
 		}
-		camel_message_info_free (info);
+		delete = TRUE;
+		g_list_free (deleted_head);
 	}
 
 	if (delete)
 		camel_object_trigger_event (CAMEL_OBJECT (folder), "folder_changed", changes);
-	
-	
+
 	g_free (container_id);
 	camel_folder_change_info_free (changes);
 }
 
-
 static void
 camel_groupwise_folder_class_init (CamelGroupwiseFolderClass *camel_groupwise_folder_class)
 {
 	CamelFolderClass *camel_folder_class = CAMEL_FOLDER_CLASS (camel_groupwise_folder_class);
-	
+
 	parent_class = CAMEL_OFFLINE_FOLDER_CLASS (camel_type_get_global_classfuncs (camel_offline_folder_get_type ()));
-	
+
 	((CamelObjectClass *) camel_groupwise_folder_class)->getv = gw_getv;
 
 	camel_folder_class->get_message = groupwise_folder_get_message;
@@ -1901,9 +2181,9 @@
 		CAMEL_MESSAGE_DRAFT | CAMEL_MESSAGE_FLAGGED | CAMEL_MESSAGE_SEEN;
 
 	folder->folder_flags = CAMEL_FOLDER_HAS_SUMMARY_CAPABILITY | CAMEL_FOLDER_HAS_SEARCH_CAPABILITY;
-	
-	gw_folder->priv = g_malloc0(sizeof(*gw_folder->priv));
 
+	gw_folder->priv = g_malloc0 (sizeof(*gw_folder->priv));
+
 #ifdef ENABLE_THREADS
 	gw_folder->priv->search_lock = e_mutex_new(E_MUTEX_SIMPLE);
 	gw_folder->priv->cache_lock = e_mutex_new(E_MUTEX_REC);
@@ -1929,20 +2209,20 @@
 camel_groupwise_folder_get_type (void)
 {
 	static CamelType camel_groupwise_folder_type = CAMEL_INVALID_TYPE;
-	
-	
+
+
 	if (camel_groupwise_folder_type == CAMEL_INVALID_TYPE) {
 		camel_groupwise_folder_type =
 			camel_type_register (camel_offline_folder_get_type (),
-					     "CamelGroupwiseFolder",
-					     sizeof (CamelGroupwiseFolder),
-					     sizeof (CamelGroupwiseFolderClass),
-					     (CamelObjectClassInitFunc) camel_groupwise_folder_class_init,
-					     NULL,
-					     (CamelObjectInitFunc) camel_groupwise_folder_init,
-					     (CamelObjectFinalizeFunc) camel_groupwise_folder_finalize);
+					"CamelGroupwiseFolder",
+					sizeof (CamelGroupwiseFolder),
+					sizeof (CamelGroupwiseFolderClass),
+					(CamelObjectClassInitFunc) camel_groupwise_folder_class_init,
+					NULL,
+					(CamelObjectInitFunc) camel_groupwise_folder_init,
+					(CamelObjectFinalizeFunc) camel_groupwise_folder_finalize);
 	}
-	
+
 	return camel_groupwise_folder_type;
 }
 
@@ -1952,7 +2232,7 @@
 	CamelFolder *folder = (CamelFolder *)object;
 	int i, count = 0;
 	guint32 tag;
-	
+
 	for (i=0 ; i<args->argc ; i++) {
 		CamelArgGet *arg = &args->argv[i];
 
@@ -1980,7 +2260,7 @@
 		return ((CamelObjectClass *)parent_class)->getv(object, ex, args);
 
 	return 0;
-		
+
 }
 
 void 
@@ -1999,7 +2279,7 @@
 	gstr = g_string_append (gstr, "BEGIN:VCALENDAR\n");
 	gstr = g_string_append (gstr, "METHOD:REQUEST\n");
 	gstr = g_string_append (gstr, "BEGIN:VEVENT\n");
-	
+
 	if ((recur_key = e_gw_item_get_recurrence_key (item)) != 0) {
 		char *recur_k = g_strdup_printf ("%d", recur_key); 
 
@@ -2013,7 +2293,7 @@
 	g_string_append_printf (gstr, "X-GWITEM-TYPE:APPOINTMENT\n");
 	g_string_append_printf (gstr, "DTSTART:%s\n",e_gw_item_get_start_date (item));
 	g_string_append_printf (gstr, "SUMMARY:%s\n", e_gw_item_get_subject (item));
-	
+
 	temp = e_gw_item_get_message (item);
 	if (temp) {
 		g_string_append(gstr, "DESCRIPTION:");
@@ -2035,8 +2315,8 @@
 	org = e_gw_item_get_organizer (item);
 	if (org)
 		g_string_append_printf (gstr, "ORGANIZER;CN= %s;ROLE= CHAIR;\n MAILTO:%s\n", 
-				        org->display_name, org->email);
-	
+				org->display_name, org->email);
+
 	recp_list = e_gw_item_get_recipient_list (item);
 	if (recp_list) {
 		GSList *rl ;
@@ -2048,14 +2328,14 @@
 					recp->display_name, recp->email);
 		}
 	}
-	
+
 	g_string_append_printf (gstr, "DTEND:%s\n", e_gw_item_get_end_date (item));
 
 	temp = NULL;
 	temp = e_gw_item_get_place (item);
 	if (temp)
 		g_string_append_printf (gstr, "LOCATION:%s\n", temp);
-	
+
 	temp = NULL;
 	temp = e_gw_item_get_task_priority (item);
 	if (temp)
@@ -2073,10 +2353,10 @@
 	}
 	gstr = g_string_append (gstr, "END:VEVENT\n");
 	gstr = g_string_append (gstr, "END:VCALENDAR\n");
-	
+
 	*str = gstr->str;
 	*len = gstr->len;
-	
+
 	g_string_free (gstr, FALSE);
 	g_strfreev (tmp);
 }
@@ -2089,7 +2369,7 @@
 	GString *gstr = g_string_new (NULL);
 	char **tmp = NULL;
 	const char *temp = NULL;
-	
+
 	tmp = g_strsplit (e_gw_item_get_id (item), "@", -1);
 
 	gstr = g_string_append (gstr, "BEGIN:VCALENDAR\n");
@@ -2107,8 +2387,8 @@
 	org = e_gw_item_get_organizer (item);
 	if (org)
 		g_string_append_printf (gstr, "ORGANIZER;CN= %s;ROLE= CHAIR;\n MAILTO:%s\n", 
-				        org->display_name, org->email);
-	
+				org->display_name, org->email);
+
 	recp_list = e_gw_item_get_recipient_list (item);
 	if (recp_list) {
 		GSList *rl;
@@ -2120,13 +2400,13 @@
 					recp->display_name, recp->email);
 		}
 	}
-	
+
 	g_string_append_printf (gstr, "DTEND:%s\n", e_gw_item_get_end_date (item));
 
 	temp = e_gw_item_get_place (item);
 	if (temp)
 		g_string_append_printf (gstr, "LOCATION:%s\n", temp);
-	
+
 	temp = NULL;
 	temp = e_gw_item_get_task_priority (item);
 	if (temp)
@@ -2138,13 +2418,13 @@
 		g_string_append_printf (gstr, "DUE:%s\n", temp);
 	gstr = g_string_append (gstr, "END:VTODO\n");
 	gstr = g_string_append (gstr, "END:VCALENDAR\n");
-	
 
+
 	*str = g_strdup (gstr->str);
 	*len = gstr->len;
-	
+
 	g_string_free (gstr, TRUE);
 	g_strfreev (tmp);
 }
 
-
+/** End **/
Index: camel/providers/groupwise/camel-groupwise-folder.h
===================================================================
--- camel/providers/groupwise/camel-groupwise-folder.h	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-folder.h	(working copy)
@@ -40,6 +40,8 @@
 #include <camel/camel-internet-address.h>
 #include <camel/camel-data-cache.h>
 #include <camel/camel-multipart.h>
+#include <camel/camel-multipart-signed.h>
+#include <camel/camel-multipart-encrypted.h>
 #include <camel/camel-offline-journal.h>
 
 #include "camel-groupwise-summary.h"
Index: camel/providers/groupwise/Makefile.am
===================================================================
--- camel/providers/groupwise/Makefile.am	(revision 444)
+++ camel/providers/groupwise/Makefile.am	(working copy)
@@ -38,8 +38,8 @@
 
 libcamelgroupwise_la_LDFLAGS = -avoid-version -module $(NO_UNDEFINED)
 libcamelgroupwise_la_LIBADD =                                            \
-        $(top_builddir)/servers/groupwise/libegroupwise-$(API_VERSION).la           \
-	$(top_builddir)/libedataserver/libedataserver-$(API_VERSION).la             \
+        $(top_builddir)/servers/groupwise/libegroupwise-1.2.la           \
+	$(top_builddir)/libedataserver/libedataserver-1.2.la             \
 	$(top_builddir)/camel/libcamel-provider-1.2.la	                 \
 	$(top_builddir)/camel/libcamel-1.2.la		                 \
 	$(CAMEL_LIBS)                                                    \
Index: camel/providers/groupwise/camel-groupwise-transport.c
===================================================================
--- camel/providers/groupwise/camel-groupwise-transport.c	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-transport.c	(working copy)
@@ -141,18 +141,24 @@
 		   CamelAddress *recipients,
 		   CamelException *ex)
 {
-	CamelService *service = CAMEL_SERVICE(transport);
+	CamelService *service;
 	CamelStore *store =  NULL;
 	CamelGroupwiseStore *groupwise_store = NULL;
 	CamelGroupwiseStorePrivate *priv = NULL;
 	EGwItem *item ,*temp_item=NULL;
 	EGwConnection *cnc = NULL;
-	EGwConnectionStatus status;
+	EGwConnectionStatus status = 0;
 	GSList *sent_item_list = NULL;
 	char *url = NULL;
 	const char *reply_request = NULL;
 	EGwItemLinkInfo *info = NULL;
 
+	if (!transport) {
+		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_CANT_AUTHENTICATE, _("Authentication failed"));
+		return FALSE;
+	}
+
+	service = CAMEL_SERVICE(transport);
 	url = camel_url_to_string (service->url,
 			           (CAMEL_URL_HIDE_PASSWORD |
 				    CAMEL_URL_HIDE_PARAMS   |
@@ -178,10 +184,9 @@
 		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_CANT_AUTHENTICATE, _("Authentication failed"));
 		return FALSE;
 	}
-
-
-	item = camel_groupwise_util_item_from_message (cnc, message, from, recipients);
 	
+	item = camel_groupwise_util_item_from_message (cnc, message, from);
+	
 	reply_request = (char *)camel_medium_get_header (CAMEL_MEDIUM (message), "In-Reply-To");
 	if (reply_request) {
 		char *id;
@@ -206,11 +211,17 @@
 	if (status != E_GW_CONNECTION_STATUS_OK) {
 		g_warning (" Error Sending mail");
 		camel_operation_end (NULL);
+		e_gw_item_set_link_info (item, NULL);
 		g_object_unref (item);
 		if (temp_item)
 			g_object_unref (temp_item);
-		camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,_("Could not send message: %s"),_("Unknown error"));
 
+		/* FIXME: 58652 should be changed with an enum.*/
+		if (status == 58652)
+			camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE, _("You have exceeded this account's storage limit. Your messages are queued in your Outbox. Resend by pressing Send/Receive after deleting/archiving some of your mail.\n"));
+		else
+			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,_("Could not send message: %s"),_("Unknown error"));
+		status = 0;
 		return FALSE;
 	}
 	e_gw_item_set_link_info (item, NULL);
Index: camel/providers/groupwise/camel-groupwise-store.c
===================================================================
--- camel/providers/groupwise/camel-groupwise-store.c	(revision 444)
+++ camel/providers/groupwise/camel-groupwise-store.c	(working copy)
@@ -24,34 +24,33 @@
  *
  */
 
-
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
-#include <glib.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include "camel/camel-session.h"
+#include "camel/camel-debug.h"
+#include "camel/camel-i18n.h"
+#include "camel/camel-types.h"
+#include "camel/camel-folder.h" 
+#include "camel/camel-private.h"
+#include "camel/camel-net-utils.h"
+
 #include "camel-groupwise-store.h"
 #include "camel-groupwise-summary.h"
 #include "camel-groupwise-store-summary.h"
 #include "camel-groupwise-folder.h"
 #include "camel-groupwise-utils.h"
 
-#include "camel-session.h"
-#include "camel-debug.h"
-#include "camel-i18n.h"
-#include "camel-types.h"
-#include "camel-folder.h" 
-#include "camel-private.h"
-#include "camel-net-utils.h"
-
 #define d(x) 
 #define CURSOR_ITEM_LIMIT 100
 #define JUNK_ENABLE 1
@@ -104,8 +103,12 @@
 				     _("Host or user not available in url"));
 	}
 
-	//store->flags = 0; 
-	groupwise_store->list_loaded = FALSE;
+	/*XXX: The number 3 assigned to the list_loaded variable denotes
+	 * the number of times the get_folder_info is called during startup.
+	 * We are just trying to minimize the call.
+	 * This is a dirty hack. But it *WORKS*
+	 */
+	groupwise_store->list_loaded = 3;
 	
 	/*storage path*/
 	priv->storage_path = camel_session_get_storage_path (session, service, ex);
@@ -124,9 +127,6 @@
 	priv->server_name = g_strdup (url->host);
 	priv->user = g_strdup (url->user);
 
-	/*remove the sync option*/
-/*	if (camel_url_get_param ((service->url, "sync_offline") != NULL)
-			camel_url_set_param (service->url, "sync_offline", NULL);*/
 	/*base url*/
 	priv->base_url = camel_url_to_string (service->url, (CAMEL_URL_HIDE_PASSWORD |
 						       CAMEL_URL_HIDE_PARAMS   |
@@ -146,9 +146,9 @@
 		store->flags |= CAMEL_STORE_FILTER_INBOX;
 	
 	/*Hash Table*/	
-	priv->id_hash = g_hash_table_new (g_str_hash, g_str_equal);
-	priv->name_hash = g_hash_table_new (g_str_hash, g_str_equal);
-	priv->parent_hash = g_hash_table_new (g_str_hash, g_str_equal);
+	priv->id_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
+	priv->name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
+	priv->parent_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
 
 	/*ssl*/
 	priv->use_ssl = g_strdup (camel_url_get_param (url, "use_ssl"));
@@ -174,9 +174,9 @@
 static gboolean
 groupwise_auth_loop (CamelService *service, CamelException *ex)
 {
-	CamelGroupwiseStore *groupwise_store = CAMEL_GROUPWISE_STORE (service);
 	CamelSession *session = camel_service_get_session (service);
 	CamelStore *store = CAMEL_STORE (service);
+	CamelGroupwiseStore *groupwise_store = CAMEL_GROUPWISE_STORE (store);
 	CamelGroupwiseStorePrivate *priv = groupwise_store->priv;
 	char *errbuf = NULL;
 	gboolean authenticated = FALSE;
@@ -188,6 +188,7 @@
 	else 
 		uri = g_strconcat ("http://", priv->server_name, ":", priv->port, "/soap", NULL);
 	service->url->passwd = NULL;
+	
 
 	while (!authenticated) {
 		if (errbuf) {
@@ -197,6 +198,7 @@
 			service->url->passwd = NULL;
 		}
 		
+	
 		if (!service->url->passwd && !(store->flags & CAMEL_STORE_PROXY)) {
 			char *prompt;
 			
@@ -214,13 +216,11 @@
 			
 			if (!service->url->passwd) {
 				camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-						     _("You didn't enter a password."));
+						     _("You did not enter a password."));
 				return FALSE;
 			}
 		}
 		
-		
-				
 		priv->cnc = e_gw_connection_new (uri, priv->user, service->url->passwd);
 		if (!E_IS_GW_CONNECTION(priv->cnc) && priv->use_ssl && g_str_equal (priv->use_ssl, "when-possible")) {
 			char *http_uri = g_strconcat ("http://", uri + 8, NULL);
@@ -229,7 +229,7 @@
 		}
 		if (!E_IS_GW_CONNECTION(priv->cnc)) {
 			errbuf = g_strdup_printf (_("Unable to authenticate "
-					    "to GroupWise server."));
+					    "to GroupWise server. "));
 						  
 			camel_exception_clear (ex);
 		} else 
@@ -263,6 +263,7 @@
 	return TRUE;
 
 }
+
 static gboolean
 groupwise_connect (CamelService *service, CamelException *ex)
 {
@@ -273,9 +274,18 @@
 
 	d("in groupwise store connect\n");
 	
-	if (((CamelOfflineStore *) store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL)
-		return TRUE;
-	
+/*	if (((CamelOfflineStore *) store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL || 
+	     (service->status == CAMEL_SERVICE_DISCONNECTED))
+		return FALSE; */
+	if (service->status == CAMEL_SERVICE_DISCONNECTED)
+		return FALSE;
+
+	if (!priv) {
+		store->priv = g_new0 (CamelGroupwiseStorePrivate, 1);
+		priv = store->priv;
+		camel_service_construct (service, service->session, service->provider, service->url, ex);
+	}
+
 	CAMEL_SERVICE_LOCK (service, connect_lock);
 	
 	if (priv->cnc) {
@@ -289,7 +299,9 @@
 		return FALSE;
 	}
 	
+	
 	service->status = CAMEL_SERVICE_CONNECTED;
+	((CamelOfflineStore *) store)->state = CAMEL_OFFLINE_STORE_NETWORK_AVAIL;
 
 	if (!e_gw_connection_get_version (priv->cnc)) {
 		camel_session_alert_user(session, 
@@ -299,19 +311,10 @@
 
 	}
 
-
 	ns = camel_groupwise_store_summary_namespace_new (store->summary, priv->storage_path, '/');
 	camel_groupwise_store_summary_namespace_set (store->summary, ns);
 
 	if (camel_store_summary_count ((CamelStoreSummary *)store->summary) == 0) {
-		/*XXX: Have to sync up folders here*/
-		groupwise_folders_sync (store, ex);
-		if (camel_exception_is_set (ex)) {
-			camel_store_summary_save ((CamelStoreSummary *) store->summary);
-			CAMEL_SERVICE_UNLOCK (service, connect_lock);
-			camel_service_disconnect (service, TRUE, NULL);
-			return FALSE;
-		}
 		/*Settting the refresh stamp to the current time*/
 		store->refresh_stamp = time (0);
 	}
@@ -326,19 +329,75 @@
 	return FALSE;
 
 }
+static void
+groupwise_disconnect_cleanup (CamelService *service, gboolean clean, CamelException *ex)
+{
+	CamelGroupwiseStore *groupwise_store = CAMEL_GROUPWISE_STORE (service);
+	CamelGroupwiseStorePrivate *priv = groupwise_store->priv;
+	
+	g_print ("camel_groupwise_store_finalize\n");
+	if (groupwise_store->summary) {
+		camel_store_summary_save ((CamelStoreSummary *)groupwise_store->summary);
+		camel_object_unref (groupwise_store->summary);
+	}
+	
+	if (priv) {
+		if (priv->user) {
+			g_free (priv->user);
+			priv->user = NULL;
+		}
+		if (priv->server_name) {
+			g_free (priv->server_name);
+			priv->server_name = NULL;
+		}
+		if (priv->port) {
+			g_free (priv->port);
+			priv->port = NULL;
+		}
+		if (priv->use_ssl) {
+			g_free (priv->use_ssl);
+			priv->use_ssl = NULL;
+		}
+		if (priv->base_url) {
+			g_free (priv->base_url);
+			priv->base_url = NULL;
+		}
+		
+		if (priv->storage_path)
+			g_free(priv->storage_path);
 
+		if(groupwise_store->root_container)
+			g_free (groupwise_store->root_container);
+		
+		if (priv->id_hash)
+			g_hash_table_destroy (priv->id_hash);
+
+		if (priv->name_hash)
+			g_hash_table_destroy (priv->name_hash);
+
+		if (priv->parent_hash)
+			g_hash_table_destroy (priv->parent_hash);
+
+		g_free (groupwise_store->priv);
+		groupwise_store->priv = NULL;
+	}
+}
+
 static gboolean
 groupwise_disconnect (CamelService *service, gboolean clean, CamelException *ex)
 {
 	CamelGroupwiseStore *groupwise_store = CAMEL_GROUPWISE_STORE (service);
 	
-	CAMEL_SERVICE_LOCK (groupwise_store, connect_lock);
-	if (groupwise_store->priv->cnc) {
-		g_object_unref (groupwise_store->priv->cnc);
-		groupwise_store->priv->cnc = NULL;
+	if (clean) {
+		CAMEL_SERVICE_LOCK (groupwise_store, connect_lock);
+		if (groupwise_store->priv && groupwise_store->priv->cnc) {
+			g_object_unref (groupwise_store->priv->cnc);
+			groupwise_store->priv->cnc = NULL;
+		}
+		CAMEL_SERVICE_UNLOCK (groupwise_store, connect_lock);
 	}
-	CAMEL_SERVICE_UNLOCK (groupwise_store, connect_lock);
 	
+	//groupwise_disconnect_cleanup (service, clean, ex);
 	return TRUE;
 }
 
@@ -399,7 +458,15 @@
 		name = fi->full_name;
 	else
 		name++;
-	
+	if (!strcmp (folder_name, "Sent Items"))
+		fi->flags |= CAMEL_FOLDER_TYPE_SENT;
+	else if (!strcmp (folder_name, "Mailbox"))
+		fi->flags |= CAMEL_FOLDER_TYPE_INBOX;
+	else if (!strcmp (folder_name, "Trash"))
+		fi->flags |= CAMEL_FOLDER_TYPE_TRASH;
+	else if (!strcmp (folder_name, "Junk Mail"))
+		fi->flags |= CAMEL_FOLDER_TYPE_JUNK;
+		
 	fi->name = g_strdup(name);
 	return fi;
 }
@@ -420,7 +487,7 @@
 	storage_path = g_strdup_printf ("%s/folders", priv->storage_path);
 	folder_dir = g_strdup(e_path_to_physical (storage_path,folder_name));
 
-	if (access(folder_dir, F_OK) != 0) {
+	if (g_access(folder_dir, F_OK) != 0) {
 		g_free(folder_dir);
 		return;
 	}
@@ -434,15 +501,15 @@
 	}
 
 	camel_object_unref (summary);
-	unlink (summary_file);
+	g_unlink (summary_file);
 	g_free (summary_file);
 
 
 	state_file = g_strdup_printf ("%s/cmeta", folder_dir);
-	unlink (state_file);
+	g_unlink (state_file);
 	g_free (state_file);
 
-	rmdir (folder_dir);
+	g_rmdir (folder_dir);
 	g_free (folder_dir);
 
 	camel_store_summary_remove_path ( (CamelStoreSummary *)gw_store->summary, folder_name);
@@ -464,7 +531,7 @@
 	storage_path = g_strdup_printf("%s/folders", priv->storage_path);
 	folder_dir = e_path_to_physical (storage_path, folder_name);
 	g_free(storage_path);
-	if (!folder_dir || access (folder_dir, F_OK) != 0) {
+	if (!folder_dir || g_access (folder_dir, F_OK) != 0) {
 		g_free (folder_dir);
 		camel_exception_setv (ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				_("No such folder %s"), folder_name);
@@ -487,7 +554,7 @@
 	char *container_id, *folder_dir, *storage_path;
 	EGwConnectionStatus status;
 	GList *list = NULL;
-	gboolean done = FALSE;
+	gboolean done = FALSE, all_ok = TRUE;
 	const char *position = E_GW_CURSOR_POSITION_END; 
 	int count = 0, cursor, summary_count = 0;
 	CamelStoreInfo *si = NULL;
@@ -536,22 +603,21 @@
 		return NULL;
 	}
 	g_free (folder_dir);
-
+	
 	si = camel_store_summary_path ((CamelStoreSummary *)gw_store->summary, folder_name);
 	if (si) {
-		camel_object_get (folder, NULL, CAMEL_FOLDER_TOTAL, &total, NULL);
+		total = si->total;
 		camel_store_summary_info_free ((CamelStoreSummary *)(gw_store)->summary, si);
-		g_print ("TOTAL:%d\n\n", total);
 	}
 
 	summary = (CamelGroupwiseSummary *) folder->summary;
 
 	summary_count = camel_folder_summary_count (folder->summary);
 	if(!summary_count || !summary->time_string) {
-		g_print ("\n\n** %s **: No summary as yet : using get cursor request\n\n", folder->name);
+		d(g_print ("\n\n** %s **: No summary as yet : using get cursor request\n\n", folder->name);)
 
 		status = e_gw_connection_create_cursor (priv->cnc, container_id, 
-				"peek id recipient attachments distribution subject status options priority startDate created",
+				"peek id recipient attachments distribution subject status options priority startDate created delivered size hasAttachment",
 				NULL,
 				&cursor);
 		if (status != E_GW_CONNECTION_STATUS_OK) {
@@ -560,7 +626,7 @@
 			return NULL;
 		}
 
-		camel_operation_start (NULL, _("Fetching summary information for new messages"));
+		camel_operation_start (NULL, _("Fetching summary information for new messages in %s"), folder->name);
 		camel_folder_summary_clear (folder->summary);
 
 		while (!done) {
@@ -568,14 +634,18 @@
 							      cursor, FALSE, 
 							      CURSOR_ITEM_LIMIT, position, &list);
 			if (status != E_GW_CONNECTION_STATUS_OK) {
+				all_ok = FALSE;
+				break;
+				/*
 				CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
 				e_gw_connection_destroy_cursor (priv->cnc, container_id, cursor);
-				camel_folder_summary_clear (folder->summary);
+				//camel_folder_summary_clear (folder->summary);
 				camel_folder_summary_save (folder->summary);
 				camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
 				camel_operation_end (NULL);
+				camel_object_unref (folder);
 				g_free (container_id);
-				return NULL;
+				return NULL;*/
 			}
 			
 			count += g_list_length (list);
@@ -596,8 +666,7 @@
 
 		camel_operation_end (NULL);
 	} 
-
-	if (done) {
+	if (done && all_ok) {
 		if (summary->time_string)
 			g_free (summary->time_string);
 		summary->time_string = g_strdup (e_gw_connection_get_server_time (priv->cnc));
@@ -614,21 +683,111 @@
 	return folder;
 }
 
-static gboolean
-get_one_folder_offline (const char *physical_path, const char *path, gpointer data)
+void 
+gw_store_reload_folder (CamelGroupwiseStore *gw_store, CamelFolder *folder, guint32 flags, CamelException *ex)
 {
-	GPtrArray *folders = data;
-	CamelGroupwiseStore *groupwise_store = folders->pdata[0];
-	CamelFolderInfo *fi;
+	CamelGroupwiseStorePrivate *priv = gw_store->priv;
+	CamelGroupwiseSummary *summary;
+	char *container_id;
+	EGwConnectionStatus status;
+	GList *list = NULL;
+	gboolean done = FALSE;
+	const char *position = E_GW_CURSOR_POSITION_END; 
+	int count = 0, cursor, summary_count = 0;
+	CamelStoreInfo *si = NULL;
+	guint total;
+	
+	camel_exception_clear (ex);
+
+	CAMEL_SERVICE_LOCK (gw_store, connect_lock);
+
+	if (!camel_groupwise_store_connected (gw_store, ex)) {
+		CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+		return;
+	}
+	
+	if (!E_IS_GW_CONNECTION( priv->cnc)) {
+		if (!groupwise_connect (CAMEL_SERVICE((CamelStore*)gw_store), ex)) {
+			camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_CANT_AUTHENTICATE, _("Authentication failed"));
+			CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+			return;
+		}
+	}
+	
+	container_id = 	g_strdup (g_hash_table_lookup (priv->name_hash, folder->full_name));
+
+	si = camel_store_summary_path ((CamelStoreSummary *)gw_store->summary, folder->name);
+	if (si) {
+		total = si->total;
+		camel_store_summary_info_free ((CamelStoreSummary *)(gw_store)->summary, si);
+	}
+
+	summary = (CamelGroupwiseSummary *) folder->summary;
+	camel_folder_summary_clear (folder->summary);
+	camel_folder_summary_save (folder->summary);
+
+	summary_count = camel_folder_summary_count (folder->summary);
+	if(!summary_count || !summary->time_string) {
+		d(g_print ("\n\n** %s **: Summary missing???? Reloading summary....\n\n", folder->name);)
+
+		status = e_gw_connection_create_cursor (priv->cnc, container_id, 
+				"peek id recipient attachments distribution subject status options priority startDate created delivered size",
+				NULL,
+				&cursor);
+		if (status != E_GW_CONNECTION_STATUS_OK) {
+			CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+			g_free (container_id);
+			return;
+		}
+
+		camel_operation_start (NULL, _("Fetching summary information for new messages in %s"), folder->name);
+
+		while (!done) {
+			status = e_gw_connection_read_cursor (priv->cnc, container_id, 
+							      cursor, FALSE, 
+							      CURSOR_ITEM_LIMIT, position, &list);
+			if (status != E_GW_CONNECTION_STATUS_OK) {
+				CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+				e_gw_connection_destroy_cursor (priv->cnc, container_id, cursor);
+				camel_folder_summary_save (folder->summary);
+				camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_INVALID, _("Authentication failed"));
+				camel_operation_end (NULL);
+				g_free (container_id);
+				return;
+			}
+			
+			count += g_list_length (list);
 		
-	if (*path != '/')
-		return TRUE;
+			if (total > 0)
+				camel_operation_progress (NULL, (100*count)/total);
+			gw_update_summary (folder, list,  ex);
+			
+			if (!list)
+				done = TRUE;
+			g_list_foreach (list, (GFunc)g_object_unref, NULL);
+			g_list_free (list);
+			list = NULL;
+			position = E_GW_CURSOR_POSITION_CURRENT;
+      		}
+
+		e_gw_connection_destroy_cursor (priv->cnc, container_id, cursor);
+
+		camel_operation_end (NULL);
+	} 
+
+	if (done) {
+		if (summary->time_string)
+			g_free (summary->time_string);
+		summary->time_string = g_strdup (e_gw_connection_get_server_time (priv->cnc));
+	}
+
+	camel_folder_summary_save (folder->summary);
+
+	gw_store->current_folder = folder;
 	
-	fi = groupwise_build_folder_info(groupwise_store, NULL, path+1);
-	if (!strcmp (fi->full_name, "Mailbox"))
-		fi->flags |= CAMEL_FOLDER_TYPE_INBOX;
-	g_ptr_array_add (folders, fi);
-	return TRUE;
+	g_free (container_id);
+	CAMEL_SERVICE_UNLOCK (gw_store, connect_lock);
+	return;
 }
 
 CamelFolderInfo *
@@ -715,13 +874,16 @@
 	if (e_gw_container_get_is_shared_by_me (container))
 		fi->flags |= CAMEL_FOLDER_SHARED_BY_ME;
 
-	if (type == E_GW_CONTAINER_TYPE_INBOX) {
+	/*if (type == E_GW_CONTAINER_TYPE_INBOX) {
 		fi->total = -1;
 		fi->unread = -1;
-	} else	if (type == E_GW_CONTAINER_TYPE_TRASH) {
+	} else	if (type == E_GW_CONTAINER_TYPE_TRASH) {*/
+			
+	if (type == E_GW_CONTAINER_TYPE_TRASH || type == E_GW_CONTAINER_TYPE_SENT) {
 		fi->total = e_gw_container_get_total_count (container);
-		fi->unread = 0;
-	}else {
+		fi->unread = 0; 
+		/* Done with a belief that user wont mark something as unread in Trash and Sent Items */
+	} else {
 		fi->total = e_gw_container_get_total_count (container);
 		fi->unread = e_gw_container_get_unread_count (container);
 	}
@@ -756,6 +918,13 @@
 	CamelStoreInfo *si = NULL;
 	int count, i;
 
+	if (!priv->cnc && ((CamelOfflineStore *) store)->state == CAMEL_OFFLINE_STORE_NETWORK_AVAIL) {
+		if (((CamelService *)store)->status == CAMEL_SERVICE_DISCONNECTED){
+			((CamelService *)store)->status = CAMEL_SERVICE_CONNECTING;
+			groupwise_connect ((CamelService *)store, ex);
+		}
+	}
+
 	status = e_gw_connection_get_container_list (priv->cnc, "folders", &folder_list);
 	if (status != E_GW_CONNECTION_STATUS_OK) {
 		g_warning ("Could not get folder list..\n");
@@ -807,7 +976,6 @@
 		if ( (type == E_GW_CONTAINER_TYPE_CALENDAR) || (type == E_GW_CONTAINER_TYPE_CONTACTS) )
 			continue;
 
-		//convert_to_folder_info (store, E_GW_CONTAINER (folder_list->data), (const char *)url, ex);
 		info = convert_to_folder_info (store, E_GW_CONTAINER (folder_list->data), (const char *)url, ex);
 		if (info) {
 			hfi = g_hash_table_lookup (present, info->full_name);
@@ -958,47 +1126,57 @@
 
 	if (top && groupwise_is_system_folder (top)) 
 		return groupwise_build_folder_info (groupwise_store, NULL, top );
+
 	/*
 	 * Thanks to Michael, for his cached folders implementation in IMAP
 	 * is used as is here.
 	 */
-	if ((groupwise_store->list_loaded == TRUE) && camel_store_summary_count((CamelStoreSummary *)groupwise_store->summary) > 0) {
-		/*Load from cache*/
-		time_t now;
-		int ref;
-
-		now = time (0);
-		ref = now > groupwise_store->refresh_stamp+60*60*1;
-		if (ref) {
-			CAMEL_SERVICE_LOCK (store, connect_lock);
-			ref = now > groupwise_store->refresh_stamp+60*60*1;
-			if (ref) {
-				struct _store_refresh_msg *m;
-				groupwise_store->refresh_stamp = now;
-				m = camel_session_thread_msg_new (((CamelService *)store)->session, &store_refresh_ops, sizeof(*m));
-				m->store = store;
-				camel_object_ref (store);
-				camel_exception_init (&m->ex);
-				camel_session_thread_queue (((CamelService *)store)->session, &m->msg, 0);
-			}
-			CAMEL_SERVICE_UNLOCK (store, connect_lock);
+	if (camel_store_summary_count ((CamelStoreSummary *)groupwise_store->summary) == 0) {
+		CAMEL_SERVICE_LOCK (store, connect_lock);
+		if (groupwise_store->list_loaded == 3) {
+			groupwise_folders_sync (groupwise_store, ex);
+			groupwise_store->list_loaded -= 1;
 		}
-	}
-
-	CAMEL_SERVICE_LOCK (store, connect_lock);
-	if ((groupwise_store->list_loaded == FALSE) && camel_groupwise_store_connected ((CamelGroupwiseStore *)store, ex)) {
-		groupwise_store->list_loaded = TRUE;
-		groupwise_folders_sync (groupwise_store, ex);
 		if (camel_exception_is_set (ex)) {
+			camel_store_summary_save ((CamelStoreSummary *) groupwise_store->summary);
 			CAMEL_SERVICE_UNLOCK (store, connect_lock);
 			return NULL;
 		}
-		camel_store_summary_touch ((CamelStoreSummary *)groupwise_store->summary);
+		CAMEL_SERVICE_UNLOCK (store, connect_lock);
 		camel_store_summary_save ((CamelStoreSummary *)groupwise_store->summary);
+		goto end_r;
 	}
+
+	if ((camel_store_summary_count((CamelStoreSummary *)groupwise_store->summary) > 0) && (groupwise_store->list_loaded > 1)) {
+		/*Load from cache*/
+		groupwise_store->list_loaded -= 1;
+		goto end_r;
+	}
+
+	CAMEL_SERVICE_LOCK (store, connect_lock);
+	if ((groupwise_store->list_loaded == 1) && check_for_connection((CamelService *)store, ex)) {
+		if (!priv->cnc) {
+			if (groupwise_connect ((CamelService *)store, ex)) {
+				g_warning ("Could connect!!!\n");
+			} else 
+				g_warning ("Could not connect..failure connecting\n");
+		}
+		if (camel_groupwise_store_connected ((CamelGroupwiseStore *)store, ex)) {
+			if (groupwise_store->current_folder)
+				CAMEL_FOLDER_CLASS (CAMEL_OBJECT_GET_CLASS (groupwise_store->current_folder))->sync(groupwise_store->current_folder, FALSE, ex);
+			groupwise_folders_sync (groupwise_store, ex);
+			if (camel_exception_is_set (ex)) {
+				CAMEL_SERVICE_UNLOCK (store, connect_lock);
+				return NULL;
+			}
+			camel_store_summary_touch ((CamelStoreSummary *)groupwise_store->summary);
+			camel_store_summary_save ((CamelStoreSummary *)groupwise_store->summary);
+		}
+	}
 	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 
-	//camel_exception_clear (ex);
+	/*camel_exception_clear (ex);*/
+end_r:
 	info = groupwise_get_folder_info_offline (store, top, flags, ex);
 	return info;
 }
@@ -1181,7 +1359,7 @@
 	g_free (storepath);
 
 	/*XXX: make sure the summary is also renamed*/
-	if (rename (oldpath, newpath) == -1) {
+	if (g_rename (oldpath, newpath) == -1) {
 		g_warning ("Could not rename message cache '%s' to '%s': %s: cache reset",
 				oldpath, newpath, strerror (errno));
 	}
@@ -1236,26 +1414,20 @@
 	return priv->base_url;
 }
 
-static void
-free_hash (gpointer key, gpointer value, gpointer data)
-{
-	if (value)
-		g_free (value);
-	if (key)
-		g_free (key);
-}
-
 static CamelFolder *
 groupwise_get_trash (CamelStore *store, CamelException *ex)
 {
-	CamelFolder *folder =  groupwise_get_folder (store, "Trash", 0, ex);
+	CamelFolder *folder = camel_store_get_folder(store, "Trash", 0, ex);
 	if (folder) {
-		g_print ("Trash Folder exists\n");
+		 char *state = g_build_filename(((CamelGroupwiseStore *)store)->priv->storage_path, "folders", "Trash", "cmeta", NULL);
+
+		camel_object_set(folder, NULL, CAMEL_OBJECT_STATE_FILE, state, NULL);
+		g_free(state);
+		camel_object_state_read(folder);
+
 		return folder;
-	} else {
-		g_print ("Trash Folder does not\n");
+	} else 
 		return NULL;
-	}
 }
 
 /*
@@ -1266,14 +1438,10 @@
 camel_groupwise_store_connected (CamelGroupwiseStore *store, CamelException *ex)
 {
 	if (((CamelOfflineStore *) store)->state == CAMEL_OFFLINE_STORE_NETWORK_AVAIL
-	    && camel_service_connect ((CamelService *)store, ex)
-	    && store->priv->cnc != NULL )
+	    && camel_service_connect ((CamelService *)store, ex)) {
 		return TRUE;
-
-	if (!camel_exception_is_set (ex))
-		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
-				_("You must be working online to complete this operation"));
-
+	}
+	/*Not online, so return FALSE*/
 	return FALSE;
 }
 
@@ -1378,18 +1546,15 @@
 		if(groupwise_store->root_container)
 			g_free (groupwise_store->root_container);
 		
-		if (priv->id_hash) {
-			g_hash_table_foreach (priv->id_hash, free_hash, NULL);
+		if (priv->id_hash)
 			g_hash_table_destroy (priv->id_hash);
-		}
-		if (priv->name_hash) {
-			g_hash_table_foreach (priv->name_hash, free_hash, NULL);
+
+		if (priv->name_hash)
 			g_hash_table_destroy (priv->name_hash);
-		}
-		if (priv->parent_hash) {
-			g_hash_table_foreach (priv->parent_hash, free_hash, NULL);
+
+		if (priv->parent_hash)
 			g_hash_table_destroy (priv->parent_hash);
-		}
+
 		g_free (groupwise_store->priv);
 		groupwise_store->priv = NULL;
 	}
Index: camel/providers/imapp/camel-imapp-folder.c
===================================================================
--- camel/providers/imapp/camel-imapp-folder.c	(revision 444)
+++ camel/providers/imapp/camel-imapp-folder.c	(working copy)
@@ -42,6 +42,7 @@
 #include "camel-imapp-exception.h"
 
 #include <libedataserver/md5-utils.h>
+#include <libedataserver/e-data-server-util.h>
 
 #include <stdlib.h>
 #include <string.h>
@@ -134,7 +135,7 @@
 		char *base = g_build_filename(root, path, NULL);
 		char *file = g_build_filename(base, ".ev-summary", NULL);
 
-		camel_mkdir(base, 0777);
+		e_util_mkdir_hier(base, 0777);
 		g_free(base);
 
 		camel_folder_summary_set_filename(folder->summary, file);
Index: camel/providers/imapp/ChangeLog
===================================================================
--- camel/providers/imapp/ChangeLog	(revision 444)
+++ camel/providers/imapp/ChangeLog	(working copy)
@@ -1,3 +1,9 @@
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-imapp-store.c: 
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
 2005-04-17  Changwoo Ryu  <cwryu@debian.org>
 
 	** See bug #300891
Index: camel/providers/imapp/camel-imapp-store.c
===================================================================
--- camel/providers/imapp/camel-imapp-store.c	(revision 444)
+++ camel/providers/imapp/camel-imapp-store.c	(working copy)
@@ -245,7 +245,7 @@
 		camel_freeaddrinfo(ai);
 		if (ret == -1) {
 			if (errno == EINTR)
-				camel_exception_throw(CAMEL_EXCEPTION_USER_CANCEL, _("Connection cancelled"));
+				camel_exception_throw(CAMEL_EXCEPTION_USER_CANCEL, _("Connection canceled"));
 			else
 				camel_exception_throw(CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 						      _("Could not connect to %s (port %s): %s"),
Index: camel/providers/imapp/camel-imapp-summary.c
===================================================================
--- camel/providers/imapp/camel-imapp-summary.c	(revision 444)
+++ camel/providers/imapp/camel-imapp-summary.c	(working copy)
@@ -115,18 +115,28 @@
 summary_header_load(CamelFolderSummary *s, FILE *in)
 {
 	CamelIMAPPSummary *ims = CAMEL_IMAPP_SUMMARY(s);
+	unsigned char *ptrchr = s->filepos;
+	gint32 *ptr32;
 
 	if (camel_imapp_summary_parent->summary_header_load(s, in) == -1)
 		return -1;
 
 	/* Legacy version */
 	if (s->version == 0x100c)
-		return camel_file_util_decode_uint32(in, &ims->uidvalidity);
+	{		
+		ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &ims->uidvalidity, FALSE);
+		s->filepos = ptrchr;
 
-	if (camel_file_util_decode_fixed_int32(in, &ims->version) == -1
-	    || camel_file_util_decode_fixed_int32(in, &ims->uidvalidity) == -1)
-		return -1;
+		return 0;
+	}
 
+	ptr32 = s->filepos;
+
+	ims->version = g_ntohl (*ptr32); ptr32++;
+	ims->uidvalidity = g_ntohl (*ptr32); ptr32++;
+
+	s->filepos = ptr32;
+
 	if (ims->version > CAMEL_IMAPP_SUMMARY_VERSION) {
 		g_warning("Unkown summary version\n");
 		errno = EINVAL;
@@ -160,16 +170,14 @@
 
 	info = camel_imapp_summary_parent->message_info_load(s, in);
 	if (info) {
+		unsigned char *ptrchr = s->filepos;
 		iinfo =(CamelIMAPPMessageInfo *)info;
 
-		if (camel_file_util_decode_uint32(in, &iinfo->server_flags) == -1)
-			goto error;
+		ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &iinfo->server_flags, FALSE);
+		s->filepos = ptrchr;		
 	}
 
 	return info;
-error:
-	camel_message_info_free(info);
-	return NULL;
 }
 
 static int
Index: camel/providers/imap/camel-imap-store.c
===================================================================
--- camel/providers/imap/camel-imap-store.c	(revision 444)
+++ camel/providers/imap/camel-imap-store.c	(working copy)
@@ -24,9 +24,7 @@
  *
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -34,40 +32,55 @@
 #include <unistd.h>
 #include <errno.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include "camel/camel-debug.h"
+#include "camel/camel-disco-diary.h"
+#include "camel/camel-exception.h"
+#include "camel/camel-file-utils.h"
+#include "camel/camel-folder.h"
+#include "camel/camel-i18n.h"
+#include "camel/camel-net-utils.h"
+#include "camel/camel-private.h"
+#include "camel/camel-sasl.h"
+#include "camel/camel-session.h"
+#include "camel/camel-stream-buffer.h"
+#include "camel/camel-stream-fs.h"
+#include "camel/camel-stream-process.h"
+#include "camel/camel-stream.h"
+#include "camel/camel-string-utils.h"
+#include "camel/camel-tcp-stream-raw.h"
+#include "camel/camel-tcp-stream-ssl.h"
+#include "camel/camel-url.h"
+#include "camel/camel-utf8.h"
+
+#include "camel-imap-command.h"
+#include "camel-imap-folder.h"
+#include "camel-imap-message-cache.h"
+#include "camel-imap-store-summary.h"
 #include "camel-imap-store.h"
-#include "camel-imap-store-summary.h"
-#include "camel-imap-folder.h"
+#include "camel-imap-summary.h"
 #include "camel-imap-utils.h"
-#include "camel-imap-command.h"
-#include "camel-imap-summary.h"
-#include "camel-imap-message-cache.h"
-#include "camel-disco-diary.h"
-#include "camel-file-utils.h"
-#include "camel-folder.h"
-#include "camel-exception.h"
-#include "camel-session.h"
-#include "camel-stream.h"
-#include "camel-stream-buffer.h"
-#include "camel-stream-fs.h"
-#include "camel-stream-process.h"
-#include "camel-tcp-stream-raw.h"
-#include "camel-tcp-stream-ssl.h"
-#include "camel-url.h"
-#include "camel-sasl.h"
-#include "camel-utf8.h"
-#include "camel-string-utils.h"
-#include "camel-imap-private.h"
-#include "camel-private.h"
-#include "camel-debug.h"
-#include "camel-i18n.h"
-#include "camel-net-utils.h"
 
+#if !GLIB_CHECK_VERSION (2, 8, 0)
+#define g_access access
+#endif
+
 #define d(x) 
 
 /* Specified in RFC 2060 */
 #define IMAP_PORT "143"
 #define IMAPS_PORT "993"
 
+#ifdef G_OS_WIN32
+/* The strtok() in Microsoft's C library is MT-safe (but still uses
+ * only one buffer pointer per thread, but for the use of strtok_r()
+ * here that's enough).
+ */
+#define strtok_r(s,sep,lasts) (*(lasts)=strtok((s),(sep)))
+#endif
+
 static CamelDiscoStoreClass *parent_class = NULL;
 
 static char imap_tag_prefix = 'A';
@@ -245,8 +258,8 @@
 	   CamelException *ex)
 {
 	CamelImapStore *imap_store = CAMEL_IMAP_STORE (service);
+	CamelStore *store = CAMEL_STORE (service);
 	CamelDiscoStore *disco_store = CAMEL_DISCO_STORE (service);
-	CamelStore *store = CAMEL_STORE (service);
 	char *tmp, *path;
 	CamelURL *summary_url;
 
@@ -266,7 +279,7 @@
 	imap_store->parameters = 0;
 	if (camel_url_get_param (url, "use_lsub"))
 		imap_store->parameters |= IMAP_PARAM_SUBSCRIPTIONS;
-	if (camel_url_get_param (url, "namespace")) {
+	if (camel_url_get_param (url, "override_namespace") && camel_url_get_param (url, "namespace")) {
 		imap_store->parameters |= IMAP_PARAM_OVERRIDE_NAMESPACE;
 		g_free(imap_store->namespace);
 		imap_store->namespace = g_strdup (camel_url_get_param (url, "namespace"));
@@ -550,7 +563,7 @@
 	CamelStream *tcp_stream;
 	CamelSockOptData sockopt;
 	gboolean force_imap4 = FALSE;
-	int clean_quit = TRUE, ret;
+	gboolean clean_quit = TRUE;
 	char *buf;
 	
 	if (ssl_mode != MODE_CLEAR) {
@@ -571,7 +584,7 @@
 		tcp_stream = camel_tcp_stream_raw_new ();
 	}
 	
-	if ((ret = camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai)) == -1) {
+	if (camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai) == -1) {
 		if (errno == EINTR)
 			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
 					     _("Connection cancelled"));
@@ -759,6 +772,10 @@
 	return FALSE;
 }
 
+#ifndef G_OS_WIN32
+
+/* Using custom commands to connect to IMAP servers is not supported on Win32 */
+
 static gboolean
 connect_to_server_process (CamelService *service, const char *cmd, CamelException *ex)
 {
@@ -902,6 +919,8 @@
 	
 }
 
+#endif
+
 static struct {
 	char *value;
 	char *serv;
@@ -918,16 +937,19 @@
 static gboolean
 connect_to_server_wrapper (CamelService *service, CamelException *ex)
 {
-	const char *command, *ssl_mode;
+	const char *ssl_mode;
 	struct addrinfo hints, *ai;
 	int mode, ret, i;
 	char *serv;
 	const char *port;
 
+#ifndef G_OS_WIN32
+	const char *command;
+
 	if (camel_url_get_param(service->url, "use_command")
 	    && (command = camel_url_get_param(service->url, "command")))
 		return connect_to_server_process(service, command, ex);
-	
+#endif	
 	if ((ssl_mode = camel_url_get_param (service->url, "use_ssl"))) {
 		for (i = 0; ssl_options[i].value; i++)
 			if (!strcmp (ssl_options[i].value, ssl_mode))
@@ -955,16 +977,11 @@
 		camel_exception_clear (ex);
 		ai = camel_getaddrinfo(service->url->host, port, &hints, ex);
 	}
+	
 	if (ai == NULL)
 		return FALSE;
 	
-	if (!(ret = connect_to_server (service, ai, mode, ex)) && mode == MODE_SSL) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (service, ai, MODE_TLS, ex);
-	} else if (!ret && mode == MODE_TLS) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (service, ai, MODE_CLEAR, ex);
-	}
+	ret = connect_to_server (service, ai, mode, ex);
 	
 	camel_freeaddrinfo (ai);
 	
@@ -1088,7 +1105,7 @@
 	storage_path = g_strdup_printf ("%s/folders", imap_store->storage_path);
 	folder_dir = imap_path_to_physical (storage_path, folder_name);
 	g_free (storage_path);
-	if (access (folder_dir, F_OK) != 0) {
+	if (g_access (folder_dir, F_OK) != 0) {
 		g_free (folder_dir);
 		goto event;
 	}
@@ -1108,22 +1125,22 @@
 	camel_object_unref (cache);
 	camel_object_unref (summary);
 	
-	unlink (summary_file);
+	g_unlink (summary_file);
 	g_free (summary_file);
 	
 	journal_file = g_strdup_printf ("%s/journal", folder_dir);
-	unlink (journal_file);
+	g_unlink (journal_file);
 	g_free (journal_file);
 
 	state_file = g_strdup_printf ("%s/cmeta", folder_dir);
-	unlink (state_file);
+	g_unlink (state_file);
 	g_free (state_file);
 
 	state_file = g_strdup_printf("%s/subfolders", folder_dir);
-	rmdir(state_file);
+	g_rmdir(state_file);
 	g_free(state_file);
 	
-	rmdir (folder_dir);
+	g_rmdir (folder_dir);
 	g_free (folder_dir);
 	
  event:
@@ -1158,6 +1175,7 @@
 	return TRUE;
 }
 
+#if 0
 /* This is a little 'hack' to avoid the deadlock conditions that would otherwise
    ensue when calling camel_folder_refresh_info from inside a lock */
 /* NB: on second thougts this is probably not entirely safe, but it'll do for now */
@@ -1204,7 +1222,8 @@
 	}
 	
 	g_ptr_array_free (folders, TRUE);
-}	
+}
+#endif
 
 static gboolean
 try_auth (CamelImapStore *store, const char *mech, CamelException *ex)
@@ -1338,7 +1357,7 @@
 			
 			if (!service->url->passwd) {
 				camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-						     _("You didn't enter a password."));
+						     _("You did not enter a password."));
 				return FALSE;
 			}
 		}
@@ -1389,10 +1408,9 @@
 imap_connect_online (CamelService *service, CamelException *ex)
 {
 	CamelImapStore *store = CAMEL_IMAP_STORE (service);
-	CamelDiscoStore *disco_store = CAMEL_DISCO_STORE (service);
 	CamelImapResponse *response;
 	/*struct _namespaces *namespaces;*/
-	char *result, *name, *path;
+	char *result, *name;
 	size_t len;
 	CamelImapStoreNamespace *ns;
 
@@ -1515,6 +1533,7 @@
 		store->refresh_stamp = time(0);
 	}
 	
+	
  done:
 	/* save any changes we had */
 	camel_store_summary_save((CamelStoreSummary *)store->summary);
@@ -1618,13 +1637,12 @@
 imap_noop (CamelStore *store, CamelException *ex)
 {
 	CamelImapStore *imap_store = (CamelImapStore *) store;
-	CamelDiscoStore *disco = (CamelDiscoStore *) store;
 	CamelImapResponse *response;
 	CamelFolder *current_folder;
 	
 	CAMEL_SERVICE_LOCK (imap_store, connect_lock);
 
-	if (!camel_imap_store_connected(imap_store, ex)) 
+	if (!camel_imap_store_connected(imap_store, ex))
 		goto done;
 
 	current_folder = imap_store->current_folder;
@@ -1636,7 +1654,6 @@
 		if (response)
 			camel_imap_response_free (imap_store, response);
 	}
-	
 done:
 	CAMEL_SERVICE_UNLOCK (imap_store, connect_lock);
 }
@@ -2195,7 +2212,7 @@
 	g_free(storage_path);
 
 	/* So do we care if this didn't work?  Its just a cache? */
-	if (rename (oldpath, newpath) == -1) {
+	if (g_rename (oldpath, newpath) == -1) {
 		g_warning ("Could not rename message cache '%s' to '%s': %s: cache reset",
 			   oldpath, newpath, strerror (errno));
 	}
@@ -2600,7 +2617,10 @@
 
 	if (store->namespace && store->namespace[0]) {
 		char *pattern;
-
+		
+		get_folders_sync(store, "INBOX", &m->ex);
+		if (camel_exception_is_set(&m->ex))
+			goto done;
 		get_folders_sync(store, store->namespace, &m->ex);
 		if (camel_exception_is_set(&m->ex))
 			goto done;
@@ -2679,6 +2699,10 @@
 
 		if (top[0] == 0) {
 			if (imap_store->namespace && imap_store->namespace[0]) {
+				get_folders_sync(imap_store, "INBOX", ex);
+				if (camel_exception_is_set(ex))
+					goto fail;
+				
 				i = strlen(imap_store->namespace)-1;
 				pattern = g_alloca(i+5);
 				strcpy(pattern, imap_store->namespace);
@@ -2693,7 +2717,7 @@
 			}
 		} else {
 			char *name;
-
+			
 			name = camel_imap_store_summary_full_from_path(imap_store->summary, top);
 			if (name == NULL)
 				name = camel_imap_store_summary_path_to_full(imap_store->summary, top, imap_store->dir_sep);
@@ -2730,6 +2754,7 @@
 			 guint32 flags, CamelException *ex)
 {
 	CamelImapStore *imap_store = CAMEL_IMAP_STORE (store);
+	gboolean include_inbox = FALSE;
 	CamelFolderInfo *fi;
 	GPtrArray *folders;
 	char *pattern, *name;
@@ -2742,12 +2767,14 @@
 
 	folders = g_ptr_array_new ();
 
-	if (top == NULL)
+	if (top == NULL || top[0] == '\0') {
+		include_inbox = TRUE;
 		top = "";
+	}
 
 	/* get starting point */
 	if (top[0] == 0) {
-		if (imap_store->namespace) {
+		if (imap_store->namespace && imap_store->namespace[0]) {
 			name = g_strdup(imap_store->summary->namespace->full_name);
 			top = imap_store->summary->namespace->path;
 		} else
@@ -2771,9 +2798,10 @@
 
 		if (si == NULL)
 			continue;
-
+		
 		if ((!strcmp(name, camel_imap_store_info_full_name(imap_store->summary, si))
-		     || imap_match_pattern(imap_store->dir_sep, pattern, camel_imap_store_info_full_name(imap_store->summary, si)))
+		     || imap_match_pattern(imap_store->dir_sep, pattern, camel_imap_store_info_full_name(imap_store->summary, si))
+		     || (include_inbox && !g_ascii_strcasecmp (camel_imap_store_info_full_name(imap_store->summary, si), "INBOX")))
 		    && ((imap_store->parameters & IMAP_PARAM_SUBSCRIPTIONS) == 0
 			|| (flags & CAMEL_STORE_FOLDER_INFO_SUBSCRIBED) == 0
 			|| (si->flags & CAMEL_STORE_INFO_FOLDER_SUBSCRIBED))) {
@@ -2786,11 +2814,11 @@
 			   it.  See create folder */
 			if (fi->flags & CAMEL_FOLDER_NOINFERIORS)
 				fi->flags = (fi->flags & ~CAMEL_FOLDER_NOINFERIORS) | CAMEL_FOLDER_NOCHILDREN;
-
+			
 			/* blah, this gets lost somewhere, i can't be bothered finding out why */
 			if (!g_ascii_strcasecmp(fi->full_name, "inbox"))
 				fi->flags = (fi->flags & ~CAMEL_FOLDER_TYPE_MASK) | CAMEL_FOLDER_TYPE_INBOX;
-
+			
 			if (si->flags & CAMEL_FOLDER_NOSELECT) {
 				CamelURL *url = camel_url_new(fi->uri, NULL);
 				
@@ -2840,15 +2868,15 @@
 	CamelFolderInfo *fi;
 	CamelStoreInfo *si;
 
-	if (!camel_disco_store_check_online (CAMEL_DISCO_STORE (store), ex))
-		return;
+	CAMEL_SERVICE_LOCK(store, connect_lock);
+
 	if (!camel_imap_store_connected (imap_store, ex))
-		return;
+		goto done;
 	
 	response = camel_imap_command (imap_store, NULL, ex,
 				       "SUBSCRIBE %F", folder_name);
 	if (!response)
-		return;
+		goto done;
 	camel_imap_response_free (imap_store, response);
 	
 	si = camel_store_summary_path((CamelStoreSummary *)imap_store->summary, folder_name);
@@ -2865,7 +2893,7 @@
 		/* we don't need to emit a "folder_subscribed" signal
                    if we are in the process of renaming folders, so we
                    are done here... */
-		return;
+		goto done;
 	}
 
 	fi = imap_build_folder_info(imap_store, folder_name);
@@ -2873,6 +2901,8 @@
 	
 	camel_object_trigger_event (CAMEL_OBJECT (store), "folder_subscribed", fi);
 	camel_folder_info_free (fi);
+done:
+	CAMEL_SERVICE_UNLOCK(store, connect_lock);
 }
 
 static void
@@ -2881,19 +2911,21 @@
 {
 	CamelImapStore *imap_store = CAMEL_IMAP_STORE (store);
 	CamelImapResponse *response;
+
+	CAMEL_SERVICE_LOCK(store, connect_lock);
 	
-	if (!camel_disco_store_check_online (CAMEL_DISCO_STORE (store), ex))
-		return;
 	if (!camel_imap_store_connected (imap_store, ex))
-		return;
+		goto done;
 	
 	response = camel_imap_command (imap_store, NULL, ex,
 				       "UNSUBSCRIBE %F", folder_name);
 	if (!response)
-		return;
+		goto done;
 	camel_imap_response_free (imap_store, response);
 
 	imap_folder_effectively_unsubscribed (imap_store, folder_name, ex);
+done:
+	CAMEL_SERVICE_UNLOCK(store, connect_lock);
 }
 
 #if 0
Index: camel/providers/imap/camel-imap-summary.c
===================================================================
--- camel/providers/imap/camel-imap-summary.c	(revision 444)
+++ camel/providers/imap/camel-imap-summary.c	(working copy)
@@ -154,23 +154,24 @@
 
 	/* Legacy version */
 	if (s->version == 0x30c)
-		return camel_file_util_decode_uint32(in, &ims->validity);
+	{
+		unsigned char* ptrchr = s->filepos;
+		ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &ims->validity, FALSE);
+		s->filepos = ptrchr;
+		return 0;
+	}
 
 	/* Version 1 */
-	if (camel_file_util_decode_fixed_int32(in, &ims->version) == -1)
-		return -1;
+	ims->version = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
 	
 	if (ims->version == 2) {
 		/* Version 2: for compat with version 2 of the imap4 summary files */
 		int have_mlist;
-		
-		if (camel_file_util_decode_fixed_int32 (in, &have_mlist) == -1)
-			return -1;
+		have_mlist = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
 	}
+
+	ims->validity = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
 	
-	if (camel_file_util_decode_fixed_int32(in, &ims->validity) == -1)
-		return -1;
-	
 	if (ims->version > CAMEL_IMAP_SUMMARY_VERSION) {
 		g_warning("Unkown summary version\n");
 		errno = EINVAL;
@@ -212,19 +213,16 @@
 	CamelImapMessageInfo *iinfo;
 
 	info = camel_imap_summary_parent->message_info_load (s, in);
+	iinfo = info;
+
 	if (info) {
-		iinfo = (CamelImapMessageInfo *)info;
-
-		if (camel_file_util_decode_uint32 (in, &iinfo->server_flags) == -1)
-			goto error;
-
+		unsigned char* ptrchr = s->filepos;
+		ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &iinfo->server_flags, FALSE);
+		s->filepos = ptrchr;
 		label_to_flags(iinfo);
 	}
 
 	return info;
-error:
-	camel_message_info_free(info);
-	return NULL;
 }
 
 static int
@@ -254,10 +252,20 @@
 static CamelMessageContentInfo *
 content_info_load (CamelFolderSummary *s, FILE *in)
 {
-	if (fgetc (in))
-		return camel_imap_summary_parent->content_info_load (s, in);
-	else
-		return camel_folder_summary_content_info_new (s);
+	CamelMessageContentInfo *retval;
+	guint32 doit;
+	unsigned char* ptrchr = s->filepos;
+
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &doit, FALSE);
+	s->filepos = ptrchr;
+
+	if (doit == 1) {
+		retval = camel_imap_summary_parent->content_info_load (s, in);
+	} else {
+		retval = camel_folder_summary_content_info_new (s);
+	}
+
+	return retval;
 }
 
 static int
@@ -265,10 +273,12 @@
 		   CamelMessageContentInfo *info)
 {
 	if (info->type) {
-		fputc (1, out);
+
+		camel_file_util_encode_uint32 (out, 1);
 		return camel_imap_summary_parent->content_info_save (s, out, info);
 	} else
-		return fputc (0, out);
+		return camel_file_util_encode_uint32 (out, 0);
+
 }
 
 void
@@ -298,6 +308,8 @@
 	}
 
 	mi->info.size = camel_message_info_size(info);
+
+	mi->info.uid_needs_free = TRUE;
 	mi->info.uid = g_strdup (uid);
 
 	label_to_flags(mi);
@@ -312,7 +324,9 @@
 	CamelImapMessageInfo *mi;
 
 	mi = camel_message_info_clone(info);
+
 	mi->info.uid = g_strdup(uid);
+	mi->info.uid_needs_free = TRUE;
 
 	label_to_flags(mi);
 
Index: camel/providers/imap/camel-imap-utils.c
===================================================================
--- camel/providers/imap/camel-imap-utils.c	(revision 444)
+++ camel/providers/imap/camel-imap-utils.c	(working copy)
@@ -31,7 +31,6 @@
 #include <time.h>
 #include <errno.h>
 #include <sys/types.h>
-#include <dirent.h>
 #include <sys/stat.h>
 #include <unistd.h>
 
@@ -42,6 +41,8 @@
 #include "camel-string-utils.h"
 #include "camel-utf8.h"
 
+#include <glib/gstdio.h>
+
 #define d(x)
 
 #define SUBFOLDER_DIR_NAME     "subfolders"
@@ -404,6 +405,7 @@
 			*flags &= ~CAMEL_FOLDER_NOSELECT;
 		
 		*folder = mailbox;
+
 	}
 	
 	return TRUE;
@@ -1348,7 +1350,7 @@
 find_folders_recursive (const char *physical_path, const char *path,
 			IMAPPathFindFoldersCallback callback, gpointer data)
 {
-	DIR *dir;
+	GDir *dir;
 	char *subfolder_directory_path;
 	gboolean ok;
 
@@ -1366,7 +1368,7 @@
 	}
 
 	/* Now scan the subfolders and load them. */
-	dir = opendir (subfolder_directory_path);
+	dir = g_dir_open (subfolder_directory_path, 0, NULL);
 	if (dir == NULL) {
 		g_free (subfolder_directory_path);
 		return TRUE;
@@ -1375,27 +1377,24 @@
 	ok = TRUE;
 	while (ok) {
 		struct stat file_stat;
-		struct dirent *dirent;
+		const char *dirent;
 		char *file_path;
 		char *new_path;
 
-		dirent = readdir (dir);
+		dirent = g_dir_read_name (dir);
 		if (dirent == NULL)
 			break;
 
-		if (strcmp (dirent->d_name, ".") == 0 || strcmp (dirent->d_name, "..") == 0)
-			continue;
-
 		file_path = g_strdup_printf ("%s/%s", subfolder_directory_path,
-					     dirent->d_name);
+					     dirent);
 
-		if (stat (file_path, &file_stat) < 0 ||
+		if (g_stat (file_path, &file_stat) < 0 ||
 		    ! S_ISDIR (file_stat.st_mode)) {
 			g_free (file_path);
 			continue;
 		}
 
-		new_path = g_strdup_printf ("%s/%s", path, dirent->d_name);
+		new_path = g_strdup_printf ("%s/%s", path, dirent);
 
 		ok = find_folders_recursive (file_path, new_path, callback, data);
 
@@ -1403,7 +1402,7 @@
 		g_free (new_path);
 	}
 
-	closedir (dir);
+	g_dir_close (dir);
 	g_free (subfolder_directory_path);
 
 	return ok;
Index: camel/providers/imap/ChangeLog
===================================================================
--- camel/providers/imap/ChangeLog	(revision 444)
+++ camel/providers/imap/ChangeLog	(working copy)
@@ -1,7 +1,67 @@
+2006-07-12  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-imap-provider.c:
+	adding trailing colon to string. Fixes bug #331858.
+
+2006-06-13  Andre Klapper <a9016009@gmx.de>
+
+	* camel-imap-store.c:
+	changing "couldn't", "can't" and "didn't" to proper
+	English. Fixes bug #342160.
+
+2006-05-22  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap-command.c (imap_read_untagged): Make sure the literal
+	length is non-negative (yes, some servers are sending negative
+	values here). Fixes Novell bug #177394.
+
+2006-05-19  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap-folder.c (imap_search_by_expression)
+	(imap_search_by_uids, imap_search_free): Get rid of the
+	search_lock and simply reuse the connect_lock.
+
+2006-05-18  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap-folder.c (camel_imap_folder_selected, imap_rename)
+	(imap_append_offline, imap_append_online, imap_append_resyncing)
+	(imap_transfer_offline, imap_transfer_online)
+	(imap_transfer_resyncing, camel_imap_folder_changed): Get rid of
+	the cache_lock and use the service connect_lock instead. Fixes
+	some possible deadlock conditions.
+
+2006-05-10  Parthasarathi Susarla <sparthasarathi@novell.com>
+
+	* camel-imap-folder.c: Add space at the end of
+	CAMEL_MESSAGE_INFO_HEADERS. The content-type header wont be
+	fetched otherwise(it mergers with the MESSAGE_LIST_HEADER).  This
+	fix shows the attachment icon in the message list
+
+2006-05-01  Jeffrey Stedfast  <fejj@novell.com>
+
+	Fix for bug #315976.
+
+	* camel-imap-store.c (construct): Only override the namespace if
+	the URL param override_namespace is also set.
+	(get_folder_info_offline): Always include INBOX if we are being
+	asked for the toplevel folder-info tree.
+	(refresh_refresh): Make sure to always query the server for INBOX.
+	(get_folder_info_online): Same.
+
+2006-04-21  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap-store.c (connect_to_server_wrapper): Don't do
+	fallback for SSL/TLS. Fixes bug #321797.
+
+2006-04-19  Sankar P  <psankar@novell.com>
+
+	* camel-imap-folder.c (imap_update_summary): Instead of
+	downloading HEADERS try to download the specific HEADER FIELDS so
+	that the initial loading time is considerably reduced.
+		
 2006-01-17  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
 	** See Bug #323106, #326385
-
 	* camel-imap-store.c:
 	(imap_connect_online):
 	(get_folder_online):
@@ -17,6 +77,14 @@
 
 	Committed on behalf of Ed Catmur - partha
 
+2006-01-12  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-imap-command.c: 
+	(imap_command_start):
+	(imap_command_continuation):
+	User g_return_val_if_fail instead of g_assert. Do not crash. 
+	Return gracefully.
+
 2006-01-10  Shreyas Srinivasan  <sshreyas@novell.com>
 
 	* camel-imap-store.c (camel_store_finalize): Fix #321812
@@ -25,22 +93,48 @@
 2005-12-14  Tor Lillqvist  <tml@novell.com>
 
 	Fix #323106:
-
+	
 	* camel-imap-store.c (camel_imap_store_summary_full_to_path,
 	camel_imap_store_summary_path_to_full): Remove extraneous
 	conversions from IMAP-UTF-7 to UTF-8 and back.
 
 	* camel-imap-command.c (imap_command_strdup_vprintf): Do the
-        conversion from UTF-8 to IMAP-UTF-7 only just before sending a
+	conversion from UTF-8 to IMAP-UTF-7 only just before sending a
 	request. Do it also for %S formats, as that is what the CREATE
 	command uses. But %S is used also for other commands (like LOGIN
 	and LIST), so maybe we really would need a new format that would
 	be used *only* for mailbox (folder) names, assuming it's only
 	mailbox names that use the IMAP-UTF-7 encoding. Or is that what %F
 	is intended for? But why then does CREATE use %S?
-			
-	Committed on behalf of Tor - partha
 
+2005-12-08  Tor Lillqvist  <tml@novell.com>
+
+	* camel-imap-folder.c: Drop unused <dirent.h>.
+
+	* camel-imap-message-cache.c: Use gstdio wrappers. Open files in
+	binary mode.
+	(camel_imap_message_cache_new): Use GDir instead of dirent API.
+	(insert_setup, camel_imap_message_cache_get): Trailing periods in
+	file names are silently dropped on Win32, so on Win32, so if we
+	would want to create a file with a name ending with a perioud,
+	append a tilde (just a random choice).
+
+	* camel-imap-provider.c: No external command possibility on Win32,
+	drop that part of the UI.
+
+	* camel-imap-store.c: Use gstdio wrappers.
+
+	* camel-imap-utils.c (find_folders_recursive): Use GDir instead of
+	dirent API.
+	
+2005-12-05  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-imap-store.c: (construct):
+	Setup disco journal during store construct. Previously,
+	it was dont in connect_offline and connect_online methods.
+	This makes sure that the diary is initialised even when evo
+	starts in offline mode.
+
 2005-12-01 Jeff Cai <jeff.cai@sun.com>
 
 	* camel-imap-command.c:(imap_command_strdup_vprintf):
@@ -53,6 +147,20 @@
 	Courier imap's LSUB response for INBOX when its not subscribed.
 	Fix #228929.
 	
+2005-10-21 Vivek Jain <jvivek@novell.com>
+	
+	Committed NotZed's patch on #314833
+	
+	** See #314833.
+	* camel-imap-store.c (subscribe_folder, unsubscribe_folder):
+	add missing locking.
+	(imap_noop): re-arrange locking slightly.
+
+2005-10-10  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-imap-folder.c:(imap_update_summary): specify the
+	folder name of the folde being refreshed in the status mesage
+
 2005-10-10  Björn Torkelsson <torkel@acc.umu.se>
 
 	** See bug #317956.
@@ -60,10 +168,10 @@
 	* camel-imap-store.c:(try_auth): Null check sasl_resp
         and bail out, otherwise evolution will crash when running strlen on
         sasl_resp. 
-
-	** Committed on behalf of Björn Torkelsson since he does not have
-	commit rights. - partha <sparthasarathi@novell.com>
 	
+	** Committed on behalf of Björn Torkelsson since he does not 
+	have commit rights - partha <sparthasarathi@novell.com>
+	
 2005-09-27  Vivek Jain <jvivek@novell.com>
 
 	** See bug #315173.
@@ -72,6 +180,27 @@
 	info before using it
 	initialize flags as we '&' with old value.
 
+2005-09-15  Tor Lillqvist  <tml@novell.com>
+
+	* camel-imap-command.c
+	* camel-imap-folder.c: Use g_ascii_str(n)casecmp() instead of
+	str(n)casecmp(). The strings we are comparing in these cases
+	should be just ASCII anyway, so spell it out that we really do
+	need ASCII casefolding only.
+
+	* camel-imap-folder.c
+	* camel-imap-search.c
+	* camel-imap-store.c: No strtok_r() in Microsoft's C library, but
+	strtok() is MT-safe, which is enough for the way it's used in this
+	file, to tokenize only one string at a time.
+
+	* camel-imap-store.c (connect_to_server_process,
+	connect_to_server_wrapper): Using custom commands to connect to
+	IMAP servers is not supported on Win32 (at least for now), so
+	bypass that code.
+
+	* camel-imap-wrapper.c: If no ENETUNREACH (Win32), use EINVAL.
+
 2005-08-23  Shreyas Srinivasan  <sshreyas@novell.com>
 
 	** See #314199
Index: camel/providers/imap/camel-imap-search.c
===================================================================
--- camel/providers/imap/camel-imap-search.c	(revision 444)
+++ camel/providers/imap/camel-imap-search.c	(working copy)
@@ -34,7 +34,6 @@
 #include "camel-imap-folder.h"
 #include "camel-imap-store.h"
 #include "camel-imap-search.h"
-#include "camel-imap-private.h"
 #include "camel-imap-utils.h"
 #include "camel-imap-summary.h"
 
@@ -46,6 +45,14 @@
 
 #define d(x)
 
+#ifdef G_OS_WIN32
+/* The strtok() in Microsoft's C library is MT-safe (but still uses
+ * only one buffer pointer per thread, but for the use of strtok_r()
+ * here that's enough).
+ */
+#define strtok_r(s,sep,lasts) (*(lasts)=strtok((s),(sep)))
+#endif
+
 /*
   File is:
    BODY	 (as in body search)
Index: camel/providers/imap/camel-imap-folder.c
===================================================================
--- camel/providers/imap/camel-imap-folder.c	(revision 444)
+++ camel/providers/imap/camel-imap-folder.c	(working copy)
@@ -23,13 +23,10 @@
  * USA
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h> 
-#endif
 
 #include <stdlib.h>
 #include <sys/types.h>
-#include <dirent.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <errno.h>
@@ -39,11 +36,12 @@
 
 /*#include "libedataserver/e-path.h"*/
 #include "libedataserver/e-time-utils.h"
+#include "libedataserver/e-data-server-util.h"
+#include "libedataserver/e-msgport.h"
 
 #include "camel-imap-folder.h"
 #include "camel-imap-command.h"
 #include "camel-imap-message-cache.h"
-#include "camel-imap-private.h"
 #include "camel-imap-search.h"
 #include "camel-imap-store.h"
 #include "camel-imap-summary.h"
@@ -72,6 +70,7 @@
 #include "camel-i18n.h"
 #include "camel/camel-store-summary.h"
 
+
 #define d(x) 
 
 /* set to -1 for infinite size (suggested max command-line length is
@@ -134,6 +133,14 @@
 
 static GData *parse_fetch_response (CamelImapFolder *imap_folder, char *msg_att);
 
+#ifdef G_OS_WIN32
+/* The strtok() in Microsoft's C library is MT-safe (but still uses
+ * only one buffer pointer per thread, but for the use of strtok_r()
+ * here that's enough).
+ */
+#define strtok_r(s,sep,lasts) (*(lasts)=strtok((s),(sep)))
+#endif
+
 static void
 camel_imap_folder_class_init (CamelImapFolderClass *camel_imap_folder_class)
 {
@@ -183,12 +190,6 @@
 	folder->folder_flags |= (CAMEL_FOLDER_HAS_SUMMARY_CAPABILITY |
 				 CAMEL_FOLDER_HAS_SEARCH_CAPABILITY);
 	
-	imap_folder->priv = g_malloc0(sizeof(*imap_folder->priv));
-#ifdef ENABLE_THREADS
-	imap_folder->priv->search_lock = e_mutex_new(E_MUTEX_SIMPLE);
-	imap_folder->priv->cache_lock = e_mutex_new(E_MUTEX_REC);
-#endif
-
 	imap_folder->need_rescan = TRUE;
 }
 
@@ -222,7 +223,7 @@
 	const char *short_name;
 	char *summary_file, *state_file;
 
-	if (camel_mkdir (folder_dir, S_IRWXU) != 0) {
+	if (e_util_mkdir_hier (folder_dir, S_IRWXU) != 0) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not create directory %s: %s"),
 				      folder_dir, g_strerror (errno));
@@ -296,22 +297,22 @@
 	
 	for (i = 0; i < response->untagged->len; i++) {
 		resp = response->untagged->pdata[i] + 2;
-		if (!strncasecmp (resp, "FLAGS ", 6) && !perm_flags) {
+		if (!g_ascii_strncasecmp (resp, "FLAGS ", 6) && !perm_flags) {
 			resp += 6;
 			folder->permanent_flags = imap_parse_flag_list (&resp);
-		} else if (!strncasecmp (resp, "OK [PERMANENTFLAGS ", 19)) {
+		} else if (!g_ascii_strncasecmp (resp, "OK [PERMANENTFLAGS ", 19)) {
 			resp += 19;
 			
 			/* workaround for broken IMAP servers that send "* OK [PERMANENTFLAGS ()] Permanent flags"
 			 * even tho they do allow storing flags. *Sigh* So many fucking broken IMAP servers out there. */
 			if ((perm_flags = imap_parse_flag_list (&resp)) != 0)
 				folder->permanent_flags = perm_flags;
-		} else if (!strncasecmp (resp, "OK [UIDVALIDITY ", 16)) {
+		} else if (!g_ascii_strncasecmp (resp, "OK [UIDVALIDITY ", 16)) {
 			validity = strtoul (resp + 16, NULL, 10);
 		} else if (isdigit ((unsigned char)*resp)) {
 			unsigned long num = strtoul (resp, &resp, 10);
 			
-			if (!strncasecmp (resp, " EXISTS", 7)) {
+			if (!g_ascii_strncasecmp (resp, " EXISTS", 7)) {
 				exists = num;
 				/* Remove from the response so nothing
 				 * else tries to interpret it.
@@ -341,9 +342,7 @@
 	else if (validity != imap_summary->validity) {
 		imap_summary->validity = validity;
 		camel_folder_summary_clear (folder->summary);
-		CAMEL_IMAP_FOLDER_LOCK (imap_folder, cache_lock);
 		camel_imap_message_cache_clear (imap_folder->cache);
-		CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
 		imap_folder->need_rescan = FALSE;
 		camel_imap_folder_changed (folder, exists, NULL, ex);
 		return;
@@ -377,7 +376,7 @@
 				exists = val;
 				continue;
 			}
-			if (uid != 0 || val != count || strncasecmp (resp, " FETCH (", 8) != 0)
+			if (uid != 0 || val != count || g_ascii_strncasecmp (resp, " FETCH (", 8) != 0)
 				continue;
 			
 			fetch_data = parse_fetch_response (imap_folder, resp + 7);
@@ -417,12 +416,6 @@
 		camel_object_unref (CAMEL_OBJECT (imap_folder->search));
 	if (imap_folder->cache)
 		camel_object_unref (CAMEL_OBJECT (imap_folder->cache));
-
-#ifdef ENABLE_THREADS
-	e_mutex_destroy(imap_folder->priv->search_lock);
-	e_mutex_destroy(imap_folder->priv->cache_lock);
-#endif
-	g_free(imap_folder->priv);
 }
 
 static int
@@ -469,26 +462,28 @@
 	CamelImapStore *imap_store = (CamelImapStore *)folder->parent_store;
 	char *folder_dir, *summary_path, *state_file;
 	char *folders;
-
+	
+	CAMEL_SERVICE_LOCK (imap_store, connect_lock);
+	
 	folders = g_strconcat (imap_store->storage_path, "/folders", NULL);
 	folder_dir = imap_path_to_physical (folders, new);
 	g_free (folders);
 	summary_path = g_strdup_printf("%s/summary", folder_dir);
-
-	CAMEL_IMAP_FOLDER_LOCK (folder, cache_lock);
+	
 	camel_imap_message_cache_set_path(imap_folder->cache, folder_dir);
-	CAMEL_IMAP_FOLDER_UNLOCK (folder, cache_lock);
-
+	
 	camel_folder_summary_set_filename(folder->summary, summary_path);
-
+	
 	state_file = g_strdup_printf ("%s/cmeta", folder_dir);
 	camel_object_set(folder, NULL, CAMEL_OBJECT_STATE_FILE, state_file, NULL);
 	g_free(state_file);
-
+	
 	g_free(summary_path);
 	g_free(folder_dir);
-
+	
 	((CamelFolderClass *)disco_folder_class)->rename(folder, new);
+	
+	CAMEL_SERVICE_UNLOCK (imap_store, connect_lock);
 }
 
 static void
@@ -625,7 +620,7 @@
 	}
 	
 	/* Check UIDs and flags of all messages we already know of. */
-	camel_operation_start (NULL, _("Scanning for changed messages"));
+	camel_operation_start (NULL, _("Scanning for changed messages in %s"), folder->name);
 	info = camel_folder_summary_index (folder->summary, summary_len - 1);
 	ok = camel_imap_command_start (store, folder, ex,
 				       "UID FETCH 1:%s (FLAGS)",
@@ -1196,21 +1191,23 @@
 	char *uid;
 
 	uid = get_temp_uid ();
-
+	
+	CAMEL_SERVICE_LOCK (imap_store, connect_lock);
+	
 	camel_imap_summary_add_offline (folder->summary, uid, message, info);
-	CAMEL_IMAP_FOLDER_LOCK (folder, cache_lock);
 	camel_imap_message_cache_insert_wrapper (cache, uid, "",
 						 CAMEL_DATA_WRAPPER (message), ex);
-	CAMEL_IMAP_FOLDER_UNLOCK (folder, cache_lock);
-
+	
 	changes = camel_folder_change_info_new ();
 	camel_folder_change_info_add_uid (changes, uid);
-	camel_object_trigger_event (CAMEL_OBJECT (folder), "folder_changed",
-				    changes);
+	camel_object_trigger_event (CAMEL_OBJECT (folder), "folder_changed", changes);
 	camel_folder_change_info_free (changes);
 
 	camel_disco_diary_log (CAMEL_DISCO_STORE (imap_store)->diary,
 			       CAMEL_DISCO_DIARY_FOLDER_APPEND, folder, uid);
+	
+	CAMEL_SERVICE_UNLOCK (imap_store, connect_lock);
+	
 	if (appended_uid)
 		*appended_uid = uid;
 	else
@@ -1321,21 +1318,22 @@
 	CamelImapResponse *response;
 	char *uid;
 	int count;
-
+	
+	CAMEL_SERVICE_LOCK (store, connect_lock);
+	
 	count = camel_folder_summary_count (folder->summary);
-	response = do_append (folder, message, info, &uid, ex);
-	if (!response)
+	if (!(response = do_append (folder, message, info, &uid, ex))) {
+		CAMEL_SERVICE_UNLOCK (store, connect_lock);
 		return;
+	}
 	
 	if (uid) {
 		/* Cache first, since freeing response may trigger a
 		 * summary update that will want this information.
 		 */
-		CAMEL_IMAP_FOLDER_LOCK (folder, cache_lock);
 		camel_imap_message_cache_insert_wrapper (
 			CAMEL_IMAP_FOLDER (folder)->cache, uid,
 			"", CAMEL_DATA_WRAPPER (message), ex);
-		CAMEL_IMAP_FOLDER_UNLOCK (folder, cache_lock);
 		if (appended_uid)
 			*appended_uid = uid;
 		else
@@ -1346,10 +1344,10 @@
 	camel_imap_response_free (store, response);
 	
 	/* Make sure a "folder_changed" is emitted. */
-	CAMEL_SERVICE_LOCK (store, connect_lock);
 	if (store->current_folder != folder ||
 	    camel_folder_summary_count (folder->summary) == count)
 		imap_refresh_info (folder, ex);
+	
 	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 }
 
@@ -1362,19 +1360,20 @@
 	CamelImapResponse *response;
 	char *uid;
 	
-	response = do_append (folder, message, info, &uid, ex);
-	if (!response)
+	CAMEL_SERVICE_LOCK (store, connect_lock);
+	
+	if (!(response = do_append (folder, message, info, &uid, ex))) {
+		CAMEL_SERVICE_UNLOCK (store, connect_lock);
 		return;
+	}
 	
 	if (uid) {
 		CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
 		const char *olduid = camel_message_info_uid (info);
 		
-		CAMEL_IMAP_FOLDER_LOCK (imap_folder, cache_lock);
 		camel_imap_message_cache_copy (imap_folder->cache, olduid,
 					       imap_folder->cache, uid, ex);
-		CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
-
+		
 		if (appended_uid)
 			*appended_uid = uid;
 		else
@@ -1383,6 +1382,8 @@
 		*appended_uid = NULL;
 	
 	camel_imap_response_free (store, response);
+	
+	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 }
 
 
@@ -1399,17 +1400,9 @@
 	CamelMessageInfo *mi;
 	char *uid, *destuid;
 	int i;
-
-	/* We grab the store's command lock first, and then grab the
-	 * source and destination cache_locks. This way we can't
-	 * deadlock in the case where we're simultaneously also trying
-	 * to copy messages in the other direction from another thread.
-	 */
+	
 	CAMEL_SERVICE_LOCK (store, connect_lock);
-	CAMEL_IMAP_FOLDER_LOCK (source, cache_lock);
-	CAMEL_IMAP_FOLDER_LOCK (dest, cache_lock);
-	CAMEL_SERVICE_UNLOCK (store, connect_lock);
-
+	
 	if (transferred_uids) {
 		*transferred_uids = g_ptr_array_new ();
 		g_ptr_array_set_size (*transferred_uids, uids->len);
@@ -1445,16 +1438,15 @@
 		if (delete_originals)
 			camel_folder_delete_message (source, uid);
 	}
-
-	CAMEL_IMAP_FOLDER_UNLOCK (dest, cache_lock);
-	CAMEL_IMAP_FOLDER_UNLOCK (source, cache_lock);
-
+	
 	camel_object_trigger_event (CAMEL_OBJECT (dest), "folder_changed", changes);
 	camel_folder_change_info_free (changes);
 
 	camel_disco_diary_log (CAMEL_DISCO_STORE (store)->diary,
 			       CAMEL_DISCO_DIARY_FOLDER_TRANSFER,
 			       source, dest, uids, delete_originals);
+	
+	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 }
 
 static void
@@ -1484,22 +1476,14 @@
 
 	src = imap_uid_set_to_array (source->summary, srcset);
 	dest = imap_uid_set_to_array (destination->summary, destset);
-
+	
 	if (src && dest && src->len == dest->len) {
-		/* We don't have to worry about deadlocking on the
-		 * cache locks here, because we've got the store's
-		 * command lock too, so no one else could be here.
-		 */
-		CAMEL_IMAP_FOLDER_LOCK (source, cache_lock);
-		CAMEL_IMAP_FOLDER_LOCK (destination, cache_lock);
 		for (i = 0; i < src->len; i++) {
 			camel_imap_message_cache_copy (scache, src->pdata[i],
 						       dcache, dest->pdata[i],
 						       NULL);
 		}
-		CAMEL_IMAP_FOLDER_UNLOCK (source, cache_lock);
-		CAMEL_IMAP_FOLDER_UNLOCK (destination, cache_lock);
-
+		
 		imap_uid_array_free (src);
 		imap_uid_array_free (dest);
 		return;
@@ -1561,7 +1545,9 @@
 	qsort (uids->pdata, uids->len, sizeof (void *), uid_compar);
 	
 	/* Now copy the messages */
+	CAMEL_SERVICE_LOCK (store, connect_lock);
 	do_copy(source, uids, dest, delete_originals, ex);
+	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 	if (camel_exception_is_set (ex))
 		return;
 
@@ -1581,12 +1567,15 @@
 			 gboolean delete_originals, CamelException *ex)
 {
 	CamelDiscoDiary *diary = CAMEL_DISCO_STORE (source->parent_store)->diary;
+	CamelStore *store = source->parent_store;
 	GPtrArray *realuids;
 	int first, i;
 	const char *uid;
 	CamelMimeMessage *message;
 	CamelMessageInfo *info;
 	
+	CAMEL_SERVICE_LOCK (store, connect_lock);
+	
 	qsort (uids->pdata, uids->len, sizeof (void *), uid_compar);
 	
 	/* This is trickier than append_resyncing, because some of
@@ -1643,10 +1632,12 @@
 	}
 
 	g_ptr_array_free (realuids, FALSE);
-
+	
 	/* FIXME */
 	if (transferred_uids)
 		*transferred_uids = NULL;
+	
+	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 }
 
 static GPtrArray *
@@ -1654,36 +1645,36 @@
 {
 	CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
 	GPtrArray *matches;
-
+	
 	/* we could get around this by creating a new search object each time,
 	   but i doubt its worth it since any long operation would lock the
 	   command channel too */
-	CAMEL_IMAP_FOLDER_LOCK(folder, search_lock);
-
+	CAMEL_SERVICE_LOCK (folder->parent_store, connect_lock);
+	
 	camel_folder_search_set_folder (imap_folder->search, folder);
 	matches = camel_folder_search_search(imap_folder->search, expression, NULL, ex);
-
-	CAMEL_IMAP_FOLDER_UNLOCK(folder, search_lock);
-
+	
+	CAMEL_SERVICE_UNLOCK (folder->parent_store, connect_lock);
+	
 	return matches;
 }
 
 static GPtrArray *
-imap_search_by_uids(CamelFolder *folder, const char *expression, GPtrArray *uids, CamelException *ex)
+imap_search_by_uids (CamelFolder *folder, const char *expression, GPtrArray *uids, CamelException *ex)
 {
-	CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER(folder);
+	CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
 	GPtrArray *matches;
-
+	
 	if (uids->len == 0)
-		return g_ptr_array_new();
-
-	CAMEL_IMAP_FOLDER_LOCK(folder, search_lock);
-
+		return g_ptr_array_new ();
+	
+	CAMEL_SERVICE_LOCK (folder->parent_store, connect_lock);
+	
 	camel_folder_search_set_folder(imap_folder->search, folder);
 	matches = camel_folder_search_search(imap_folder->search, expression, uids, ex);
-
-	CAMEL_IMAP_FOLDER_UNLOCK(folder, search_lock);
-
+	
+	CAMEL_SERVICE_UNLOCK (folder->parent_store, connect_lock);
+	
 	return matches;
 }
 
@@ -1691,14 +1682,14 @@
 imap_search_free (CamelFolder *folder, GPtrArray *uids)
 {
 	CamelImapFolder *imap_folder = CAMEL_IMAP_FOLDER (folder);
-
+	
 	g_return_if_fail (imap_folder->search);
-
-	CAMEL_IMAP_FOLDER_LOCK(folder, search_lock);
-
+	
+	CAMEL_SERVICE_LOCK (folder->parent_store, connect_lock);
+	
 	camel_folder_search_free_result (imap_folder->search, uids);
-
-	CAMEL_IMAP_FOLDER_UNLOCK(folder, search_lock);
+	
+	CAMEL_SERVICE_UNLOCK (folder->parent_store, connect_lock);
 }
 
 static CamelMimeMessage *get_message (CamelImapFolder *imap_folder,
@@ -2050,7 +2041,7 @@
 	CamelMimeMessage *msg = NULL;
 	CamelStream *stream = NULL;
 	int retry;
-
+	
 	mi = (CamelImapMessageInfo *)camel_folder_summary_uid (folder->summary, uid);
 	if (mi == NULL) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_FOLDER_INVALID_UID,
@@ -2060,7 +2051,7 @@
 
 	/* If its cached in full, just get it as is, this is only a shortcut,
 	   since we get stuff from the cache anyway.  It affects a busted connection though. */
-	if ( (stream = camel_imap_folder_fetch_data(imap_folder, uid, "", TRUE, NULL))
+	if ((stream = camel_imap_folder_fetch_data(imap_folder, uid, "", TRUE, NULL))
 	     && (msg = get_message_simple(imap_folder, uid, stream, ex)))
 		goto done;
 
@@ -2089,7 +2080,7 @@
 				char *body, *found_uid;
 				int i;
 				
-				CAMEL_SERVICE_LOCK(store, connect_lock);
+				CAMEL_SERVICE_LOCK (store, connect_lock);
 				if (!camel_imap_store_connected(store, ex)) {
 					CAMEL_SERVICE_UNLOCK(store, connect_lock);
 					camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
@@ -2098,8 +2089,7 @@
 				}
 				
 				response = camel_imap_command (store, folder, ex, "UID FETCH %s BODY", uid);
-				CAMEL_SERVICE_UNLOCK(store, connect_lock);
-
+				
 				if (response) {
 					for (i = 0, body = NULL; i < response->untagged->len; i++) {
 						fetch_data = parse_fetch_response (imap_folder, response->untagged->pdata[i]);
@@ -2119,7 +2109,7 @@
 						imap_parse_body ((const char **) &body, folder, mi->info.content);
 						camel_folder_summary_touch (folder->summary);
 					}
-
+					
 					if (fetch_data)
 						g_datalist_clear (&fetch_data);
 					
@@ -2127,6 +2117,8 @@
 				} else {
 					camel_exception_clear(ex);
 				}
+				
+				CAMEL_SERVICE_UNLOCK (store, connect_lock);
 			}
 
 			if (camel_debug_start("imap:folder")) {
@@ -2240,7 +2232,7 @@
 		return (time_t) -1;
 	
 	for (n = 0; n < 12; n++) {
-		if (!strncasecmp (inptr, tm_months[n], 3))
+		if (!g_ascii_strncasecmp (inptr, tm_months[n], 3))
 			break;
 	}
 	
@@ -2304,6 +2296,7 @@
 	}
 	
 	mi = (CamelImapMessageInfo *)camel_folder_summary_info_new_from_message (folder->summary, msg);
+	
 	camel_object_unref (CAMEL_OBJECT (msg));
 	
 	if ((idate = g_datalist_get_data (&data, "INTERNALDATE")))
@@ -2316,7 +2309,7 @@
 }
 
 
-#define CAMEL_MESSAGE_INFO_HEADERS "DATE FROM TO CC SUBJECT REFERENCES IN-REPLY-TO MESSAGE-ID MIME-VERSION CONTENT-TYPE"
+#define CAMEL_MESSAGE_INFO_HEADERS "DATE FROM TO CC SUBJECT REFERENCES IN-REPLY-TO MESSAGE-ID MIME-VERSION CONTENT-TYPE "
 
 /* FIXME: this needs to be kept in sync with camel-mime-utils.c's list
    of mailing-list headers and so might be best if this were
@@ -2342,7 +2335,7 @@
 	
 	CAMEL_SERVICE_ASSERT_LOCKED (store, connect_lock);
 	if (store->server_level >= IMAP_LEVEL_IMAP4REV1)
-		header_spec = "HEADER";
+		header_spec = "HEADER.FIELDS (" CAMEL_MESSAGE_INFO_HEADERS MAILING_LIST_HEADERS ")";
 	else
 		header_spec = "0";
 	
@@ -2366,7 +2359,7 @@
 				       "UID FETCH %d:* (FLAGS RFC822.SIZE INTERNALDATE BODY.PEEK[%s])",
 				       uidval + 1, header_spec))
 		return;
-	camel_operation_start (NULL, _("Fetching summary information for new messages"));
+	camel_operation_start (NULL, _("Fetching summary information for new messages in %s"), folder->name);
 	
 	/* Parse the responses. We can't add a message to the summary
 	 * until we've gotten its headers, and there's no guarantee
@@ -2436,7 +2429,7 @@
 		qsort (needheaders->pdata, needheaders->len,
 		       sizeof (void *), uid_compar);
 		
-		camel_operation_start (NULL, _("Fetching summary information for new messages"));
+		camel_operation_start (NULL, _("Fetching summary information for new messages in %s"), folder->name);
 		
 		while (uid < needheaders->len) {
 			uidset = imap_uid_array_to_set (folder->summary, needheaders, uid, UID_SET_LIMIT, &uid);
@@ -2519,8 +2512,11 @@
 		}
 		
 		uid = g_datalist_get_data (&data, "UID");
+
+		/* This strdup() might not get freed since the mmap() patch! */
 		if (uid)
 			mi->info.uid = g_strdup (uid);
+
 		flags = GPOINTER_TO_INT (g_datalist_get_data (&data, "FLAGS"));
 		if (flags) {
 			((CamelImapMessageInfo *)mi)->server_flags = flags;
@@ -2578,7 +2574,7 @@
 		if ((mi->info.flags & CAMEL_IMAP_MESSAGE_RECENT))
 			camel_folder_change_info_recent_uid(changes, camel_message_info_uid (mi));
 	}
-	
+
 	for ( ; i < messages->len; i++) {
 		if ((mi = messages->pdata[i]))
 			camel_message_info_free(&mi->info);
@@ -2631,9 +2627,7 @@
 			}
 			
 			camel_folder_change_info_remove_uid (changes, camel_message_info_uid (info));
-			CAMEL_IMAP_FOLDER_LOCK (imap_folder, cache_lock);
 			camel_imap_message_cache_remove (imap_folder->cache, camel_message_info_uid (info));
-			CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
 			camel_folder_summary_remove (folder->summary, info);
 			camel_message_info_free(info);
 		}
@@ -2680,36 +2674,23 @@
 	char *found_uid;
 	int i;
 	
-	/* EXPUNGE responses have to modify the cache, which means
-	 * they have to grab the cache_lock while holding the
-	 * connect_lock.
-
-	 * Because getting the service lock may cause MUCH unecessary
-	 * delay when we already have the data locally, we do the
-	 * locking separately.  This could cause a race
-	 * getting the same data from the cache, but that is only
-	 * an inefficiency, and bad luck.
-	 */
-	CAMEL_IMAP_FOLDER_LOCK (imap_folder, cache_lock);
+	CAMEL_SERVICE_LOCK (store, connect_lock);
 	stream = camel_imap_message_cache_get (imap_folder->cache, uid, section_text, ex);
 	if (!stream && (!strcmp (section_text, "HEADER") || !strcmp (section_text, "0"))) {
 		camel_exception_clear (ex);
 		stream = camel_imap_message_cache_get (imap_folder->cache, uid, "", ex);
 	}
-	CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
 	
-	if (stream || cache_only)
+	if (stream || cache_only) {
+		CAMEL_SERVICE_UNLOCK (store, connect_lock);
 		return stream;
-
+	}
+	
 	camel_exception_clear(ex);
-
-	CAMEL_SERVICE_LOCK (store, connect_lock);
-	CAMEL_IMAP_FOLDER_LOCK (imap_folder, cache_lock);
-
+	
 	if (!camel_imap_store_connected(store, ex)) {
 		camel_exception_set (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 				     _("This message is not currently available"));
-		CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
 		CAMEL_SERVICE_UNLOCK (store, connect_lock);
 		return NULL;
 	}
@@ -2724,11 +2705,9 @@
 					       "UID FETCH %s BODY.PEEK[%s]",
 					       uid, section_text);
 	}
-	/* We won't need the connect_lock again after this. */
-	CAMEL_SERVICE_UNLOCK (store, connect_lock);
 	
 	if (!response) {
-		CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
+		CAMEL_SERVICE_UNLOCK (store, connect_lock);
 		return NULL;
 	}
 	
@@ -2742,8 +2721,9 @@
 		g_datalist_clear (&fetch_data);
 		stream = NULL;
 	}
+	
 	camel_imap_response_free (store, response);
-	CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
+	
 	if (!stream) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 				      _("Could not find message body in FETCH response."));
@@ -2752,6 +2732,8 @@
 		g_datalist_clear (&fetch_data);
 	}
 	
+	CAMEL_SERVICE_UNLOCK (store, connect_lock);
+	
 	return stream;
 }
 
@@ -2763,6 +2745,8 @@
 	gboolean cache_header = TRUE, header = FALSE;
 	size_t body_len = 0;
 	
+	CAMEL_SERVICE_ASSERT_LOCKED (((CamelFolder *) imap_folder)->parent_store, connect_lock);
+	
 	if (*response != '(') {
 		long seq;
 		
@@ -2771,7 +2755,7 @@
 		seq = strtol (response + 2, &response, 10);
 		if (seq == 0)
 			return NULL;
-		if (strncasecmp (response, " FETCH (", 8) != 0)
+		if (g_ascii_strncasecmp (response, " FETCH (", 8) != 0)
 			return NULL;
 		response += 7;
 		
@@ -2782,7 +2766,7 @@
 		/* Skip the initial '(' or the ' ' between elements */
 		response++;
 		
-		if (!strncasecmp (response, "FLAGS ", 6)) {
+		if (!g_ascii_strncasecmp (response, "FLAGS ", 6)) {
 			guint32 flags;
 			
 			response += 6;
@@ -2790,25 +2774,25 @@
 			flags = imap_parse_flag_list (&response);
 			
 			g_datalist_set_data (&data, "FLAGS", GUINT_TO_POINTER (flags));
-		} else if (!strncasecmp (response, "RFC822.SIZE ", 12)) {
+		} else if (!g_ascii_strncasecmp (response, "RFC822.SIZE ", 12)) {
 			unsigned long size;
 			
 			response += 12;
 			size = strtoul (response, &response, 10);
 			g_datalist_set_data (&data, "RFC822.SIZE", GUINT_TO_POINTER (size));
-		} else if (!strncasecmp (response, "BODY[", 5) ||
-			   !strncasecmp (response, "RFC822 ", 7)) {
+		} else if (!g_ascii_strncasecmp (response, "BODY[", 5) ||
+			   !g_ascii_strncasecmp (response, "RFC822 ", 7)) {
 			char *p;
 			
 			if (*response == 'B') {
 				response += 5;
 				
 				/* HEADER], HEADER.FIELDS (...)], or 0] */
-				if (!strncasecmp (response, "HEADER", 6)) {
+				if (!g_ascii_strncasecmp (response, "HEADER", 6)) {
 					header = TRUE;
-					if (!strncasecmp (response + 6, ".FIELDS", 7))
+					if (!g_ascii_strncasecmp (response + 6, ".FIELDS", 7))
 						cache_header = FALSE;
-				} else if (!strncasecmp (response, "0]", 2))
+				} else if (!g_ascii_strncasecmp (response, "0]", 2))
 					header = TRUE;
 				
 				p = strchr (response, ']');
@@ -2825,7 +2809,7 @@
 				part_spec = g_strdup ("");
 				response += 7;
 				
-				if (!strncasecmp (response, "HEADER", 6))
+				if (!g_ascii_strncasecmp (response, "HEADER", 6))
 					header = TRUE;
 			}
 			
@@ -2840,20 +2824,20 @@
 			g_datalist_set_data_full (&data, "BODY_PART_SPEC", part_spec, g_free);
 			g_datalist_set_data_full (&data, "BODY_PART_DATA", body, g_free);
 			g_datalist_set_data (&data, "BODY_PART_LEN", GINT_TO_POINTER (body_len));
-		} else if (!strncasecmp (response, "BODY ", 5) ||
-			   !strncasecmp (response, "BODYSTRUCTURE ", 14)) {
+		} else if (!g_ascii_strncasecmp (response, "BODY ", 5) ||
+			   !g_ascii_strncasecmp (response, "BODYSTRUCTURE ", 14)) {
 			response = strchr (response, ' ') + 1;
 			start = response;
 			imap_skip_list ((const char **) &response);
 			g_datalist_set_data_full (&data, "BODY", g_strndup (start, response - start), g_free);
-		} else if (!strncasecmp (response, "UID ", 4)) {
+		} else if (!g_ascii_strncasecmp (response, "UID ", 4)) {
 			int len;
 			
 			len = strcspn (response + 4, " )");
 			uid = g_strndup (response + 4, len);
 			g_datalist_set_data_full (&data, "UID", uid, g_free);
 			response += 4 + len;
-		} else if (!strncasecmp (response, "INTERNALDATE ", 13)) {
+		} else if (!g_ascii_strncasecmp (response, "INTERNALDATE ", 13)) {
 			int len;
 			
 			response += 13;
@@ -2881,11 +2865,9 @@
 		if (header && !cache_header) {
 			stream = camel_stream_mem_new_with_buffer (body, body_len);
 		} else {
-			CAMEL_IMAP_FOLDER_LOCK (imap_folder, cache_lock);
 			stream = camel_imap_message_cache_insert (imap_folder->cache,
 								  uid, part_spec,
 								  body, body_len, NULL);
-			CAMEL_IMAP_FOLDER_UNLOCK (imap_folder, cache_lock);
 			if (stream == NULL)
 				stream = camel_stream_mem_new_with_buffer (body, body_len);
 		}
Index: camel/providers/imap/camel-imap-command.c
===================================================================
--- camel/providers/imap/camel-imap-command.c	(revision 444)
+++ camel/providers/imap/camel-imap-command.c	(working copy)
@@ -38,7 +38,6 @@
 #include "camel-imap-folder.h"
 #include "camel-imap-store.h"
 #include "camel-imap-store-summary.h"
-#include "camel-imap-private.h"
 #include <camel/camel-exception.h>
 #include <camel/camel-private.h>
 #include <camel/camel-utf8.h>
@@ -50,8 +49,8 @@
 
 static gboolean imap_command_start (CamelImapStore *store, CamelFolder *folder,
 				    const char *cmd, CamelException *ex);
-CamelImapResponse *imap_read_response (CamelImapStore *store,
-				       CamelException *ex);
+static CamelImapResponse *imap_read_response (CamelImapStore *store,
+					      CamelException *ex);
 static char *imap_read_untagged (CamelImapStore *store, char *line,
 				 CamelException *ex);
 static char *imap_command_strdup_vprintf (CamelImapStore *store,
@@ -211,10 +210,10 @@
 		else
 			mask = cmd;
 		
-		fprintf (stderr, "sending : %c%.5d %s\r\n", store->tag_prefix, store->command, mask);
+		fprintf (stderr, "sending : %c%.5u %s\r\n", store->tag_prefix, store->command, mask);
 	}
 	
-	nwritten = camel_stream_printf (store->ostream, "%c%.5d %s\r\n",
+	nwritten = camel_stream_printf (store->ostream, "%c%.5u %s\r\n",
 					store->tag_prefix, store->command++, cmd);
 	
 	if (nwritten == -1) {
@@ -439,10 +438,9 @@
 		fulllen += str->len;
 		g_ptr_array_add (data, str);
 		
-		p = strrchr (str->str, '{');
-		if (!p)
+		if (!(p = strrchr (str->str, '{')) || p[1] == '-')
 			break;
-
+		
 		/* HACK ALERT: We scan the non-literal part of the string, looking for possible s expression braces.
 		   This assumes we're getting s-expressions, which we should be.
 		   This is so if we get a blank line after a literal, in an s-expression, we can keep going, since
@@ -530,7 +528,7 @@
 		 * don't want it to be shorter either, because then the
 		 * GString's length would be off...
 		 */
-		sprintf (p, "{%0*d}", ldigits, length);
+		sprintf (p, "{%0*u}", ldigits, length);
 		
 		fulllen += str->len;
 		g_ptr_array_add (data, str);
Index: camel/providers/imap/camel-imap-folder.h
===================================================================
--- camel/providers/imap/camel-imap-folder.h	(revision 444)
+++ camel/providers/imap/camel-imap-folder.h	(working copy)
@@ -44,9 +44,7 @@
 
 struct _CamelImapFolder {
 	CamelDiscoFolder parent_object;
-
-	struct _CamelImapFolderPrivate *priv;
-
+	
 	CamelFolderSearch *search;
 	CamelImapMessageCache *cache;
 
Index: camel/providers/imap/camel-imap-wrapper.c
===================================================================
--- camel/providers/imap/camel-imap-wrapper.c	(revision 444)
+++ camel/providers/imap/camel-imap-wrapper.c	(working copy)
@@ -30,7 +30,6 @@
 
 #include "camel-imap-folder.h"
 #include "camel-imap-wrapper.h"
-#include "camel-imap-private.h"
 #include "camel-exception.h"
 #include "camel-stream-filter.h"
 #include "camel-mime-filter-basic.h"
@@ -38,6 +37,17 @@
 #include "camel-mime-filter-charset.h"
 #include "camel-mime-part.h"
 
+#include "libedataserver/e-msgport.h"
+
+
+struct _CamelImapWrapperPrivate {
+	GMutex *lock;
+};
+
+#define CAMEL_IMAP_WRAPPER_LOCK(f, l) (g_mutex_lock(((CamelImapWrapper *)f)->priv->l))
+#define CAMEL_IMAP_WRAPPER_UNLOCK(f, l) (g_mutex_unlock(((CamelImapWrapper *)f)->priv->l))
+
+
 static CamelDataWrapperClass *parent_class = NULL;
 
 /* Returns the class for a CamelDataWrapper */
@@ -68,10 +78,9 @@
 		g_free (imap_wrapper->uid);
 	if (imap_wrapper->part)
 		g_free (imap_wrapper->part_spec);
-
-#ifdef ENABLE_THREADS
+	
 	g_mutex_free (imap_wrapper->priv->lock);
-#endif
+	
 	g_free (imap_wrapper->priv);
 }
 
@@ -81,9 +90,7 @@
 	CamelImapWrapper *imap_wrapper = CAMEL_IMAP_WRAPPER (object);
 
 	imap_wrapper->priv = g_new0 (struct _CamelImapWrapperPrivate, 1);
-#ifdef ENABLE_THREADS
 	imap_wrapper->priv->lock = g_mutex_new ();
-#endif
 }
 
 CamelType
@@ -139,7 +146,12 @@
 			imap_wrapper->part_spec, FALSE, NULL);
 		if (!datastream) {
 			CAMEL_IMAP_WRAPPER_UNLOCK (imap_wrapper, lock);
+#ifdef ENETUNREACH
 			errno = ENETUNREACH;
+#else
+#warning FIXME: what errno to use if no ENETUNREACH
+			errno = EINVAL;
+#endif
 			return -1;
 		}
 		
Index: camel/providers/imap/camel-imap-message-cache.c
===================================================================
--- camel/providers/imap/camel-imap-message-cache.c	(revision 444)
+++ camel/providers/imap/camel-imap-message-cache.c	(working copy)
@@ -22,12 +22,9 @@
  * USA
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <sys/types.h>
-#include <dirent.h>
 #include <errno.h>
 #include <string.h>
 #include <ctype.h>
@@ -38,6 +35,12 @@
 #include "camel-stream-fs.h"
 #include "camel-i18n.h"
 
+#include <glib/gstdio.h>
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
 static void finalize (CamelImapMessageCache *cache);
 static void stream_finalize (CamelObject *stream, gpointer event_data, gpointer user_data);
 
@@ -144,17 +147,19 @@
 			      CamelException *ex)
 {
 	CamelImapMessageCache *cache;
-	DIR *dir;
-	struct dirent *d;
+	GDir *dir;
+	const char *dname;
 	char *uid, *p;
 	GPtrArray *deletes;
 	CamelMessageInfo *info;
+	GError *error;
 
-	dir = opendir (path);
+	dir = g_dir_open (path, 0, &error);
 	if (!dir) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not open cache directory: %s"),
-				      g_strerror (errno));
+				      error->message);
+		g_error_free (error);
 		return NULL;
 	}
 
@@ -164,28 +169,27 @@
 	cache->parts = g_hash_table_new (g_str_hash, g_str_equal);
 	cache->cached = g_hash_table_new (NULL, NULL);
 	deletes = g_ptr_array_new ();
-	while ((d = readdir (dir))) {
-		if (!isdigit (d->d_name[0]))
+	while ((dname = g_dir_read_name (dir))) {
+		if (!isdigit (dname[0]))
 			continue;
-
-		p = strchr (d->d_name, '.');
+		p = strchr (dname, '.');
 		if (p)
-			uid = g_strndup (d->d_name, p - d->d_name);
+			uid = g_strndup (dname, p - dname);
 		else
-			uid = g_strdup (d->d_name);
+			uid = g_strdup (dname);
 
 		info = camel_folder_summary_uid (summary, uid);
 		if (info) {
 			camel_message_info_free(info);
-			cache_put (cache, uid, d->d_name, NULL);
+			cache_put (cache, uid, dname, NULL);
 		} else
-			g_ptr_array_add (deletes, g_strdup_printf ("%s/%s", cache->path, d->d_name));
+			g_ptr_array_add (deletes, g_strdup_printf ("%s/%s", cache->path, dname));
 		g_free (uid);
 	}
-	closedir (dir);
+	g_dir_close (dir);
 
 	while (deletes->len) {
-		unlink (deletes->pdata[0]);
+		g_unlink (deletes->pdata[0]);
 		g_free (deletes->pdata[0]);
 		g_ptr_array_remove_index_fast (deletes, 0);
 	}
@@ -241,13 +245,22 @@
 	CamelStream *stream;
 	int fd;
 	
+#ifdef G_OS_WIN32
+	/* Trailing periods in file names are silently dropped on
+	 * Win32, argh. The code in this file requires the period to
+	 * be there. So in case part_spec is empty, use a tilde (just
+	 * a random choice) instead.
+	 */
+	if (!*part_spec)
+		part_spec = "~";
+#endif
 	*path = g_strdup_printf ("%s/%s.%s", cache->path, uid, part_spec);
 	*key = strrchr (*path, '/') + 1;
 	stream = g_hash_table_lookup (cache->parts, *key);
 	if (stream)
 		camel_object_unref (CAMEL_OBJECT (stream));
 	
-	fd = open (*path, O_RDWR | O_CREAT | O_TRUNC, 0600);
+	fd = g_open (*path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0600);
 	if (fd == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Failed to cache message %s: %s"),
@@ -262,7 +275,7 @@
 static CamelStream *
 insert_abort (char *path, CamelStream *stream)
 {
-	unlink (path);
+	g_unlink (path);
 	g_free (path);
 	camel_object_unref (CAMEL_OBJECT (stream));
 	return NULL;
@@ -400,6 +413,11 @@
 	if (uid[0] == 0)
 		return NULL;
 	
+#ifdef G_OS_WIN32
+	/* See comment in insert_setup() */
+	if (!*part_spec)
+		part_spec = "~";
+#endif
 	path = g_strdup_printf ("%s/%s.%s", cache->path, uid, part_spec);
 	key = strrchr (path, '/') + 1;
 	stream = g_hash_table_lookup (cache->parts, key);
@@ -445,7 +463,7 @@
 	for (i = 0; i < subparts->len; i++) {
 		key = subparts->pdata[i];
 		path = g_strdup_printf ("%s/%s", cache->path, key);
-		unlink (path);
+		g_unlink (path);
 		g_free (path);
 		stream = g_hash_table_lookup (cache->parts, key);
 		if (stream) {
@@ -519,7 +537,7 @@
 		part = strchr (subparts->pdata[i], '.');
 		if (!part++)
 			continue;
-		
+
 		if ((stream = camel_imap_message_cache_get (source, source_uid, part, ex))) {
 			camel_imap_message_cache_insert_stream (dest, dest_uid, part, stream, ex);
 			camel_object_unref (CAMEL_OBJECT (stream));
Index: camel/providers/imap/Makefile.am
===================================================================
--- camel/providers/imap/Makefile.am	(revision 444)
+++ camel/providers/imap/Makefile.am	(working copy)
@@ -37,8 +37,7 @@
 	camel-imap-summary.h			\
 	camel-imap-types.h			\
 	camel-imap-utils.h			\
-	camel-imap-wrapper.h			\
-	camel-imap-private.h
+	camel-imap-wrapper.h
 
 libcamelimap_la_LDFLAGS = -avoid-version -module $(NO_UNDEFINED)
 
Index: camel/providers/imap/camel-imap-store-summary.c
===================================================================
--- camel/providers/imap/camel-imap-store-summary.c	(revision 444)
+++ camel/providers/imap/camel-imap-store-summary.c	(working copy)
@@ -211,7 +211,7 @@
 char *
 camel_imap_store_summary_path_to_full(CamelImapStoreSummary *s, const char *path, char dir_sep)
 {
-	unsigned char *full, *f;
+	char *full, *f;
 	guint32 c, v = 0;
 	const char *p;
 	int state=0;
@@ -248,7 +248,7 @@
 	else
 		p = path;
 
-	while ( (c = camel_utf8_getc((const unsigned char **)&p)) ) {
+	while ((c = camel_utf8_getc((const unsigned char **)&p))) {
 		switch(state) {
 		case 0:
 			if (c == '%')
@@ -469,27 +469,44 @@
 	guint32 sep = '/';
 
 	ns = g_malloc0(sizeof(*ns));
-	if (camel_file_util_decode_string(in, &ns->path) == -1
-	    || camel_file_util_decode_string(in, &ns->full_name) == -1
-	    || camel_file_util_decode_uint32(in, &sep) == -1) {
-		namespace_free(s, ns);
-		ns = NULL;
-	} else {
-		ns->sep = sep;
-	}
 
+	if (camel_file_util_decode_string(in, &ns->path) == -1)
+		goto nserror;
+
+	if (camel_file_util_decode_string(in, &ns->full_name) == -1)
+		goto nserror;
+	
+	if (camel_file_util_decode_uint32(in, &sep) == -1)
+		goto nserror;
+
+	ns->sep = sep;
+
 	return ns;
+
+ nserror:
+
+	namespace_free(s, ns);
+	return NULL;
 }
 
 static int
 namespace_save(CamelStoreSummary *s, FILE *in, CamelImapStoreNamespace *ns)
 {
-	if (camel_file_util_encode_string(in, ns->path) == -1
-	    || camel_file_util_encode_string(in, ns->full_name) == -1
-	    || camel_file_util_encode_uint32(in, (guint32)ns->sep) == -1)
-		return -1;
+	if (camel_file_util_encode_string(in, ns->path) == -1)
+		goto serr;
 
+	if (camel_file_util_encode_string(in, ns->full_name) == -1)
+		goto serr;
+
+	if (camel_file_util_encode_uint32(in, (guint32)ns->sep) == -1)
+		goto serr;
+
 	return 0;
+
+ serr:
+	printf ("Error happend while writing\n");
+	return -1;
+
 }
 
 static int
Index: camel/providers/imap/camel-imap-provider.c
===================================================================
--- camel/providers/imap/camel-imap-provider.c	(revision 444)
+++ camel/providers/imap/camel-imap-provider.c	(working copy)
@@ -22,9 +22,7 @@
  *
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <string.h>
 #include "camel-imap-store.h"
@@ -45,6 +43,7 @@
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "check_all", NULL,
 	  N_("C_heck for new messages in all folders"), "1" },
 	{ CAMEL_PROVIDER_CONF_SECTION_END },
+#ifndef G_OS_WIN32
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "cmdsection", NULL,
 	  N_("Connection to Server") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "use_command", NULL,
@@ -52,6 +51,7 @@
 	{ CAMEL_PROVIDER_CONF_ENTRY, "command", "use_command",
 	  N_("Command:"), "ssh -C -l %u %h exec /usr/sbin/imapd" },
 	{ CAMEL_PROVIDER_CONF_SECTION_END },
+#endif
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "folders", NULL,
 	  N_("Folders") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "use_lsub", NULL,
@@ -59,7 +59,7 @@
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "override_namespace", NULL,
 	  N_("O_verride server-supplied folder namespace"), "0" },
 	{ CAMEL_PROVIDER_CONF_ENTRY, "namespace", "override_namespace",
-	  N_("Namespace") },
+	  N_("Namespace:") },
 	{ CAMEL_PROVIDER_CONF_SECTION_END },
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "general", NULL, N_("Options") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "filter", NULL,
Index: camel/providers/Makefile.am
===================================================================
--- camel/providers/Makefile.am	(revision 444)
+++ camel/providers/Makefile.am	(working copy)
@@ -8,13 +8,11 @@
 IMAPP_DIR=imapp
 endif
 
-if WITH_SOUP
-GROUPWISE_DIR=groupwise
-endif
-
 if OS_WIN32
 else
 SENDMAIL_DIR=sendmail
 endif
 
-SUBDIRS = pop3 $(SENDMAIL_DIR) smtp imap imap4 $(NNTP_DIR) local $(IMAPP_DIR) $(GROUPWISE_DIR)
+SUBDIRS = pop3 $(SENDMAIL_DIR) smtp imap imap4 $(NNTP_DIR) local $(IMAPP_DIR)
+
+
Index: camel/providers/imap4/camel-imap4-specials.h
===================================================================
--- camel/providers/imap4/camel-imap4-specials.h	(revision 444)
+++ camel/providers/imap4/camel-imap4-specials.h	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/imap4/camel-imap4-journal.c
===================================================================
--- camel/providers/imap4/camel-imap4-journal.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-journal.c	(working copy)
@@ -351,6 +351,7 @@
 	e_dlist_addtail (&journal->queue, (EDListNode *) entry);
 	
 	info = camel_folder_summary_info_new_from_message (folder->summary, message);
+	g_free(info->uid);
 	info->uid = g_strdup (uid);
 	
 	imap4_message_info_dup_to ((CamelMessageInfoBase *) info, (CamelMessageInfoBase *) mi);
Index: camel/providers/imap4/camel-imap4-folder.c
===================================================================
--- camel/providers/imap4/camel-imap4-folder.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-folder.c	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
@@ -35,6 +35,7 @@
 #include <errno.h>
 #include <time.h>
 
+#include <libedataserver/e-data-server-util.h>
 #include <camel/camel-utf8.h>
 #include <camel/camel-private.h>
 #include <camel/camel-file-utils.h>
@@ -345,7 +346,7 @@
 	
 	folder->summary = camel_imap4_summary_new (folder);
 	imap4_folder->cachedir = imap4_store_build_filename (store, folder->full_name);
-	camel_mkdir (imap4_folder->cachedir, 0777);
+	e_util_mkdir_hier (imap4_folder->cachedir, 0777);
 	
 	imap4_folder->cache = camel_data_cache_new (imap4_folder->cachedir, 0, NULL);
 	
@@ -784,7 +785,7 @@
 		if (camel_data_wrapper_construct_from_stream ((CamelDataWrapper *) message, stream) == -1) {
 			if (errno == EINTR) {
 				CAMEL_SERVICE_UNLOCK (folder->parent_store, connect_lock);
-				camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User cancelled"));
+				camel_exception_setv (ex, CAMEL_EXCEPTION_USER_CANCEL, _("User canceled"));
 				camel_object_unref (message);
 				camel_object_unref (stream);
 				return NULL;
@@ -1012,6 +1013,7 @@
 				char *parent_name, *p;
 				
 				parent_name = g_alloca (strlen (folder->full_name) + 1);
+				strcpy (parent_name, folder->full_name);
 				if (!(p = strrchr (parent_name, '/')))
 					*parent_name = '\0';
 				else
Index: camel/providers/imap4/camel-imap4-command.c
===================================================================
--- camel/providers/imap4/camel-imap4-command.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-command.c	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
@@ -507,7 +507,6 @@
 	CamelIMAP4Literal *literal;
 	camel_imap4_token_t token;
 	unsigned char *linebuf;
-	ssize_t nwritten;
 	size_t len;
 	
 	g_assert (ic->part != NULL);
@@ -545,7 +544,7 @@
 	linebuf = ic->part->buffer;
 	len = ic->part->buflen;
 	
-	if ((nwritten = camel_stream_write (engine->ostream, linebuf, len)) == -1) {
+	if (camel_stream_write (engine->ostream, linebuf, len) == -1) {
 		camel_exception_setv (&ic->ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Failed sending command to IMAP server %s: %s"),
 				      engine->url->host, g_strerror (errno));
Index: camel/providers/imap4/ChangeLog
===================================================================
--- camel/providers/imap4/ChangeLog	(revision 444)
+++ camel/providers/imap4/ChangeLog	(working copy)
@@ -1,3 +1,68 @@
+2006-07-12  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-imap4-provider.c:
+	adding trailing colon to string. Fixes bug #331858.
+
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-imap4-folder.c: 
+	* camel-imap4-store.c: 
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
+2006-06-09  Chris Heath  <chris@heathens.co.nz>
+
+	* camel-imap4-journal.c (camel_imap4_journal_append): Fix memory leak.
+	Fixes bug #335423.
+
+2006-04-21  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap4-store.c (connect_to_server): Set some socket options
+	like keepalive and nodelay.
+	(connect_to_server_wrapper): Don't do fallback with SSL/TLS. Fixes
+	bug #321797.
+
+2006-04-12  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap4-folder.c (imap4_append_message): strcpy the
+	folder->full_name into the freshly alloca'd parent_name buffer
+	before using strrchr on it.
+
+2006-03-31  Jeffrey Stedfast  <fejj@novell.com>
+
+	Fix for bug #272058
+
+	* camel-imap4-summary.c (untagged_fetch_all): Get the In-Reply-To
+	header too.
+	(decode_envelope): Only decode the ENVELOPE's In-Reply-To field if
+	we don't already have a list of references decoded (e.g. from a
+	header query). Decode the Message-Id value before getting the md5
+	digest so that the format matches the References/In-Reply-To
+	values.
+	(decode_references): Modified to take 2 string args - References
+	and In-Reply-To - so that we can merge the 2 references lists like
+	the default CamelFolderSummary implementation.
+
+2006-03-28  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap4-store.c (imap4_reconnect): Only try to authenticate
+	if the engine is not already in the authenticated state.
+
+2005-12-08  Tor Lillqvist  <tml@novell.com>
+
+	* camel-imap4-store.c: Bypass the external command stuff on Win32.
+
+	* camel-imap4-summary.c: Use g_ascii_strncasecmp() instead of
+	strncasecmp().
+	
+2005-09-28  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-imap4-store.c (imap4_create_folder): Finally fixed to
+	handle recreating parent folders to allow subfolders.
+	(imap4_try_authenticate): Only request a password if no
+	authentication mechanism is to be used or if the mechanism
+	requires a password. Fixes bug #317301.
+
 2005-08-22  Not Zed  <NotZed@Ximian.com>
 
 	* camel-imap4-utils.c (camel_imap4_utils_set_unexpected_token_error): 
Index: camel/providers/imap4/camel-imap4-folder.h
===================================================================
--- camel/providers/imap4/camel-imap4-folder.h	(revision 444)
+++ camel/providers/imap4/camel-imap4-folder.h	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/imap4/camel-imap4-command.h
===================================================================
--- camel/providers/imap4/camel-imap4-command.h	(revision 444)
+++ camel/providers/imap4/camel-imap4-command.h	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/imap4/camel-imap4-store-summary.c
===================================================================
--- camel/providers/imap4/camel-imap4-store-summary.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-store-summary.c	(working copy)
@@ -113,7 +113,7 @@
 static CamelIMAP4NamespaceList *
 load_namespaces (FILE *in)
 {
-	CamelIMAP4Namespace *ns, *tail;
+	CamelIMAP4Namespace *ns, *tail = NULL;
 	CamelIMAP4NamespaceList *nsl;
 	guint32 i, j, n;
 	
@@ -200,7 +200,7 @@
 static int
 save_namespaces (FILE *out, CamelIMAP4NamespaceList *nsl)
 {
-	CamelIMAP4Namespace *cur, *ns;
+	CamelIMAP4Namespace *ns, *cur = NULL;
 	guint32 i, n;
 	
 	for (i = 0; i < 3; i++) {
Index: camel/providers/imap4/camel-imap4-provider.c
===================================================================
--- camel/providers/imap4/camel-imap4-provider.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-provider.c	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
@@ -31,19 +31,12 @@
 #include "camel-imap4-store.h"
 
 
-CamelProviderConfEntry imap4_conf_entries[] = {
+static CamelProviderConfEntry imap4_conf_entries[] = {
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "mailcheck", NULL,
 	  N_("Checking for new mail") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "check_all", NULL,
 	  N_("C_heck for new messages in all folders"), "1" },
 	{ CAMEL_PROVIDER_CONF_SECTION_END },
-	{ CAMEL_PROVIDER_CONF_SECTION_START, "cmdsection", NULL,
-	  N_("Connection to Server") },
-	{ CAMEL_PROVIDER_CONF_CHECKBOX, "use_command", NULL,
-	  N_("_Use custom command to connect to server"), "0" },
-	{ CAMEL_PROVIDER_CONF_ENTRY, "command", "use_command",
-	  N_("Command:"), "ssh -C -l %u %h exec /usr/sbin/imapd" },
-	{ CAMEL_PROVIDER_CONF_SECTION_END },
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "folders", NULL,
 	  N_("Folders") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "use_lsub", NULL,
@@ -51,7 +44,7 @@
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "override_namespace", NULL,
 	  N_("O_verride server-supplied folder namespace"), "0" },
 	{ CAMEL_PROVIDER_CONF_ENTRY, "namespace", "override_namespace",
-	  N_("Namespace") },
+	  N_("Namespace:") },
 	{ CAMEL_PROVIDER_CONF_SECTION_END },
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "general", NULL, N_("Options") },
 	{ CAMEL_PROVIDER_CONF_CHECKBOX, "filter", NULL,
Index: camel/providers/imap4/camel-imap4-store.c
===================================================================
--- camel/providers/imap4/camel-imap4-store.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-store.c	(working copy)
@@ -32,7 +32,6 @@
 
 #include <camel/camel-sasl.h>
 #include <camel/camel-utf8.h>
-#include <camel/camel-stream-process.h>
 #include <camel/camel-tcp-stream-raw.h>
 
 #ifdef HAVE_SSL
@@ -218,79 +217,6 @@
 					service->url->user, service->url->host);
 }
 
-
-static gboolean
-connect_to_server_process (CamelIMAP4Engine *engine, const char *format, CamelException *ex)
-{
-	CamelService *service = engine->service;
-	CamelStream *stream;
-	const char *start;
-	GString *exec;
-	
-	exec = g_string_new ("");
-	start = format;
-	
-	while (*format) {
-		register char ch = *format++;
-		
-		if (ch == '%') {
-			g_string_append_len (exec, start, format - start - 1);
-			
-			switch (*format) {
-			case '%':
-				/* literal % */
-				g_string_append_c (exec, '%');
-				break;
-			case 'h':
-				g_string_append (exec, service->url->host);
-				break;
-			case 'u':
-				g_string_append (exec, service->url->user);
-				break;
-			default:
-				g_warning ("unknown formatter '%%%c'", *format);
-				g_string_append_c (exec, '%');
-				g_string_append_c (exec, *format);
-				break;
-			}
-			
-			format++;
-			
-			start = format;
-		}
-	}
-	
-	g_string_append (exec, start);
-	
-	stream = camel_stream_process_new ();
-	
-	if (camel_stream_process_connect ((CamelStreamProcess *) stream, exec->str, NULL) == -1) {
-		if (errno == EINTR)
-			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-					     _("Connection cancelled"));
-		else
-			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
-					      _("Could not connect with command \"%s\": %s"),
-					      exec->str, g_strerror (errno));
-		
-		camel_object_unref (stream);
-		g_string_free (exec, TRUE);
-		return FALSE;
-	}
-	
-	g_string_free (exec, TRUE);
-	
-	if (camel_imap4_engine_take_stream (engine, stream, ex) == -1)
-		return FALSE;
-	
-	if (camel_imap4_engine_capability (engine, ex) == -1)
-		return FALSE;
-	
-	camel_imap4_store_summary_set_capabilities (((CamelIMAP4Store *) service)->summary, engine->capa);
-	
-	return TRUE;
-}
-
 enum {
 	MODE_CLEAR,
 	MODE_SSL,
@@ -306,9 +232,12 @@
 connect_to_server (CamelIMAP4Engine *engine, struct addrinfo *ai, int ssl_mode, CamelException *ex)
 {
 	CamelService *service = engine->service;
+	CamelSockOptData sockopt;
 	CamelStream *tcp_stream;
+#ifdef HAVE_SSL
 	CamelIMAP4Command *ic;
-	int id, ret;
+	int id;
+#endif
 	
 	if (ssl_mode != MODE_CLEAR) {
 #ifdef HAVE_SSL
@@ -328,10 +257,10 @@
 		tcp_stream = camel_tcp_stream_raw_new ();
 	}
 	
-	if ((ret = camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai)) == -1) {
+	if (camel_tcp_stream_connect ((CamelTcpStream *) tcp_stream, ai) == -1) {
 		if (errno == EINTR)
 			camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-					     _("Connection cancelled"));
+					     _("Connection canceled"));
 		else
 			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_UNAVAILABLE,
 					      _("Could not connect to %s: %s"),
@@ -343,6 +272,15 @@
 		return FALSE;
 	}
 	
+	/* set some socket options to better tailor the connection to our needs */
+	sockopt.option = CAMEL_SOCKOPT_NODELAY;
+	sockopt.value.no_delay = TRUE;
+	camel_tcp_stream_setsockopt ((CamelTcpStream *) tcp_stream, &sockopt);
+	
+	sockopt.option = CAMEL_SOCKOPT_KEEPALIVE;
+	sockopt.value.keep_alive = TRUE;
+	camel_tcp_stream_setsockopt ((CamelTcpStream *) tcp_stream, &sockopt);
+	
 	if (camel_imap4_engine_take_stream (engine, tcp_stream, ex) == -1)
 		return FALSE;
 	
@@ -414,15 +352,10 @@
 	CamelService *service = engine->service;
 	struct addrinfo *ai, hints;
 	const char *ssl_mode;
-	const char *command;
 	int mode, ret, i;
 	const char *port;
 	char *serv;
 	
-	if (camel_url_get_param(service->url, "use_command")
-	    &&(command = camel_url_get_param (service->url, "command")))
-		return connect_to_server_process (engine, command, ex);
-	
 	if ((ssl_mode = camel_url_get_param (service->url, "use_ssl"))) {
 		for (i = 0; ssl_options[i].value; i++)
 			if (!strcmp (ssl_options[i].value, ssl_mode))
@@ -450,16 +383,11 @@
 		camel_exception_clear (ex);
 		ai = camel_getaddrinfo (service->url->host, port, &hints, ex);
 	}
+	
 	if (ai == NULL)
 		return FALSE;
 	
-	if (!(ret = connect_to_server (engine, ai, mode, ex)) && mode == MODE_SSL) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (engine, ai, MODE_TLS, ex);
-	} else if (!ret && mode == MODE_TLS) {
-		camel_exception_clear (ex);
-		ret = connect_to_server (engine, ai, MODE_CLEAR, ex);
-	}
+	ret = connect_to_server (engine, ai, mode, ex);
 	
 	camel_freeaddrinfo (ai);
 	
@@ -509,11 +437,15 @@
 {
 	CamelService *service = engine->service;
 	CamelSession *session = service->session;
+	CamelServiceAuthType *mech = NULL;
 	CamelSasl *sasl = NULL;
 	CamelIMAP4Command *ic;
 	int id;
 	
-	if (!service->url->passwd) {
+	if (service->url->authmech)
+		mech = g_hash_table_lookup (engine->authtypes, service->url->authmech);
+	
+	if ((!mech || (mech && mech->need_password)) && !service->url->passwd) {
 		guint32 flags = CAMEL_SESSION_PASSWORD_SECRET;
 		char *prompt;
 		
@@ -534,9 +466,6 @@
 	}
 	
 	if (service->url->authmech) {
-		CamelServiceAuthType *mech;
-		
-		mech = g_hash_table_lookup (engine->authtypes, service->url->authmech);
 		sasl = camel_sasl_new ("imap", mech->authproto, service);
 		
 		ic = camel_imap4_engine_prequeue (engine, NULL, "AUTHENTICATE %s\r\n", service->url->authmech);
@@ -578,7 +507,6 @@
 imap4_reconnect (CamelIMAP4Engine *engine, CamelException *ex)
 {
 	CamelService *service = engine->service;
-	CamelServiceAuthType *mech;
 	gboolean reprompt = FALSE;
 	char *errmsg = NULL;
 	CamelException lex;
@@ -586,32 +514,34 @@
 	if (!connect_to_server_wrapper (engine, ex))
 		return FALSE;
 	
-#define CANT_USE_AUTHMECH (!(mech = g_hash_table_lookup (engine->authtypes, service->url->authmech)))
-	if (service->url->authmech && CANT_USE_AUTHMECH) {
-		/* Oops. We can't AUTH using the requested mechanism */
-		camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_CANT_AUTHENTICATE,
-				      _("Cannot authenticate to IMAP server %s using %s"),
-				      service->url->host, service->url->authmech);
+	if (engine->state != CAMEL_IMAP4_ENGINE_AUTHENTICATED) {
+#define CANT_USE_AUTHMECH (!g_hash_table_lookup (engine->authtypes, service->url->authmech))
+		if (service->url->authmech && CANT_USE_AUTHMECH) {
+			/* Oops. We can't AUTH using the requested mechanism */
+			camel_exception_setv (ex, CAMEL_EXCEPTION_SERVICE_CANT_AUTHENTICATE,
+					      _("Cannot authenticate to IMAP server %s using %s"),
+					      service->url->host, service->url->authmech);
+			
+			return FALSE;
+		}
 		
-		return FALSE;
-	}
-	
-	camel_exception_init (&lex);
-	while (imap4_try_authenticate (engine, reprompt, errmsg, &lex)) {
+		camel_exception_init (&lex);
+		while (imap4_try_authenticate (engine, reprompt, errmsg, &lex)) {
+			g_free (errmsg);
+			errmsg = g_strdup (lex.desc);
+			camel_exception_clear (&lex);
+			g_free (service->url->passwd);
+			service->url->passwd = NULL;
+			reprompt = TRUE;
+		}
 		g_free (errmsg);
-		errmsg = g_strdup (lex.desc);
-		camel_exception_clear (&lex);
-		g_free (service->url->passwd);
-		service->url->passwd = NULL;
-		reprompt = TRUE;
+		
+		if (camel_exception_is_set (&lex)) {
+			camel_exception_xfer (ex, &lex);
+			return FALSE;
+		}
 	}
-	g_free (errmsg);
 	
-	if (camel_exception_is_set (&lex)) {
-		camel_exception_xfer (ex, &lex);
-		return FALSE;
-	}
-	
 	if (camel_imap4_engine_namespace (engine, ex) == -1)
 		return FALSE;
 	
@@ -832,51 +762,93 @@
 	return folder;
 }
 
-static CamelFolderInfo *
-imap4_create_folder (CamelStore *store, const char *parent_name, const char *folder_name, CamelException *ex)
+
+static gboolean
+imap4_folder_can_contain_folders (CamelStore *store, const char *folder_name, CamelException *ex)
 {
-	/* FIXME: also need to deal with parent folders that can't
-	 * contain subfolders - delete them and re-create with the
-	 * proper hint */
 	CamelIMAP4Engine *engine = ((CamelIMAP4Store *) store)->engine;
-	CamelFolderInfo *fi = NULL;
+	guint32 flags = CAMEL_FOLDER_NOINFERIORS;
+	camel_imap4_list_t *list;
 	CamelIMAP4Command *ic;
+	GPtrArray *array;
 	char *utf7_name;
-	CamelURL *url;
-	const char *c;
-	char *name;
-	char sep;
-	int id;
+	int id, i;
 	
-	sep = camel_imap4_get_path_delim (((CamelIMAP4Store *) store)->summary, parent_name);
+	CAMEL_SERVICE_LOCK (store, connect_lock);
 	
-	c = folder_name;
-	while (*c != '\0') {
-		if (*c == sep || strchr ("/#%*", *c)) {
-			camel_exception_setv (ex, CAMEL_EXCEPTION_FOLDER_INVALID_PATH,
-					      _("The folder name \"%s\" is invalid because "
-						"it contains the character \"%c\""),
-					      folder_name, *c);
-			return NULL;
+	utf7_name = imap4_folder_utf7_name (store, folder_name, '\0');
+	
+	ic = camel_imap4_engine_queue (engine, NULL, "LIST \"\" %S\r\n", utf7_name);
+	camel_imap4_command_register_untagged (ic, "LIST", camel_imap4_untagged_list);
+	ic->user_data = array = g_ptr_array_new ();
+	
+	while ((id = camel_imap4_engine_iterate (engine)) < ic->id && id != -1)
+		;
+	
+	if (id == -1 || ic->status != CAMEL_IMAP4_COMMAND_COMPLETE) {
+		camel_exception_xfer (ex, &ic->ex);
+		camel_imap4_command_unref (ic);
+		
+		for (i = 0; i < array->len; i++) {
+			list = array->pdata[i];
+			g_free (list->name);
+			g_free (list);
 		}
 		
-		c++;
+		goto done;
 	}
 	
-	if (((CamelOfflineStore *) store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL) {
-		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create IMAP folders in offline mode."));
-		return NULL;
+	if (ic->result != CAMEL_IMAP4_RESULT_OK) {
+		camel_imap4_command_unref (ic);
+		
+		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
+				      _("Cannot get LIST information for `%s' on IMAP server %s: %s"),
+				      folder_name, engine->url->host, ic->result == CAMEL_IMAP4_RESULT_BAD ?
+				      _("Bad command") : _("Unknown"));
+		
+		for (i = 0; i < array->len; i++) {
+			list = array->pdata[i];
+			g_free (list->name);
+			g_free (list);
+		}
+		
+		goto done;
 	}
 	
-	if (parent_name != NULL && *parent_name)
-		name = g_strdup_printf ("%s/%s", parent_name, folder_name);
-	else
-		name = g_strdup (folder_name);
+	flags = 0;
+	for (i = 0; i < array->len; i++) {
+		list = array->pdata[i];
+		if (!strcmp (list->name, utf7_name))
+			flags |= list->flags;
+		g_free (list->name);
+		g_free (list);
+	}
 	
+ done:
+	
+	CAMEL_SERVICE_UNLOCK (store, connect_lock);
+	
+	g_ptr_array_free (array, TRUE);
+	g_free (utf7_name);
+	
+	return (flags & CAMEL_FOLDER_NOINFERIORS) == 0;
+}
+
+static CamelFolderInfo *
+imap4_folder_create (CamelStore *store, const char *folder_name, const char *subfolder_hint, CamelException *ex)
+{
+	CamelIMAP4Engine *engine = ((CamelIMAP4Store *) store)->engine;
+	CamelFolderInfo *fi = NULL;
+	CamelIMAP4Command *ic;
+	char *utf7_name;
+	CamelURL *url;
+	const char *c;
+	int id;
+	
 	CAMEL_SERVICE_LOCK (store, connect_lock);
 	
-	utf7_name = imap4_folder_utf7_name (store, name, '\0');
-	ic = camel_imap4_engine_queue (engine, NULL, "CREATE %S\r\n", utf7_name);
+	utf7_name = imap4_folder_utf7_name (store, folder_name, '\0');
+	ic = camel_imap4_engine_queue (engine, NULL, "CREATE %S%s\r\n", utf7_name, subfolder_hint);
 	g_free (utf7_name);
 	
 	while ((id = camel_imap4_engine_iterate (engine)) < ic->id && id != -1)
@@ -885,20 +857,19 @@
 	if (id == -1 || ic->status != CAMEL_IMAP4_COMMAND_COMPLETE) {
 		camel_exception_xfer (ex, &ic->ex);
 		camel_imap4_command_unref (ic);
-		g_free (name);
 		goto done;
 	}
 	
 	switch (ic->result) {
 	case CAMEL_IMAP4_RESULT_OK:
 		url = camel_url_copy (engine->url);
-		camel_url_set_fragment (url, name);
+		camel_url_set_fragment (url, folder_name);
 		
-		c = strrchr (name, '/');
+		c = strrchr (folder_name, '/');
 		
 		fi = g_malloc0 (sizeof (CamelFolderInfo));
-		fi->full_name = name;
-		fi->name = g_strdup (c ? c + 1: name);
+		fi->full_name = g_strdup (folder_name);
+		fi->name = g_strdup (c ? c + 1: folder_name);
 		fi->uri = camel_url_to_string (url, CAMEL_URL_HIDE_ALL);
 		camel_url_free (url);
 		fi->flags = 0;
@@ -913,14 +884,12 @@
 		/* FIXME: would be good to save the NO reason into the err message */
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot create folder `%s': Invalid mailbox name"),
-				      name);
-		g_free (name);
+				      folder_name);
 		break;
 	case CAMEL_IMAP4_RESULT_BAD:
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot create folder `%s': Bad command"),
-				      name);
-		g_free (name);
+				      folder_name);
 		break;
 	default:
 		g_assert_not_reached ();
@@ -935,6 +904,82 @@
 	return fi;
 }
 
+static gboolean
+imap4_folder_recreate (CamelStore *store, const char *folder_name, CamelException *ex)
+{
+	CamelFolderInfo *fi = NULL;
+	char hint[2];
+	char sep;
+	
+	sep = camel_imap4_get_path_delim (((CamelIMAP4Store *) store)->summary, folder_name);
+	sprintf (hint, "%c", sep);
+	
+	imap4_delete_folder (store, folder_name, ex);
+	if (camel_exception_is_set (ex))
+		return FALSE;
+	
+	if (!(fi = imap4_folder_create (store, folder_name, hint, ex)))
+		return FALSE;
+	
+	camel_folder_info_free (fi);
+	
+	return TRUE;
+}
+
+static CamelFolderInfo *
+imap4_create_folder (CamelStore *store, const char *parent_name, const char *folder_name, CamelException *ex)
+{
+	CamelFolderInfo *fi = NULL;
+	const char *c;
+	char *name;
+	char sep;
+	
+	sep = camel_imap4_get_path_delim (((CamelIMAP4Store *) store)->summary, parent_name);
+	
+	c = folder_name;
+	while (*c != '\0') {
+		if (*c == sep || strchr ("/#%*", *c)) {
+			camel_exception_setv (ex, CAMEL_EXCEPTION_FOLDER_INVALID_PATH,
+					      _("The folder name \"%s\" is invalid because "
+						"it contains the character \"%c\""),
+					      folder_name, *c);
+			return NULL;
+		}
+		
+		c++;
+	}
+	
+	if (((CamelOfflineStore *) store)->state == CAMEL_OFFLINE_STORE_NETWORK_UNAVAIL) {
+		camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create IMAP folders in offline mode."));
+		return NULL;
+	}
+	
+	if (parent_name != NULL && *parent_name) {
+		CamelException lex;
+		
+		camel_exception_init (&lex);
+		if (!imap4_folder_can_contain_folders (store, parent_name, &lex)) {
+			if (camel_exception_is_set (&lex)) {
+				camel_exception_xfer (ex, &lex);
+				return NULL;
+			}
+			
+			if (!imap4_folder_recreate (store, parent_name, &lex)) {
+				camel_exception_xfer (ex, &lex);
+				return NULL;
+			}
+		}
+		
+		name = g_strdup_printf ("%s/%s", parent_name, folder_name);
+	} else
+		name = g_strdup (folder_name);
+	
+	fi = imap4_folder_create (store, name, "", ex);
+	g_free (name);
+	
+	return fi;
+}
+
 static void
 imap4_delete_folder (CamelStore *store, const char *folder_name, CamelException *ex)
 {
@@ -1351,7 +1396,9 @@
 	}
 #endif
 	
+#ifdef USE_FOLDER_INFO_CACHE_LOGIC_FOR_SPEED
  check_online:
+#endif
 	
 	if (flags & CAMEL_STORE_FOLDER_INFO_SUBSCRIBED)
 		cmd = "LSUB";
Index: camel/providers/imap4/camel-imap4-summary.c
===================================================================
--- camel/providers/imap4/camel-imap4-summary.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-summary.c	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
@@ -146,13 +146,14 @@
 imap4_header_load (CamelFolderSummary *summary, FILE *fin)
 {
 	CamelIMAP4Summary *imap4_summary = (CamelIMAP4Summary *) summary;
+	gint32 *ptr32 = summary->filepos;
 	
 	if (CAMEL_FOLDER_SUMMARY_CLASS (parent_class)->summary_header_load (summary, fin) == -1)
 		return -1;
 	
-	if (camel_file_util_decode_fixed_int32 (fin, &imap4_summary->version) == -1)
-		return -1;
-	
+	imap4_summary->version = g_ntohl (*ptr32); ptr32++;
+	summary->filepos = ptr32;
+
 	if (imap4_summary->version > CAMEL_IMAP4_SUMMARY_VERSION) {
 		g_warning ("Unknown IMAP4 summary version\n");
 		errno = EINVAL;
@@ -162,18 +163,17 @@
 	if (imap4_summary->version == 2) {
 		/* check that we have Mailing-List info */
 		int have_mlist;
+
+		have_mlist = g_ntohl (*ptr32); ptr32++;
 		
-		if (camel_file_util_decode_fixed_int32 (fin, &have_mlist) == -1)
-			return -1;
-		
 		if (have_mlist)
 			summary->flags |= CAMEL_IMAP4_SUMMARY_HAVE_MLIST;
 		else
 			summary->flags ^= CAMEL_IMAP4_SUMMARY_HAVE_MLIST;
 	}
 	
-	if (camel_file_util_decode_fixed_int32 (fin, &imap4_summary->uidvalidity) == -1)
-		return -1;
+	imap4_summary->uidvalidity = g_ntohl (*ptr32); ptr32++;
+	summary->filepos = ptr32;
 	
 	return 0;
 }
@@ -429,19 +429,32 @@
 }
 
 static CamelSummaryReferences *
-decode_references (const char *string, int inreplyto)
+decode_references (const char *refstr, const char *irtstr)
 {
-	struct _camel_header_references *refs, *r;
+	struct _camel_header_references *refs, *irt, *r;
 	CamelSummaryReferences *references;
 	unsigned char md5sum[16];
 	guint32 i, n;
 	
-	if (inreplyto) {
-		if (!(refs = camel_header_references_inreplyto_decode (string)))
-			return NULL;
-	} else {
-		if (!(refs = camel_header_references_decode (string)))
-			return NULL;
+	refs = camel_header_references_decode (refstr);
+	irt = camel_header_references_inreplyto_decode (irtstr);
+	
+	if (!refs && !irt)
+		return NULL;
+	
+	if (irt) {
+		/* The References field is populated from the `References' and/or `In-Reply-To'
+		   headers. If both headers exist, take the first thing in the In-Reply-To header
+		   that looks like a Message-ID, and append it to the References header. */
+		
+		if (refs) {
+			r = irt;
+			while (r->next != NULL)
+				r = r->next;
+			r->next = refs;
+		}
+		
+		refs = irt;
 	}
 	
 	n = camel_header_references_list_size (&refs);
@@ -450,7 +463,7 @@
 	
 	for (i = 0, r = refs; r != NULL; i++, r = r->next) {
 		md5_get_digest (r->id, strlen (r->id), md5sum);
-		memcpy (references->references[i].id.hash, md5sum, sizeof (references->references[i].id.hash));
+		memcpy (references->references[i].id.hash, md5sum, sizeof (CamelSummaryMessageID));
 	}
 	
 	camel_header_references_list_clear (&refs);
@@ -462,9 +475,8 @@
 decode_envelope (CamelIMAP4Engine *engine, CamelMessageInfo *info, camel_imap4_token_t *token, CamelException *ex)
 {
 	CamelIMAP4MessageInfo *iinfo = (CamelIMAP4MessageInfo *) info;
-	CamelSummaryReferences *refs;
 	unsigned char md5sum[16];
-	char *nstring;
+	char *nstring, *msgid;
 	
 	if (camel_imap4_engine_next_token (engine, token, ex) == -1)
 		return -1;
@@ -480,6 +492,9 @@
 	/* subject */
 	if (envelope_decode_nstring (engine, &nstring, TRUE, ex) == -1)
 		goto exception;
+
+	iinfo->info.needs_free = TRUE;
+
 	iinfo->info.subject = camel_pstring_strdup (nstring);
 	g_free(nstring);
 	
@@ -521,12 +536,8 @@
 		goto exception;
 	
 	if (nstring != NULL) {
-		refs = decode_references (nstring, TRUE);
-		
 		if (!iinfo->info.references)
-			iinfo->info.references = refs;
-		else
-			g_free (refs);
+			iinfo->info.references = decode_references (NULL, nstring);
 		
 		g_free (nstring);
 	}
@@ -536,8 +547,11 @@
 		goto exception;
 	
 	if (nstring != NULL) {
-		md5_get_digest (nstring, strlen (nstring), md5sum);
-		memcpy (iinfo->info.message_id.id.hash, md5sum, sizeof (iinfo->info.message_id.id.hash));
+		if ((msgid = camel_header_msgid_decode (nstring))) {
+			md5_get_digest (msgid, strlen (msgid), md5sum);
+			memcpy (iinfo->info.message_id.id.hash, md5sum, sizeof (CamelSummaryMessageID));
+			g_free (msgid);
+		}
 		g_free (nstring);
 	}
 	
@@ -638,7 +652,7 @@
 		return (time_t) -1;
 	
 	for (n = 0; n < 12; n++) {
-		if (!strncasecmp (inptr, tm_months[n], 3))
+		if (!g_ascii_strncasecmp (inptr, tm_months[n], 3))
 			break;
 	}
 	
@@ -764,6 +778,7 @@
 		
 		if ((info = camel_folder_summary_uid (fetch->summary, camel_message_info_uid (envelope->info)))) {
 			camel_message_info_free (envelope->info);
+			camel_message_info_free (info);
 			g_free (envelope);
 			continue;
 		}
@@ -980,8 +995,11 @@
 					g_assert_not_reached ();
 				}
 			} else {
-				g_free (info->uid);
+				if (((CamelMessageInfoBase*)info)->uid_needs_free)
+					g_free (info->uid);
 				info->uid = g_strdup (uid);
+				((CamelMessageInfoBase*)info)->uid_needs_free = TRUE;
+
 				g_hash_table_insert (fetch->uid_hash, (void *) camel_message_info_uid (info), envelope);
 				changed |= IMAP4_FETCH_UID;
 			}
@@ -991,7 +1009,7 @@
 			struct _camel_header_raw *h;
 			CamelMimeParser *parser;
 			unsigned char *literal;
-			const char *str;
+			const char *refs, *str;
 			char *mlist;
 			size_t n;
 			
@@ -1051,9 +1069,12 @@
 				h = camel_mime_parser_headers_raw (parser);
 				
 				/* find our mailing-list header */
-				mlist = camel_header_raw_check_mailing_list (&h);
-				iinfo->info.mlist = camel_pstring_strdup (mlist);
-				g_free (mlist);
+
+				/* This introduces a problem for the mmap() implementation */
+
+				// mlist = camel_header_raw_check_mailing_list (&h);
+				// iinfo->info.mlist = camel_pstring_strdup (mlist);
+				// g_free (mlist);
 				
 				/* check if we possibly have attachments */
 				if ((str = camel_header_raw_find (&h, "Content-Type", NULL))) {
@@ -1065,10 +1086,10 @@
 				}
 				
 				/* check for References: */
-				if ((str = camel_header_raw_find (&h, "References", NULL))) {
-					g_free (iinfo->info.references);
-					iinfo->info.references = decode_references (str, FALSE);
-				}
+				g_free (iinfo->info.references);
+				refs = camel_header_raw_find (&h, "References", NULL);
+				str = camel_header_raw_find (&h, "In-Reply-To", NULL);
+				iinfo->info.references = decode_references (refs, str);
 			default:
 				break;
 			}
@@ -1105,7 +1126,7 @@
 #define IMAP4_ALL "FLAGS INTERNALDATE RFC822.SIZE ENVELOPE"
 #define MAILING_LIST_HEADERS "List-Post List-Id Mailing-List Originator X-Mailing-List X-Loop X-List Sender Delivered-To Return-Path X-BeenThere List-Unsubscribe"
 
-#define BASE_HEADER_FIELDS "Content-Type References"
+#define BASE_HEADER_FIELDS "Content-Type References In-Reply-To"
 #define MORE_HEADER_FIELDS BASE_HEADER_FIELDS " " MAILING_LIST_HEADERS
 
 static CamelIMAP4Command *
@@ -1237,22 +1258,17 @@
 {
 	CamelIMAP4MessageInfo *minfo;
 	CamelMessageInfo *info;
-	
+	unsigned char *ptrchr = summary->filepos;
+
 	if (!(info = CAMEL_FOLDER_SUMMARY_CLASS (parent_class)->message_info_load (summary, fin)))
 		return NULL;
 	
 	minfo = (CamelIMAP4MessageInfo *) info;
 	
-	if (camel_file_util_decode_uint32 (fin, &minfo->server_flags) == -1)
-		goto exception;
-	
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &minfo->server_flags, FALSE);
+	summary->filepos = ptrchr;
+
 	return info;
-	
- exception:
-	
-	camel_message_info_free(info);
-	
-	return NULL;
 }
 
 static int
Index: camel/providers/imap4/camel-imap4-utils.c
===================================================================
--- camel/providers/imap4/camel-imap4-utils.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-utils.c	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
@@ -485,7 +485,7 @@
 }
 
 
-struct {
+static struct {
 	const char *name;
 	guint32 flag;
 } list_flags[] = {
Index: camel/providers/imap4/camel-imap4-store.h
===================================================================
--- camel/providers/imap4/camel-imap4-store.h	(revision 444)
+++ camel/providers/imap4/camel-imap4-store.h	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/imap4/camel-imap4-summary.h
===================================================================
--- camel/providers/imap4/camel-imap4-summary.h	(revision 444)
+++ camel/providers/imap4/camel-imap4-summary.h	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/imap4/camel-imap4-specials.c
===================================================================
--- camel/providers/imap4/camel-imap4-specials.c	(revision 444)
+++ camel/providers/imap4/camel-imap4-specials.c	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/imap4/camel-imap4-utils.h
===================================================================
--- camel/providers/imap4/camel-imap4-utils.h	(revision 444)
+++ camel/providers/imap4/camel-imap4-utils.h	(working copy)
@@ -1,6 +1,6 @@
 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*  Camel
- *  Copyright (C) 1999-2004 Jeffrey Stedfast
+ *  Copyright (C) 1999-2006 Jeffrey Stedfast
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU Lesser General Public License as published by
Index: camel/providers/local/camel-local-summary.c
===================================================================
--- camel/providers/local/camel-local-summary.c	(revision 444)
+++ camel/providers/local/camel-local-summary.c	(working copy)
@@ -30,12 +30,16 @@
 #include <string.h>
 #include <stdlib.h>
 
-#include "camel-local-summary.h"
+#include <glib.h>
+#include <glib/gstdio.h>
+
 #include "camel/camel-mime-message.h"
 #include "camel/camel-stream-null.h"
 #include "camel/camel-file-utils.h"
 #include "camel/camel-i18n.h"
 
+#include "camel-local-summary.h"
+
 #define w(x)
 #define io(x)
 #define d(x) /*(printf("%s(%d): ", __FILE__, __LINE__),(x))*/
@@ -149,7 +153,7 @@
 	d(printf("Loading summary ...\n"));
 
 	if (forceindex
-	    || stat(s->summary_path, &st) == -1
+	    || g_stat(s->summary_path, &st) == -1
 	    || ((CamelLocalSummaryClass *)(CAMEL_OBJECT_GET_CLASS(cls)))->load(cls, forceindex, ex) == -1) {
 		w(g_warning("Could not load summary: flags may be reset"));
 		camel_folder_summary_clear((CamelFolderSummary *)cls);
@@ -554,13 +558,13 @@
 		params = camel_header_param_list_decode(header+1);
 		scan = params;
 		while (scan) {
-			if (!strcasecmp(scan->name, "flags")) {
+			if (!g_ascii_strcasecmp(scan->name, "flags")) {
 				char **flagv = g_strsplit(scan->value, ",", 1000);
 
 				for (i=0;flagv[i];i++)
 					camel_message_info_set_user_flag((CamelMessageInfo *)mi, flagv[i], TRUE);
 				g_strfreev(flagv);
-			} else if (!strcasecmp(scan->name, "tags")) {
+			} else if (!g_ascii_strcasecmp(scan->name, "tags")) {
 				char **tagv = g_strsplit(scan->value, ",", 10000);
 				char *val;
 
@@ -589,6 +593,7 @@
 summary_header_load(CamelFolderSummary *s, FILE *in)
 {
 	CamelLocalSummary *cls = (CamelLocalSummary *)s;
+	gint32 *ptr32 = s->filepos;
 
 	/* We dont actually add our own headers, but version that we don't anyway */
 
@@ -600,7 +605,12 @@
 		return 0;
 
 	/* otherwise load the version number */
-	return camel_file_util_decode_fixed_int32(in, &cls->version);
+	
+	ptr32 = s->filepos;
+	cls->version = g_ntohl (*ptr32); ptr32++;
+	s->filepos = ptr32;
+
+	return 0;
 }
 
 static int
@@ -629,6 +639,7 @@
 		if (xev==NULL || camel_local_summary_decode_x_evolution(cls, xev, mi) == -1) {
 			/* to indicate it has no xev header */
 			mi->info.flags |= CAMEL_MESSAGE_FOLDER_FLAGGED | CAMEL_MESSAGE_FOLDER_NOXEV;
+			g_free (mi->info.uid);
 			mi->info.uid = camel_folder_summary_next_uid_string(s);
 
 			/* shortcut, no need to look it up in the index library */
Index: camel/providers/local/camel-mbox-summary.c
===================================================================
--- camel/providers/local/camel-mbox-summary.c	(revision 444)
+++ camel/providers/local/camel-mbox-summary.c	(working copy)
@@ -23,26 +23,26 @@
 #include <config.h>
 #endif
 
-#include "camel-mbox-summary.h"
-#include "camel/camel-mime-message.h"
-#include "camel/camel-operation.h"
-
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <unistd.h>
 #include <fcntl.h>
-#include <sys/uio.h>
-#include <unistd.h>
 #include <errno.h>
 #include <string.h>
 #include <stdlib.h>
 #include <ctype.h>
 
-#include "camel-mbox-summary.h"
-#include "camel/camel-file-utils.h"
-#include "camel/camel-mime-message.h"
-#include "camel/camel-operation.h"
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include "camel-file-utils.h"
 #include "camel-i18n.h"
+#include "camel-mime-message.h"
+#include "camel-operation.h"
+#include "camel-private.h"
 
+#include "camel-mbox-summary.h"
+
 #define io(x)
 #define d(x) /*(printf("%s(%d): ", __FILE__, __LINE__),(x))*/
 
@@ -233,22 +233,32 @@
 	}
 }
 
+
+	
 static int
 summary_header_load(CamelFolderSummary *s, FILE *in)
 {
 	CamelMboxSummary *mbs = CAMEL_MBOX_SUMMARY(s);
+	gint32 *ptr32;
+	unsigned char *ptrchr;
 
 	if (((CamelFolderSummaryClass *)camel_mbox_summary_parent)->summary_header_load(s, in) == -1)
 		return -1;
 
 	/* legacy version */
 	if (s->version == 0x120c)
-		return camel_file_util_decode_uint32(in, (guint32 *) &mbs->folder_size);
+	{
+		unsigned char* ptrchr = s->filepos;
+		ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &mbs->folder_size, FALSE);
+		s->filepos = ptrchr;
+	}
 
 	/* version 1 */
-	if (camel_file_util_decode_fixed_int32(in, &mbs->version) == -1
-	    || camel_file_util_decode_size_t(in, &mbs->folder_size) == -1)
-		return -1;
+	ptr32 = s->filepos;
+	mbs->version = g_ntohl (*ptr32); ptr32++;
+	ptrchr = (unsigned char*)ptr32;
+	ptrchr = camel_file_util_mmap_decode_size_t (ptrchr, &mbs->folder_size);
+	s->filepos = ptrchr;
 
 	return 0;
 }
@@ -319,6 +329,7 @@
 
 		if (add&1) {
 			mi->info.info.flags |= CAMEL_MESSAGE_FOLDER_FLAGGED | CAMEL_MESSAGE_FOLDER_NOXEV;
+			g_free (mi->info.info.uid);
 			mi->info.info.uid = camel_folder_summary_next_uid_string(s);
 		} else {
 			camel_folder_summary_set_uid(s, strtoul(camel_message_info_uid(mi), NULL, 10));
@@ -360,6 +371,7 @@
 	return mi;
 }
 
+
 static CamelMessageInfo *
 message_info_load(CamelFolderSummary *s, FILE *in)
 {
@@ -370,17 +382,16 @@
 	mi = ((CamelFolderSummaryClass *)camel_mbox_summary_parent)->message_info_load(s, in);
 	if (mi) {
 		CamelMboxMessageInfo *mbi = (CamelMboxMessageInfo *)mi;
-		
-		if (camel_file_util_decode_off_t(in, &mbi->frompos) == -1)
-			goto error;
+
+		unsigned char *ptrchr = s->filepos;
+		ptrchr = camel_file_util_mmap_decode_off_t (ptrchr, &mbi->frompos);
+		s->filepos = ptrchr;
 	}
 	
 	return mi;
-error:
-	camel_message_info_free(mi);
-	return NULL;
 }
 
+
 static int
 message_info_save(CamelFolderSummary *s, FILE *out, CamelMessageInfo *mi)
 {
@@ -389,7 +400,7 @@
 	io(printf("saving mbox message info\n"));
 
 	if (((CamelFolderSummaryClass *)camel_mbox_summary_parent)->message_info_save(s, out, mi) == -1
-	    || camel_file_util_encode_off_t(out, mbi->frompos) == -1)
+	    || camel_file_util_encode_off_t (out, mbi->frompos) == -1)
 		return -1;
 
 	return 0;
@@ -415,7 +426,7 @@
 
 	camel_operation_start(NULL, _("Storing folder"));
 
-	fd = open(cls->folder_path, O_RDONLY);
+	fd = g_open(cls->folder_path, O_RDONLY | O_BINARY, 0);
 	if (fd == -1) {
 		d(printf("%s failed to open: %s\n", cls->folder_path, strerror (errno)));
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
@@ -496,7 +507,7 @@
 	
 	/* update the file size/mtime in the summary */
 	if (ok != -1) {
-		if (stat(cls->folder_path, &st) == 0) {
+		if (g_stat(cls->folder_path, &st) == 0) {
 			camel_folder_summary_touch(s);
 			mbs->folder_size = st.st_size;
 			s->time = st.st_mtime;
@@ -520,7 +531,7 @@
 	d(printf("Checking summary\n"));
 
 	/* check if the summary is up-to-date */
-	if (stat(cls->folder_path, &st) == -1) {
+	if (g_stat(cls->folder_path, &st) == -1) {
 		camel_folder_summary_clear(s);
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot check folder: %s: %s"),
@@ -588,7 +599,7 @@
 
 	camel_operation_start(NULL, _("Storing folder"));
 
-	fd = open(cls->folder_path, O_RDONLY);
+	fd = g_open(cls->folder_path, O_RDONLY | O_BINARY, 0);
 	if (fd == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not open file: %s: %s"),
@@ -600,7 +611,7 @@
 	tmpname = g_alloca (strlen (cls->folder_path) + 5);
 	sprintf (tmpname, "%s.tmp", cls->folder_path);
 	d(printf("Writing tmp file to %s\n", tmpname));
-	fdout = open(tmpname, O_WRONLY|O_CREAT|O_TRUNC, 0600);
+	fdout = g_open(tmpname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0600);
 	if (fdout == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot open temporary mailbox: %s"),
@@ -633,7 +644,11 @@
 
 	/* this should probably either use unlink/link/unlink, or recopy over
 	   the original mailbox, for various locking reasons/etc */
-	if (rename(tmpname, cls->folder_path) == -1) {
+#ifdef G_OS_WIN32
+	if (g_file_test(cls->folder_path,G_FILE_TEST_IS_REGULAR) && g_remove(cls->folder_path) == -1)
+		g_warning ("Cannot remove %s: %s", cls->folder_path, g_strerror (errno));
+#endif
+	if (g_rename(tmpname, cls->folder_path) == -1) {
 		g_warning("Cannot rename folder: %s", strerror (errno));
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not rename folder: %s"),
@@ -653,7 +668,7 @@
 		close(fdout);
 	
 	if (tmpname)
-		unlink(tmpname);
+		g_unlink(tmpname);
 
 	camel_operation_end(NULL);
 
@@ -679,7 +694,7 @@
 
 	camel_operation_start(NULL, _("Storing folder"));
 
-	fd = open(cls->folder_path, O_RDWR);
+	fd = g_open(cls->folder_path, O_RDWR|O_BINARY, 0);
 	if (fd == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not open file: %s: %s"),
@@ -862,7 +877,7 @@
 	if (ret == -1)
 		return -1;
 
-	if (stat(cls->folder_path, &st) == -1) {
+	if (g_stat(cls->folder_path, &st) == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Unknown error: %s"), g_strerror (errno));
 		return -1;
@@ -1099,32 +1114,32 @@
 static void
 encode_status(guint32 flags, char status[8])
 {
+	size_t i;
 	char *p;
-	int i;
-
+	
 	p = status;
-	for (i=0;i<sizeof(status_flags)/sizeof(status_flags[0]);i++)
+	for (i = 0; i < G_N_ELEMENTS (status_flags); i++)
 		if (status_flags[i].flag & flags)
 			*p++ = status_flags[i].tag;
 	*p++ = 'O';
-	*p=0;
+	*p = '\0';
 }
 
 static guint32
 decode_status(const char *status)
 {
 	const char *p;
+	guint32 flags = 0;
+	size_t i;
 	char c;
-	guint32 flags = 0;
-	int i;
-
+	
 	p = status;
 	while ((c = *p++)) {
-		for (i=0;i<sizeof(status_flags)/sizeof(status_flags[0]);i++)
-			if (status_flags[i].tag == *p)
+		for (i = 0; i < G_N_ELEMENTS (status_flags); i++)
+			if (status_flags[i].tag == c)
 				flags |= status_flags[i].flag;
 	}
-
+	
 	return flags;
 }
 
Index: camel/providers/local/camel-mbox-folder.c
===================================================================
--- camel/providers/local/camel-mbox-folder.c	(revision 444)
+++ camel/providers/local/camel-mbox-folder.c	(working copy)
@@ -26,24 +26,32 @@
 
 #include <stdlib.h>
 #include <sys/types.h>
-#include <dirent.h>
 #include <sys/stat.h>
 #include <unistd.h>
+#include <fcntl.h>
 #include <errno.h>
 #include <string.h>
-#include <fcntl.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include "camel/camel-data-wrapper.h"
+#include "camel/camel-exception.h"
+#include "camel/camel-i18n.h"
+#include "camel/camel-mime-filter-from.h"
+#include "camel/camel-mime-message.h"
+#include "camel/camel-private.h"
+#include "camel/camel-stream-filter.h"
+#include "camel/camel-stream-fs.h"
+
 #include "camel-mbox-folder.h"
 #include "camel-mbox-store.h"
-#include "camel-stream-fs.h"
 #include "camel-mbox-summary.h"
-#include "camel-data-wrapper.h"
-#include "camel-mime-message.h"
-#include "camel-stream-filter.h"
-#include "camel-mime-filter-from.h"
-#include "camel-exception.h"
-#include "camel-i18n.h"
 
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
 #define d(x) /*(printf("%s(%d): ", __FILE__, __LINE__),(x))*/
 
 static CamelLocalFolderClass *parent_class = NULL;
@@ -136,6 +144,7 @@
 
 static int mbox_lock(CamelLocalFolder *lf, CamelLockType type, CamelException *ex)
 {
+#ifndef G_OS_WIN32
 	CamelMboxFolder *mf = (CamelMboxFolder *)lf;
 
 	/* make sure we have matching unlocks for locks, camel-local-folder class should enforce this */
@@ -154,18 +163,20 @@
 		mf->lockfd = -1;
 		return -1;
 	}
-
+#endif
 	return 0;
 }
 
 static void mbox_unlock(CamelLocalFolder *lf)
 {
+#ifndef G_OS_WIN32
 	CamelMboxFolder *mf = (CamelMboxFolder *)lf;
 
 	g_assert(mf->lockfd != -1);
 	camel_unlock_folder(lf->folder_path, mf->lockfd);
 	close(mf->lockfd);
 	mf->lockfd = -1;
+#endif
 }
 
 static void
@@ -242,7 +253,7 @@
 
 	/* now we 'fudge' the summary  to tell it its uptodate, because its idea of uptodate has just changed */
 	/* the stat really shouldn't fail, we just wrote to it */
-	if (stat(lf->folder_path, &st) == 0) {
+	if (g_stat(lf->folder_path, &st) == 0) {
 		mbs->folder_size = st.st_size;
 		((CamelFolderSummary *)mbs)->time = st.st_mtime;
 	}
@@ -263,7 +274,7 @@
 fail_write:
 	if (errno == EINTR)
 		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-				     _("Mail append cancelled"));
+				     _("Mail append canceled"));
 	else
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot append message to mbox file: %s: %s"),
@@ -281,7 +292,7 @@
 	g_free(fromline);
 
 	/* reset the file to original size */
-	fd = open(lf->folder_path, O_WRONLY, 0600);
+	fd = g_open(lf->folder_path, O_WRONLY | O_BINARY, 0600);
 	if (fd != -1) {
 		ftruncate(fd, mbs->folder_size);
 		close(fd);
@@ -291,7 +302,7 @@
 	camel_folder_summary_remove_uid (CAMEL_FOLDER_SUMMARY (mbs), camel_message_info_uid (mi));
 	
 	/* and tell the summary its uptodate */
-	if (stat(lf->folder_path, &st) == 0) {
+	if (g_stat(lf->folder_path, &st) == 0) {
 		mbs->folder_size = st.st_size;
 		((CamelFolderSummary *)mbs)->time = st.st_mtime;
 	}
@@ -352,7 +363,7 @@
 	   with no stream).  This means we dont have to lock the mbox for the life of the message, but only
 	   while it is being created. */
 
-	fd = open(lf->folder_path, O_RDONLY);
+	fd = g_open(lf->folder_path, O_RDONLY | O_BINARY, 0);
 	if (fd == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot get message: %s from folder %s\n  %s"),
Index: camel/providers/local/camel-local-provider.c
===================================================================
--- camel/providers/local/camel-local-provider.c	(revision 444)
+++ camel/providers/local/camel-local-provider.c	(working copy)
@@ -29,15 +29,17 @@
 #include "camel-provider.h"
 #include "camel-session.h"
 #include "camel-url.h"
+#include "camel-i18n.h"
 
 #include "camel-mh-store.h"
 #include "camel-mbox-store.h"
 #include "camel-maildir-store.h"
 #include "camel-spool-store.h"
-#include "camel-i18n.h"
 
 #define d(x)
 
+#ifndef G_OS_WIN32
+
 static CamelProviderConfEntry mh_conf_entries[] = {
 	CAMEL_PROVIDER_CONF_DEFAULT_PATH,
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "general", NULL, N_("Options") },
@@ -58,6 +60,8 @@
 	/* ... */
 };
 
+#endif
+
 static CamelProviderConfEntry mbox_conf_entries[] = {
 	CAMEL_PROVIDER_CONF_DEFAULT_PATH,
 	{ CAMEL_PROVIDER_CONF_END }
@@ -66,7 +70,7 @@
 static CamelProvider mbox_provider = {
 	"mbox",
 	N_("Local delivery"),
-	N_("For retrieving (moving) local mail from standard mbox formated spools into folders managed by Evolution."),
+	N_("For retrieving (moving) local mail from standard mbox-formatted spools into folders managed by Evolution."),
 	"mail",
 	CAMEL_PROVIDER_IS_SOURCE | CAMEL_PROVIDER_IS_STORAGE | CAMEL_PROVIDER_IS_LOCAL,
 	CAMEL_URL_NEED_PATH | CAMEL_URL_PATH_IS_ABSOLUTE | CAMEL_URL_FRAGMENT_IS_PATH,
@@ -74,6 +78,8 @@
 	/* ... */
 };
 
+#ifndef G_OS_WIN32
+
 static CamelProviderConfEntry maildir_conf_entries[] = {
 	CAMEL_PROVIDER_CONF_DEFAULT_PATH,
 	{ CAMEL_PROVIDER_CONF_SECTION_START, "general", NULL, N_("Options") },
@@ -114,6 +120,8 @@
 	/* ... */
 };
 
+#endif
+
 /* build a canonical 'path' */
 static char *
 make_can_path(char *p, char *o)
@@ -193,29 +201,38 @@
 
 void camel_provider_module_init(void)
 {
+#ifndef G_OS_WIN32
 	char *path;
+#endif
 	static int init = 0;
 
 	if (init)
 		abort();
 	init = 1;
 
+#ifndef G_OS_WIN32
 	mh_conf_entries[0].value = "";  /* default path */
 	mh_provider.object_types[CAMEL_PROVIDER_STORE] = camel_mh_store_get_type ();
 	mh_provider.url_hash = local_url_hash;
 	mh_provider.url_equal = local_url_equal;
 	mh_provider.translation_domain = GETTEXT_PACKAGE;
 	camel_provider_register(&mh_provider);
-	
+#endif
+
+#ifndef G_OS_WIN32
 	if (!(path = getenv ("MAIL")))
 		path = g_strdup_printf (SYSTEM_MAIL_DIR "/%s", g_get_user_name ());
 	mbox_conf_entries[0].value = path;  /* default path */
+#else
+	mbox_conf_entries[0].value = "";  /* default path */
+#endif
 	mbox_provider.object_types[CAMEL_PROVIDER_STORE] = camel_mbox_store_get_type ();
 	mbox_provider.url_hash = local_url_hash;
 	mbox_provider.url_equal = local_url_equal;
 	mbox_provider.translation_domain = GETTEXT_PACKAGE;
 	camel_provider_register(&mbox_provider);
-	
+
+#ifndef G_OS_WIN32
 	spool_conf_entries[0].value = path;  /* default path - same as mbox */
 	spool_provider.object_types[CAMEL_PROVIDER_STORE] = camel_spool_store_get_type ();
 	spool_provider.url_hash = local_url_hash;
@@ -230,4 +247,5 @@
 	maildir_provider.url_equal = local_url_equal;
 	maildir_provider.translation_domain = GETTEXT_PACKAGE;
 	camel_provider_register(&maildir_provider);
+#endif
 }
Index: camel/providers/local/camel-local-store.c
===================================================================
--- camel/providers/local/camel-local-store.c	(revision 444)
+++ camel/providers/local/camel-local-store.c	(working copy)
@@ -30,21 +30,22 @@
 #include <stdio.h>
 
 #include <glib.h>
+#include <glib/gstdio.h>
 
-#include "camel-private.h"
+#include <libedataserver/e-data-server-util.h>
+#include "camel/camel-exception.h"
+#include "camel/camel-file-utils.h"
+#include "camel/camel-i18n.h"
+#include "camel/camel-private.h"
+#include "camel/camel-text-index.h"
+#include "camel/camel-url.h"
+#include "camel/camel-vtrash-folder.h"
 
+#include "camel-local-folder.h"
 #include "camel-local-store.h"
-#include "camel-exception.h"
-#include "camel-url.h"
-#include "camel-i18n.h"
 
-#include "camel-local-folder.h"
-#include <camel/camel-text-index.h>
-#include <camel/camel-file-utils.h>
-#include <camel/camel-vtrash-folder.h>
+#define d(x)
 
-#define d(x) 
-
 /* Returns the class for a CamelLocalStore */
 #define CLOCALS_CLASS(so) CAMEL_LOCAL_STORE_CLASS (CAMEL_OBJECT_GET_CLASS(so))
 #define CF_CLASS(so) CAMEL_FOLDER_CLASS (CAMEL_OBJECT_GET_CLASS(so))
@@ -127,7 +128,7 @@
 		return;
 
 	len = strlen (service->url->path);
-	if (service->url->path[len - 1] != '/')
+	if (!G_IS_DIR_SEPARATOR (service->url->path[len - 1]))
 		local_store->toplevel_dir = g_strdup_printf ("%s/", service->url->path);
 	else
 		local_store->toplevel_dir = g_strdup (service->url->path);
@@ -142,16 +143,21 @@
 static CamelFolder *
 get_folder(CamelStore * store, const char *folder_name, guint32 flags, CamelException * ex)
 {
-	char *path = ((CamelLocalStore *)store)->toplevel_dir;
+	int len = strlen(((CamelLocalStore *)store)->toplevel_dir);
+	char *path = g_alloca(len + 1);
 	struct stat st;
+
+	strcpy(path, ((CamelLocalStore *)store)->toplevel_dir);
+	if (G_IS_DIR_SEPARATOR(path[len-1]))
+		path[len-1] = '\0';
 	
-	if (path[0] != '/') {
+	if (!g_path_is_absolute(path)) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				     _("Store root %s is not an absolute path"), path);
 		return NULL;
 	}
 
-	if (stat(path, &st) == 0) {
+	if (g_stat(path, &st) == 0) {
 		if (!S_ISDIR(st.st_mode)) {
 			camel_exception_setv(ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 					     _("Store root %s is not a regular directory"), path);
@@ -169,7 +175,7 @@
 	}
 	
 	/* need to create the dir heirarchy */
-	if (camel_mkdir (path, 0777) == -1 && errno != EEXIST) {
+	if (e_util_mkdir_hier (path, 0777) == -1 && errno != EEXIST) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				      _("Cannot get folder: %s: %s"),
 				      path, g_strerror (errno));
@@ -256,7 +262,7 @@
 
 	/* This is a pretty hacky version of create folder, but should basically work */
 
-	if (path[0] != '/') {
+	if (g_path_is_absolute(path)) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				     _("Store root %s is not an absolute path"), path);
 		return NULL;
@@ -267,7 +273,7 @@
 	else
 		name = g_strdup_printf("%s/%s", path, folder_name);
 
-	if (stat(name, &st) == 0 || errno != ENOENT) {
+	if (g_stat(name, &st) == 0 || errno != ENOENT) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				      _("Cannot get folder: %s: %s"),
 				      name, g_strerror (errno));
@@ -300,20 +306,21 @@
 static int xrename(const char *oldp, const char *newp, const char *prefix, const char *suffix, int missingok, CamelException *ex)
 {
 	struct stat st;
-	char *old = g_strconcat(prefix, oldp, suffix, 0);
-	char *new = g_strconcat(prefix, newp, suffix, 0);
+	char *old = g_strconcat(prefix, oldp, suffix, NULL);
+	char *new = g_strconcat(prefix, newp, suffix, NULL);
 	int ret = -1;
 	int err = 0;
 
 	d(printf("renaming %s%s to %s%s\n", oldp, suffix, newp, suffix));
 
-	if (stat(old, &st) == -1) {
+	if (g_stat(old, &st) == -1) {
 		if (missingok && errno == ENOENT) {
 			ret = 0;
 		} else {
 			err = errno;
 			ret = -1;
 		}
+#ifndef G_OS_WIN32
 	} else if (S_ISDIR(st.st_mode)) { /* use rename for dirs */
 		if (rename(old, new) == 0
 		    || stat(new, &st) == 0) {
@@ -334,6 +341,14 @@
 	} else {
 		err = errno;
 		ret = -1;
+#else
+	} else if ((!g_file_test (new, G_FILE_TEST_EXISTS) || g_remove (new) == 0) &&
+		   g_rename(old, new) == 0) {
+		ret = 0;
+	} else {
+		err = errno;
+		ret = -1;
+#endif
 	}
 
 	if (ret == -1) {
@@ -426,7 +441,7 @@
 	/* remove metadata only */
 	name = g_strdup_printf("%s%s", CAMEL_LOCAL_STORE(store)->toplevel_dir, folder_name);
 	str = g_strdup_printf("%s.ev-summary", name);
-	if (unlink(str) == -1 && errno != ENOENT) {
+	if (g_unlink(str) == -1 && errno != ENOENT) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not delete folder summary file `%s': %s"),
 				      str, g_strerror (errno));
@@ -459,7 +474,7 @@
 	if (str == NULL)
 		str = g_strdup_printf ("%s.cmeta", name);
 	
-	if (unlink (str) == -1 && errno != ENOENT) {
+	if (g_unlink (str) == -1 && errno != ENOENT) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not delete folder meta file `%s': %s"),
 				      str, g_strerror (errno));
Index: camel/providers/local/camel-spool-store.c
===================================================================
--- camel/providers/local/camel-spool-store.c	(revision 444)
+++ camel/providers/local/camel-spool-store.c	(working copy)
@@ -36,6 +36,7 @@
 #include <stdio.h>
 #include <dirent.h>
 
+#include <libedataserver/e-data-server-util.h>
 #include "camel-spool-store.h"
 #include "camel-spool-folder.h"
 #include "camel-exception.h"
@@ -492,7 +493,7 @@
 	if (root == NULL)
 		return NULL;
 
-	camel_mkdir(root, 0777);
+	e_util_mkdir_hier(root, 0777);
 	key = camel_file_util_safe_filename(full_name);
 	path = g_strdup_printf("%s/%s%s", root, key, ext);
 	g_free(key);
Index: camel/providers/local/ChangeLog
===================================================================
--- camel/providers/local/ChangeLog	(revision 444)
+++ camel/providers/local/ChangeLog	(working copy)
@@ -1,3 +1,77 @@
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-maildir-folder.c: 
+	* camel-mbox-folder.c: 
+	* camel-mh-folder.c:
+	changing "cancelled" to "canceled" in user-visible strings.
+	Fixes bug #342163.
+
+2006-06-15  Tor Lillqvist  <tml@novell.com>
+
+	* camel-mbox-summary.c (summary_update, mbox_summary_check)
+	(mbox_summary_sync): Use g_stat() instead of plain stat() for full
+	Unicode pathname support on Win32. These instances had gone
+	unnoticed earlier.
+
+2006-06-09  Chris Heath  <chris@heathens.co.nz>
+
+	* camel-local-summary.c (message_info_new_from_header): Fix memory leak
+	* camel-mbox-summary.c (message_info_new_from_header): Ditto.
+	Fixes bug #335423.
+
+2006-03-28  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-mbox-summary.c (summary_update, mbox_summary_sync_full),
+	(mbox_summary_sync_full, mbox_summary_sync_quick): Use O_LARGEFILE
+	when opening the mbox file.
+
+	* camel-mbox-store.c (get_folder): Use O_LARGEFILE when opening
+	the mbox file.
+
+	* camel-mbox-folder.c (mbox_append_message, mbox_get_message): Use
+	O_LARGEFILE when opening the mbox file.
+
+2006-03-28  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 160889 on bugzilla.novell.com
+
+	* camel-mbox-store.c: ignore *.ev-summary-meta extensions 
+	when displaying folder lists
+
+2005-12-09  Tor Lillqvist  <tml@novell.com>
+
+	* camel-mbox-folder.c: Just #define O_BINARY as 0 on Unix, less
+	ifdefs that way. Should really do this in some suitable header, of
+	course, and not duplicate here and there.
+
+2005-12-09  David Malcolm  <dmalcolm@redhat.com>
+
+	* camel-local-folder.c: restore missing declarations for non-Win32 
+	systems.
+
+	* camel-mbox-folder.c: avoid use of O_BINARY on non-Win32 systems.
+
+2005-12-08  Tor Lillqvist  <tml@novell.com>
+
+	* *.c: Use gstdio wrappers. Use GLib portable path manipulation
+	API. No symlinks on Win32. Use GDir instead of dirent.
+
+	* camel-local-provider.c: Compile in only the mbox provider on Win32.
+
+	* camel-mbox-folder.c: Bypass locking so far on Win32. Should
+	implement, though, several threads in Evo might be accessing the
+	same mbox folder.
+
+	* camel-mbox-store.c: No inode numbers on Win32, but no symlinks
+	either, so bypass the code to avoid visiting the same folder
+	twice.
+
+2005-09-15  Tor Lillqvist  <tml@novell.com>
+
+	* camel-local-summary.c: Use g_ascii_strcasecmp() instead of
+	strcasecmp(). The strings we are comparing are just ASCII anyway,
+	so spell it out that we really do need ASCII casefolding only.
+
 2005-08-22  Not Zed  <NotZed@Ximian.com>
 
 	* camel-mbox-summary.c (mbox_summary_sync_quick): removed some
Index: camel/providers/local/camel-maildir-folder.c
===================================================================
--- camel/providers/local/camel-maildir-folder.c	(revision 444)
+++ camel/providers/local/camel-maildir-folder.c	(working copy)
@@ -212,7 +212,7 @@
 	
 	if (errno == EINTR)
 		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-				     _("Maildir append message cancelled"));
+				     _("Maildir append message canceled"));
 	else
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot append message to maildir folder: %s: %s"),
Index: camel/providers/local/camel-mbox-store.c
===================================================================
--- camel/providers/local/camel-mbox-store.c	(revision 444)
+++ camel/providers/local/camel-mbox-store.c	(working copy)
@@ -27,17 +27,22 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
-#include <dirent.h>
 #include <fcntl.h>
 #include <errno.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#include <libedataserver/e-data-server-util.h>
+#include "camel/camel-exception.h"
+#include "camel/camel-file-utils.h"
+#include "camel/camel-i18n.h"
+#include "camel/camel-private.h"
+#include "camel/camel-text-index.h"
+#include "camel/camel-url.h"
+
+#include "camel-mbox-folder.h"
 #include "camel-mbox-store.h"
-#include "camel-mbox-folder.h"
-#include "camel-file-utils.h"
-#include "camel-text-index.h"
-#include "camel-exception.h"
-#include "camel-url.h"
-#include "camel-i18n.h"
 
 #define d(x) 
 
@@ -95,7 +100,7 @@
 }
 
 static char *extensions[] = {
-	".msf", ".ev-summary", ".ibex.index", ".ibex.index.data", ".cmeta", ".lock"
+	".msf", ".ev-summary", ".ev-summary-meta", ".ibex.index", ".ibex.index.data", ".cmeta", ".lock"
 };
 
 static gboolean
@@ -131,8 +136,8 @@
 	
 	name = camel_local_store_get_full_path(store, folder_name);
 	
-	if (stat(name, &st) == -1) {
-		const char *basename;
+	if (g_stat(name, &st) == -1) {
+		char *basename;
 		char *dirname;
 		int fd;
 		
@@ -153,20 +158,19 @@
 		}
 		
 		/* sanity check the folder name */
-		if (!(basename = strrchr (folder_name, '/')))
-			basename = folder_name;
-		else
-			basename++;
+		basename = g_path_get_basename (folder_name);
 		
 		if (basename[0] == '.' || ignore_file (basename, TRUE)) {
 			camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM,
 					     _("Cannot create a folder by this name."));
 			g_free (name);
+			g_free (basename);
 			return NULL;
 		}
+		g_free (basename);
 		
 		dirname = g_path_get_dirname(name);
-		if (camel_mkdir(dirname, 0777) == -1 && errno != EEXIST) {
+		if (e_util_mkdir_hier(dirname, 0777) == -1 && errno != EEXIST) {
 			camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 					     _("Cannot create folder `%s': %s"),
 					     folder_name, g_strerror (errno));
@@ -177,7 +181,7 @@
 		
 		g_free(dirname);
 		
-		fd = open(name, O_WRONLY | O_CREAT | O_APPEND, 0666);
+		fd = g_open(name, O_WRONLY | O_CREAT | O_APPEND | O_BINARY, 0666);
 		if (fd == -1) {
 			camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 					     _("Cannot create folder `%s': %s"),
@@ -218,7 +222,7 @@
 	name = camel_local_store_get_full_path(store, folder_name);
 	path = g_strdup_printf("%s.sbd", name);
 	
-	if (rmdir(path) == -1 && errno != ENOENT) {
+	if (g_rmdir(path) == -1 && errno != ENOENT) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 				     _("Could not delete folder `%s':\n%s"),
 				     folder_name, g_strerror(errno));
@@ -229,7 +233,7 @@
 	
 	g_free(path);
 	
-	if (stat(name, &st) == -1) {
+	if (g_stat(name, &st) == -1) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 				     _("Could not delete folder `%s':\n%s"),
 				     folder_name, g_strerror(errno));
@@ -252,7 +256,7 @@
 		return;
 	}
 	
-	if (unlink(name) == -1 && errno != ENOENT) {
+	if (g_unlink(name) == -1 && errno != ENOENT) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 				     _("Could not delete folder `%s':\n%s"),
 				     name, g_strerror(errno));
@@ -266,7 +270,7 @@
 	 * CamelLocalStore to be able to construct the folder & meta
 	 * paths itself */
 	path = camel_local_store_get_meta_path(store, folder_name, ".ev-summary");
-	if (unlink(path) == -1 && errno != ENOENT) {
+	if (g_unlink(path) == -1 && errno != ENOENT) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 				     _("Could not delete folder summary file `%s': %s"),
 				     path, g_strerror(errno));
@@ -302,7 +306,7 @@
 	if (path == NULL)
 		path = camel_local_store_get_meta_path(store, folder_name, ".cmeta");
 	
-	if (unlink(path) == -1 && errno != ENOENT) {
+	if (g_unlink(path) == -1 && errno != ENOENT) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 				     _("Could not delete folder meta file `%s': %s"),
 				     path, g_strerror(errno));
@@ -337,7 +341,7 @@
 	CamelFolder *folder;
 	struct stat st;
 	
-	if (toplevel_dir[0] != '/') {
+	if (!g_path_is_absolute(toplevel_dir)) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				     _("Store root %s is not an absolute path"), toplevel_dir);
 		return NULL;
@@ -357,7 +361,7 @@
 	path = camel_local_store_get_full_path(store, name);
 	
 	dir = g_path_get_dirname(path);
-	if (camel_mkdir(dir, 0777) == -1 && errno != EEXIST) {
+	if (e_util_mkdir_hier(dir, 0777) == -1 && errno != EEXIST) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM, _("Cannot create directory `%s': %s."),
 				     dir, g_strerror(errno));
 		
@@ -370,7 +374,7 @@
 	
 	g_free(dir);
 	
-	if (stat(path, &st) == 0 || errno != ENOENT) {
+	if (g_stat(path, &st) == 0 || errno != ENOENT) {
 		camel_exception_setv(ex, CAMEL_EXCEPTION_STORE_NO_FOLDER,
 				     _("Cannot create folder: %s: %s"),
 				     path, errno ? g_strerror(errno) :
@@ -412,13 +416,14 @@
 		newpath = camel_local_store_get_full_path(ls, new_name);
 	}
 	
-	if (stat(oldpath, &st) == -1) {
+	if (g_stat(oldpath, &st) == -1) {
 		if (missingok && errno == ENOENT) {
 			ret = 0;
 		} else {
 			err = errno;
 			ret = -1;
 		}
+#ifndef G_OS_WIN32
 	} else if (S_ISDIR(st.st_mode)) {
 		/* use rename for dirs */
 		if (rename(oldpath, newpath) == 0 || stat(newpath, &st) == 0) {
@@ -439,6 +444,14 @@
 	} else {
 		err = errno;
 		ret = -1;
+#else
+	} else if ((!g_file_test (newpath, G_FILE_TEST_EXISTS) || g_remove (newpath) == 0) &&
+		   g_rename(oldpath, newpath) == 0) {
+		ret = 0;
+	} else {
+		err = errno;
+		ret = -1;
+#endif
 	}
 	
 	g_free(oldpath);
@@ -466,7 +479,7 @@
 	newibex = camel_local_store_get_meta_path(store, new, ".ibex");
 	
 	newdir = g_path_get_dirname(newibex);
-	if (camel_mkdir(newdir, 0777) == -1) {
+	if (e_util_mkdir_hier(newdir, 0777) == -1) {
 		if (errno != EEXIST) {
 			camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM,
 					     _("Could not rename `%s': `%s': %s"),
@@ -539,7 +552,7 @@
 ibex_failed:
 	if (newdir) {
 		/* newdir is only non-NULL if we needed to mkdir */
-		rmdir(newdir);
+		g_rmdir(newdir);
 		g_free(newdir);
 	}
 	
@@ -623,12 +636,12 @@
 {
 	CamelFolderInfo *folders, *tail, *fi;
 	GHashTable *folder_hash;
-	struct dirent *dent;
-	DIR *dir;
+	const char *dent;
+	GDir *dir;
 	
 	tail = folders = NULL;
 	
-	if (!(dir = opendir(root)))
+	if (!(dir = g_dir_open(root, 0, NULL)))
 		return NULL;
 	
 	folder_hash = g_hash_table_new(g_str_hash, g_str_equal);
@@ -637,22 +650,22 @@
 	 * scans till the end so that we can limit the number of
 	 * directory descriptors open at any given time... */
 	
-	while ((dent = readdir(dir))) {
+	while ((dent = g_dir_read_name(dir))) {
 		char *short_name, *full_name, *path, *ext;
 		struct stat st;
 		
-		if (dent->d_name[0] == '.')
+		if (dent[0] == '.')
 			continue;
 		
-		if (ignore_file(dent->d_name, FALSE))
+		if (ignore_file(dent, FALSE))
 			continue;
 		
-		path = g_strdup_printf("%s/%s", root, dent->d_name);
-		if (stat(path, &st) == -1) {
+		path = g_strdup_printf("%s/%s", root, dent);
+		if (g_stat(path, &st) == -1) {
 			g_free(path);
 			continue;
 		}
-		
+#ifndef G_OS_WIN32		
 		if (S_ISDIR(st.st_mode)) {
 			struct _inode in = { st.st_dev, st.st_ino };
 			
@@ -661,8 +674,8 @@
 				continue;
 			}
 		}
-		
-		short_name = g_strdup(dent->d_name);
+#endif		
+		short_name = g_strdup(dent);
 		if ((ext = strrchr(short_name, '.')) && !strcmp(ext, ".sbd"))
 			*ext = '\0';
 		
@@ -713,12 +726,12 @@
 			struct _inode in = { st.st_dev, st.st_ino };
 			
 			if (g_hash_table_lookup(visited, &in) == NULL) {
+#ifndef G_OS_WIN32
 				struct _inode *inew = g_new(struct _inode, 1);
 				
 				*inew = in;
-				
 				g_hash_table_insert(visited, inew, inew);
-				
+#endif
 				if ((fi->child = scan_dir (store, url, visited, fi, path, fi->full_name, flags, ex)))
 					fi->flags |= CAMEL_FOLDER_CHILDREN;
 				else
@@ -729,7 +742,7 @@
 		g_free(path);
 	}
 	
-	closedir(dir);
+	g_dir_close(dir);
 	
 	g_hash_table_destroy(folder_hash);
 	
@@ -740,10 +753,12 @@
 get_folder_info(CamelStore *store, const char *top, guint32 flags, CamelException *ex)
 {
 	GHashTable *visited;
+#ifndef G_OS_WIN32
 	struct _inode *inode;
+#endif
 	char *path, *subdir;
 	CamelFolderInfo *fi;
-	const char *base;
+	char *basename;
 	struct stat st;
 	CamelURL *url;
 	
@@ -752,19 +767,19 @@
 	
 	if (*top == '\0') {
 		/* requesting root dir scan */
-		if (stat(path, &st) == -1 || !S_ISDIR(st.st_mode)) {
+		if (g_stat(path, &st) == -1 || !S_ISDIR(st.st_mode)) {
 			g_free(path);
 			return NULL;
 		}
 		
 		visited = g_hash_table_new(inode_hash, inode_equal);
-		
+#ifndef G_OS_WIN32
 		inode = g_malloc0(sizeof(*inode));
 		inode->dnode = st.st_dev;
 		inode->inode = st.st_ino;
 		
 		g_hash_table_insert(visited, inode, inode);
-		
+#endif
 		url = camel_url_copy (((CamelService *) store)->url);
 		fi = scan_dir (store, url, visited, NULL, path, NULL, flags, ex);
 		g_hash_table_foreach(visited, inode_free, NULL);
@@ -776,17 +791,14 @@
 	}
 	
 	/* requesting scan of specific folder */
-	if (stat(path, &st) == -1 || !S_ISREG(st.st_mode)) {
+	if (g_stat(path, &st) == -1 || !S_ISREG(st.st_mode)) {
 		g_free(path);
 		return NULL;
 	}
 	
 	visited = g_hash_table_new(inode_hash, inode_equal);
 	
-	if (!(base = strrchr(top, '/')))
-		base = top;
-	else
-		base++;
+	basename = g_path_get_basename(top);
 	
 	url = camel_url_copy (((CamelService *) store)->url);
 	camel_url_set_fragment (url, top);
@@ -794,13 +806,13 @@
 	fi = g_new0(CamelFolderInfo, 1);
 	fi->parent = NULL;
 	fi->uri = camel_url_to_string (url, 0);
-	fi->name = g_strdup(base);
+	fi->name = basename;
 	fi->full_name = g_strdup(top);
 	fi->unread = -1;
 	fi->total = -1;
 	
 	subdir = g_strdup_printf("%s.sbd", path);
-	if (stat(subdir, &st) == 0) {
+	if (g_stat(subdir, &st) == 0) {
 		if  (S_ISDIR(st.st_mode))
 			fi->child = scan_dir (store, url, visited, fi, subdir, top, flags, ex);
 		else
@@ -832,7 +844,7 @@
 	char *path, *p;
 	
 	while (*inptr != '\0') {
-		if (*inptr == '/')
+		if (G_IS_DIR_SEPARATOR (*inptr))
 			subdirs++;
 		inptr++;
 	}
@@ -842,15 +854,15 @@
 	
 	inptr = full_name;
 	while (*inptr != '\0') {
-		while (*inptr != '/' && *inptr != '\0')
+		while (!G_IS_DIR_SEPARATOR (*inptr) && *inptr != '\0')
 			*p++ = *inptr++;
 		
-		if (*inptr == '/') {
+		if (G_IS_DIR_SEPARATOR (*inptr)) {
 			p = g_stpcpy (p, ".sbd/");
 			inptr++;
 			
 			/* strip extranaeous '/'s */
-			while (*inptr == '/')
+			while (G_IS_DIR_SEPARATOR (*inptr))
 				inptr++;
 		}
 	}
Index: camel/providers/local/camel-local-folder.c
===================================================================
--- camel/providers/local/camel-local-folder.c	(revision 444)
+++ camel/providers/local/camel-local-folder.c	(working copy)
@@ -27,17 +27,20 @@
 #include <stdlib.h>
 #include <limits.h>
 #include <sys/types.h>
-#include <dirent.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <errno.h>
 #include <string.h>
 #include <fcntl.h>
 
-#ifndef _POSIX_PATH_MAX
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#if !defined (G_OS_WIN32) && !defined (_POSIX_PATH_MAX)
 #include <posix1_lim.h>
 #endif
 
+#include "camel-private.h"
 #include "camel-local-folder.h"
 #include "camel-local-store.h"
 #include "camel-stream-fs.h"
@@ -204,21 +207,20 @@
 {
 	CamelFolderInfo *fi;
 	CamelFolder *folder;
-	const char *root_dir_path, *name;
+	const char *root_dir_path;
+	char *name;
 	char *tmp, *statepath;
+#ifndef G_OS_WIN32
 	char folder_path[PATH_MAX];
 	struct stat st;
+#endif
 	int forceindex, len;
 	CamelURL *url;
 	CamelLocalStore *ls = (CamelLocalStore *)parent_store;
 	
 	folder = (CamelFolder *)lf;
 
-	name = strrchr(full_name, '/');
-	if (name)
-		name++;
-	else
-		name = full_name;
+	name = g_path_get_basename(full_name);
 
 	camel_folder_construct(folder, parent_store, full_name, name);
 
@@ -227,7 +229,7 @@
 	len = strlen (root_dir_path);
 	tmp = g_alloca (len + 1);
 	strcpy (tmp, root_dir_path);
-	if (len>1 && tmp[len-1] == '/')
+	if (len>1 && G_IS_DIR_SEPARATOR(tmp[len-1]))
 		tmp[len-1] = 0;
 
 	lf->base_path = g_strdup(root_dir_path);
@@ -247,19 +249,19 @@
 		camel_object_set(lf, NULL, CAMEL_LOCAL_FOLDER_INDEX_BODY, TRUE, 0);
 		camel_object_state_write(lf);
 	}
-
+#ifndef G_OS_WIN32
 	/* follow any symlinks to the mailbox */
 	if (lstat (lf->folder_path, &st) != -1 && S_ISLNK (st.st_mode) &&
 	    realpath (lf->folder_path, folder_path) != NULL) {
 		g_free (lf->folder_path);
 		lf->folder_path = g_strdup (folder_path);
 	}
-	
+#endif
 	lf->changes = camel_folder_change_info_new();
 
 	/* TODO: Remove the following line, it is a temporary workaround to remove
 	   the old-format 'ibex' files that might be lying around */
-	unlink(lf->index_path);
+	g_unlink(lf->index_path);
 
 	/* FIXME: Need to run indexing off of the setv method */
 
@@ -297,6 +299,7 @@
 	/* we sync here so that any hard work setting up the folder isn't lost */
 	/*if (camel_local_summary_sync((CamelLocalSummary *)folder->summary, FALSE, lf->changes, ex) == -1) {
 		camel_object_unref (CAMEL_OBJECT (folder));
+		g_free(name);
 		return NULL;
 		}*/
 #endif
@@ -318,7 +321,7 @@
 		camel_object_trigger_event(CAMEL_OBJECT (parent_store), "folder_created", fi);
 		camel_folder_info_free(fi);
 	}
-	
+	g_free(name);
 	return lf;
 }
 
Index: camel/providers/local/camel-mh-folder.c
===================================================================
--- camel/providers/local/camel-mh-folder.c	(revision 444)
+++ camel/providers/local/camel-mh-folder.c	(working copy)
@@ -172,7 +172,7 @@
 	
 	if (errno == EINTR)
 		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL,
-				     _("MH append message cancelled"));
+				     _("MH append message canceled"));
 	else
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot append message to mh folder: %s: %s"),
Index: camel/providers/sendmail/camel-sendmail-transport.c
===================================================================
--- camel/providers/sendmail/camel-sendmail-transport.c	(revision 444)
+++ camel/providers/sendmail/camel-sendmail-transport.c	(working copy)
@@ -128,7 +128,7 @@
 	header = (struct _camel_header_raw *) &CAMEL_MIME_PART (message)->headers;
 	n = header->next;
 	while (n != NULL) {
-		if (!strcasecmp (n->name, "Bcc")) {
+		if (!g_ascii_strcasecmp (n->name, "Bcc")) {
 			header->next = n->next;
 			tail->next = n;
 			n->next = NULL;
Index: camel/providers/sendmail/ChangeLog
===================================================================
--- camel/providers/sendmail/ChangeLog	(revision 444)
+++ camel/providers/sendmail/ChangeLog	(working copy)
@@ -1,3 +1,9 @@
+2005-09-16  Tor Lillqvist  <tml@novell.com>
+
+	* camel-sendmail-transport.c: Use g_ascii_strcasecmp() instead of
+	strcasecmp(). The strings we are comparing are just ASCII anyway,
+	so spell it out that we really do need ASCII casefolding only.
+
 2005-04-17  Changwoo Ryu  <cwryu@debian.org>
 
 	** See bug #300891
Index: camel/camel-mime-utils.c
===================================================================
--- camel/camel-mime-utils.c	(revision 444)
+++ camel/camel-mime-utils.c	(working copy)
@@ -43,11 +43,12 @@
 #endif
 
 #include <glib.h>
-#include <libedataserver/e-iconv.h>
-#include <libedataserver/e-time-utils.h>
 
+#include "libedataserver/e-iconv.h"
+#include "libedataserver/e-time-utils.h"
+
+#include "camel-charset-map.h"
 #include "camel-mime-utils.h"
-#include "camel-charset-map.h"
 #include "camel-net-utils.h"
 #include "camel-utf8.h"
 
@@ -55,6 +56,16 @@
 #include "broken-date-parser.h"
 #endif
 
+#ifdef G_OS_WIN32
+/* Undef the similar macro from pthread.h, it doesn't check if
+ * gmtime() returns NULL.
+ */
+#undef gmtime_r
+
+/* The gmtime() in Microsoft's C library is MT-safe */
+#define gmtime_r(tp,tmp) (gmtime(tp)?(*(tmp)=*gmtime(tp),(tmp)):0)
+#endif
+
 #if 0
 int strdup_count = 0;
 int malloc_count = 0;
@@ -1297,7 +1308,7 @@
 	
 	ascii = g_alloca (bufflen);
 	
-	if (strcasecmp (type, "UTF-8") != 0)
+	if (g_ascii_strcasecmp (type, "UTF-8") != 0)
 		ic = e_iconv_open (type, "UTF-8");
 	
 	while (inlen) {
@@ -2151,16 +2162,16 @@
 {
 	/* no type == text/plain or text/"*" */
 	if (ct==NULL || (ct->type == NULL && ct->subtype == NULL)) {
-		return (!strcasecmp(type, "text")
+		return (!g_ascii_strcasecmp(type, "text")
 			&& (!g_ascii_strcasecmp(subtype, "plain")
-			    || !strcasecmp(subtype, "*")));
+			    || !strcmp(subtype, "*")));
 	}
 
 	return (ct->type != NULL
 		&& (!g_ascii_strcasecmp(ct->type, type)
 		    && ((ct->subtype != NULL
 			 && !g_ascii_strcasecmp(ct->subtype, subtype))
-			|| !strcasecmp("*", subtype))));
+			|| !strcmp("*", subtype))));
 }
 
 
@@ -2236,6 +2247,7 @@
 			g_free(ct->type);
 			g_free(ct->subtype);
 			g_free(ct);
+			ct = NULL;
 		} else {
 			ct->refcount--;
 		}
@@ -2246,19 +2258,18 @@
 static char *
 header_decode_domain(const char **in)
 {
-	const char *inptr = *in, *start;
+	const char *inptr = *in;
 	int go = TRUE;
 	char *ret;
 	GString *domain = g_string_new("");
 
-				/* domain ref | domain literal */
+	/* domain ref | domain literal */
 	header_decode_lwsp(&inptr);
 	while (go) {
 		if (*inptr == '[') { /* domain literal */
 			domain = g_string_append_c(domain, '[');
 			inptr++;
 			header_decode_lwsp(&inptr);
-			start = inptr;
 			while (camel_mime_is_dtext(*inptr)) {
 				domain = g_string_append_c(domain, *inptr);
 				inptr++;
@@ -2437,7 +2448,7 @@
 				}
 			}
 			pre = header_decode_word (&inptr);
-			header_decode_lwsp(&inptr);
+			/*header_decode_lwsp(&inptr);*/
 		} else {
 			w(g_warning("broken address? %s", *in));
 		}
@@ -2496,10 +2507,10 @@
 					g_string_truncate(name, 0);
 					g_string_append(name, text);
 				}
-			} else {
+			}/* else {
 				g_string_append(name, text?text:addr->str);
 				g_string_truncate(addr, 0);
-			}
+			}*/
 			g_free(text);
 
 			/* or maybe that we've added up a bunch of broken bits to make an encoded word */
@@ -3196,7 +3207,8 @@
 	const char *charset;
 	GString *out;
 	guint32 c;
-
+	char *str;
+	
 	*encoded = FALSE;
 	
 	g_return_val_if_fail (in != NULL, NULL);
@@ -3226,11 +3238,11 @@
 	}
 	g_free (outbuf);
 	
-	outbuf = out->str;
+	str = out->str;
 	g_string_free (out, FALSE);
 	*encoded = TRUE;
 	
-	return outbuf;
+	return str;
 }
 
 void
@@ -3363,7 +3375,7 @@
 			inptr++;
 			subtype = decode_token(&inptr);
 		}
-		if (subtype == NULL && (!strcasecmp(type, "text"))) {
+		if (subtype == NULL && (!g_ascii_strcasecmp(type, "text"))) {
 			w(g_warning("text type with no subtype, resorting to text/plain: %s", in));
 			subtype = g_strdup("plain");
 		}
@@ -3519,7 +3531,7 @@
 }
 
 /* hrm, is there a library for this shit? */
-static const struct {
+static struct {
 	char *name;
 	int offset;
 } tz_offsets [] = {
@@ -3829,13 +3841,13 @@
 
 	/* debug */
 #if 0
-	if (!strcasecmp(name, "To")) {
+	if (!g_ascii_strcasecmp(name, "To")) {
 		printf("- Decoding To\n");
 		camel_header_to_decode(value);
-	} else if (!strcasecmp(name, "Content-type")) {
+	} else if (!g_ascii_strcasecmp(name, "Content-type")) {
 		printf("- Decoding content-type\n");
 		camel_content_type_dump(camel_content_type_decode(value));		
-	} else if (!strcasecmp(name, "MIME-Version")) {
+	} else if (!g_ascii_strcasecmp(name, "MIME-Version")) {
 		printf("- Decoding mime version\n");
 		camel_header_mime_decode(value);
 	}
@@ -4058,23 +4070,23 @@
 			match[j].rm_eo = -1;
 		}
 		if (v != NULL && regexec (&mail_list_magic[i].regex, v, 3, match, 0) == 0 && match[1].rm_so != -1) {
-			char *list;
 			int len1, len2;
-
+			char *mlist;
+			
 			len1 = match[1].rm_eo - match[1].rm_so;
 			len2 = match[2].rm_eo - match[2].rm_so;
-
-			list = g_malloc(len1+len2+2);
-			memcpy(list, v + match[1].rm_so, len1);
+			
+			mlist = g_malloc (len1 + len2 + 2);
+			memcpy (mlist, v + match[1].rm_so, len1);
 			if (len2) {
-				list[len1] = '@';
-				memcpy(list+len1+1, v+match[2].rm_so, len2);
-				list[len1+len2+1]=0;
+				mlist[len1] = '@';
+				memcpy (mlist + len1 + 1, v + match[2].rm_so, len2);
+				mlist[len1 + len2 + 1] = '\0';
 			} else {
-				list[len1] = 0;
+				mlist[len1] = '\0';
 			}
-
-			return list;
+			
+			return mlist;
 		}
 	}
 
Index: camel/ChangeLog
===================================================================
--- camel/ChangeLog	(revision 444)
+++ camel/ChangeLog	(working copy)
@@ -1,29 +1,548 @@
+2006-07-07  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-string-utils.c (camel_pstring_add): If the value is in the
+	table already and 'own' is TRUE, g_free the passed-in string.
+
+2006-07-07  Sankar P  <psankar@novell.com>
+
+	* camel-string-utils.c (camel_pstring_add):
+	Fixes a variable naming error. Fixes build break.
+		
+2006-07-06  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-string-utils.c (camel_pstring_add): New function that now
+	holds the main logic of the old camel_pstring_strdup function. If
+	'own' is TRUE, re-use the memory if the string doesn't already
+	exist and free it otherwise. If FALSE, strdup the value if it
+	doesn't already exist.
+	(camel_pstring_strdup): Calls camel_pstring_add() with 'own' as
+	FALSE.
+
+	* camel-folder-summary.c (message_info_new_from_header): Use
+	camel_pstring_add instead of camel_pstring_strdup here to prevent
+	unnecessary strdup/freeing.
+	(message_info_load): Same.
+
+2006-06-26  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-gpg-context.c (gpg_ctx_parse_status): Only set name to ""
+	if it wasn't already set. Fixes bug #345965.
+
+2006-06-15  Tor Lillqvist  <tml@novell.com>
+
+	* camel.c (camel_init): On Win32, NSS wants the directory name in
+	system codepage, not UTF-8. No need to handle g_atexit()
+	differently on Win32 any longer, in current GLib it is on Win32
+	just a #define for atexit().
+
+2006-06-15  Andre Klapper  <a9016009@gmx.de>
+
+	* camel-gpg-context.c:
+
+	* camel-net-utils.c: changing "cancelled" to "canceled" in
+	user-visible strings.  Fixes bug #342163.
+
+2006-06-15  Andre Klapper <a9016009@gmx.de>
+
+	* addressbook/libebook/e-book.c:
+
+	* camel/camel-folder.c:
+
+	* camel/providers/nntp/camel-nntp-folder.c:
+
+	* camel/providers/pop3/camel-pop3-folder.c: changing "uri" to
+	"URI" in user-visible strings.  Fixes bug #342161.
+
+2006-06-09  Chris Heath  <chris@heathens.co.nz>
+
+	* camel-net-utils.c (camel_getnameinfo): Fix memory leak
+
+	* camel-folder-search.c (camel_folder_search_search): Ditto
+
+	* camel-digest-folder.c (digest_add_multipart): Ditto.
+	Fixes bug #335423.
+
+2006-06-02  Tor Lillqvist  <tml@novell.com>
+
+	* camel-file-utils.c (camel_read, camel_write, camel_read_socket)
+	(camel_write_socket): Improve doc comment, mention the Win32
+	aspects.
+
+2006-05-25  Srinivasa Ragavan  <sragavan@novell.com>
+
+	* camel-stream-vfs.h: Added the missed file to commit.
+
+2006-05-24  Srinivasa Ragavan  <sragavan@novell.com>
+
+	* Makefile.am: Added new files for camel vfs stream
+	* camel-stream-vfs.[ch]: Added a new gnome-vfs backend for 
+	camel stream.
+
+2006-05-05  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-charset-map.c (camel_charset_best_mask): Fixed a
+	mis-ordering of an if-statement clause that caused bug #340717.
+
+2006-05-01  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-gpg-context.c (gpg_ctx_parse_status): Handle prompts from
+	GnuPG asking for the user's PIN for their SmartCard. Fixes bug
+	#335386.
+
+2006-04-19  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-mime-filter-pgp.c (filter_run): You cannot CANNOT modify
+	the input strings. EVER. Fixed to not do that and to also work if
+	there is preface before the pgp block (previous code failed in
+	that case).
+	(reset): Reset the filter state.
+
+2006-04-13  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-mime-utils.c (camel_header_raw_check_mailing_list): Fixed
+	a goof in the last patch.
+
+2006-04-12  Jeffrey Stedfast  <fejj@novell.com>
+
+	* Fixes to many source files to suppress compiler warnings thanks
+	to Kjartan Maraas.
+
+2006-04-04  Jeffrey Stedfast  <fejj@novell.com>
+
+	* camel-charset-map.c (main): Set appropriate structs/struct
+	elements to static/const.
+
+	* camel-charset-map-private.h: Regenerated.
+
+2006-04-05  Simon Zheng  <simon.zheng@sun.com>
+
+	** Fixes bug #333698
+
+	* camel-search-private.c (header_match):
+	(camel_search_header_match):
+	To traverse strings by utf8 char order rather than one by one byte,
+	use camel_utf8_getc() and other utf8-specific routines instead.
+
+2006-03-20  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 272307
+
+	* camel-mime-utils.c (header_decode_mailbox): Do not decode_lwsp
+	if there is a space in mail id, just append it.  Also do not
+	truncate address if addr is not NULL.
+
+2006-03-20  Srinivasa Ragavan  <sragavan@novell.com>
+
+	* camel-gpg-context.c (gpg_ctx_parse_status): Added flag to ask
+	for pass phrase.
+
+	* camel-session.h: Added the flag for passphrase.
+
+2006-03-20  Srinivasa Ragavan  <sragavan@novell.com>
+
+	* providers/groupwise/camel-groupwise-store.c:
+	(groupwise_build_folder_info): Added flags for the system folders.
+
+2006-02-21  Rohini S  <srohini@novell.com>
+
+	** See bug 318697
+
+	* camel-url-scanner.c (camel_url_addrspec_start): conditions
+	modified to parse only valid mailto links
+
+2006-02-21  Rohini S  <srohini@novell.com>
+ 
+ 	** Fixes bug #328322
+ 
+	* camel-mime-filter-tohtml.c: add new pattern for sftp urls.
+ 
+2006-02-21  Rohini S  <srohini@novell.com>
+ 
+	* camel-url-scanner.c (camel_url_web_end): Modified to accept urls 
+ 	with ./
+ 	Fixes bug#256142
+ 
+2006-02-16  Parthasarathi Susarla <sparthasarathi@novell.com>
+
+	* camel-disco-diary.c (camel_disco_diary_log): proceed only if
+	diary is a valid pointer
+
+2006-02-13  Rohini S  <srohini@novell.com>
+
+	**See bug 328384
+
+	* camel-url-scanner.c (camel_url_addrspec_start): modified to
+	remove all invalid characters in the beginning of a email address
+
+2006-02-02  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug 328481
+
+	* camel-gpg-context.c (gpg_ctx_parse_status): do not search if the
+	gpg->need_id is NULL
+
+2006-02-02  Parthasarathi Susarla <sparthasarathi@novell.com>
+
+	* camel-object.c (object_finalise):
+	(camel_message_info_free): decrement Ref count properly
+
+2006-02-02  Tor Lillqvist  <tml@novell.com>
+
+	* camel-net-utils.h
+	* camel-net-utils.c: Make it compile on Win32 also without
+	getaddrinfo() (with NEED_ADDRINFO).
+
+2006-01-25  Not Zed  <NotZed@Ximian.com>
+ 
+	* camel-folder-search.c (search_match_threads): add new
+ 	match-thread type "unreplied", matches messages that are unreplied
+ 	to. 
+	Committed to head on behaf of Notzed
+ 
+2006-01-23  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-mime-utils.c (camel_content_type_unref):
+	Id the content-type refcount is <1 then free it and
+	assign it to NULL
+
+2006-01-17  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	* camel-service.c (camel_service_disconnect):
+	set the service-status to CAMEL_SERVICE_DISCONNECTED
+
+2006-01-10  Simon Zheng  <simon.zheng@sun.com>
+
+	* camel-file-utils.h: 
+	* camel-file-utils.c: Delete function camel_mkdir().
+
+	* camel-data-cache.c (camel_data_cache_new):
+	* camel-object.c (camel_object_state_write):
+	* camel-session.c (get_storage_path):
+	* camel-uid-cache.c (camel_uid_cache_new):
+	* providers/imap/camel-imap-folder.c (camel_imap_folder_new):
+	* providers/imap4/camel-imap4-folder.c (camel_imap4_folder_new):
+	* providers/imapp/camel-imapp-folder.c (camel_imapp_folder_new):
+	* providers/local/camel-local-store.c (get_folder):
+	* providers/local/camel-mbox-store.c (get_folder):
+	(create_folder):
+	(rename_folder):
+	* providers/local/camel-spool-store.c (spool_get_meta_path):
+	* providers/nntp/camel-nntp-folder.c (camel_nntp_folder_new):
+	Because of deletion of camel_mkdir(), all the callers use
+	e_util_mkdir_hier() instead and add the related header file 
+	<libedataserver/e-data-server-util.h>.
+
+	* camel-debug.c: 
+	* camel-win32.c: As file e-util.h is renamed,
+	replace "libedataserver/e-util.h" as
+	"libedataserver/e-data-server-util.h".
+
+2006-01-05  Kjartan Maraas  <kmaraas@gnome.org>
+
+	* camel-session.c (camel_session_get_network_state): Return stuff
+	from this non-void function.
+
+	* providers/imap4/camel-imap4-store.c (connect_to_server): Move
+	some vars inside #ifdef HAVE_SSL
+
+	* providers/local/camel-local-store.c (xrename): Use NULL not 0 as
+	the last parameter to g_strconcat().
+
+2006-01-04  Tor Lillqvist  <tml@novell.com>
+
+	* camel-win32.c (setup): Modify calls to e_util_replace_prefix()
+	according to its changed interface.
+
+	* Makefile.am (INCLUDES): Need to pass also E_DATA_SERVER_PREFIX
+	to the compilation because of the above.
+
+2005-12-22  Shreyas Srinivasan  <sshreyas@novell.com>
+
+	* Network Manager Support
+	
+	* camel-session.[h,c]: Add a gboolean network_state which the
+	shell uses to set the current network state.  Add new api's
+	camel_session_get_network_state and
+	camel_session_set_network_state.
+	
+	* camel-offline-folder.c: If network down then dont sync folders
+	while going offline and send clean as FALSE to
+	camel_service_disconnect.
+	
+	* camel-disco-folder.c: If network down then dont sync folders
+	while going offline and send clean as FALSE to
+	camel_service_disconnect.
+
+2005-12-13  Tor Lillqvist  <tml@novell.com>
+
+	* camel-filter-driver.c: Use gstdio wrappers. Use
+	g_filename_to_uri().
+
+	* camel-filter-driver.c (pipe_to_system)
+	* camel-filter-search.c (run_command): Use
+	g_spawn_async_with_pipes() instead of manual fork/dup/exec dance.
+
+	* camel-folder.c
+	* camel-junk-plugin.c: Just cosmetics.
+
+	* camel-lock.c: Use g_usleep() instead of sleep() which isn't
+	available (as such) on Win32. No locking implementation for Win32
+	yet (none of USE_DOT, USE_FCNTL or USE_FLOCK get defined on
+	Win32), I wonder whether it is necessary t ohave one? Is locking
+	used to guard against several threads in Evolution (or Evolution
+	and the E-D-S or E-E processes) accessing the same files
+	simultaneously, not just against other apps accessing them while
+	Evolution is?
+
+	* camel-object.c: Use gstdio wrappers. Use binary mode when
+	opening files. Use g_path_get_dirname().
+
+	Use a separate have_owner boolean flag field to indicate whether
+	the pthread_t owner field is valid in the _CamelObjectBagKey
+	struct. There is no portable way to check a pthread_t for
+	uninitializedness. Remove the E_THREAD_NONE magic constant. Use
+	pthread_equal() to compare pthread_t values.
+
+	* camel-tcp-stream.h: Include Winsock headers on Win32.
+
+	* camel-tcp-stream-raw.h (struct _CamelTcpStreamRaw): There is no
+	way to find out a socket's blockingness state on Win32, so keep
+	the state in a separate flag field on Win32.
+
+	* camel-tcp-stream-raw.c: Use socket API wrapper macros to hide
+	Unix/Winsock differences. Use camel_read_socket() and
+	camel_write_socket() to read and write from sockets. Use
+	ioctlsocket(FIONBIO) to set and clean nonblocking mode on Win32.
+	
+	* camel-tcp-stream-ssl.c (set_errno): Most of the network related
+	errno values don't exist in the Win32 C library, so use ifdef
+	around those cases.
+	(stream_read, stream_write): Check PR_GetError() instead of errno.
+	No ETIMEDOUT on Win32, so use the catch-all EIO instead.
+	(cert_fingerprint): The fingerprint is used as a file name, and
+	there can't be colons in file names on Win32, so use underscore
+	instead.
+	(camel_certdb_nss_cert_get, camel_certdb_nss_cert_set): Use gstdio
+	wrappers. Use g_get_home_dir() on Win32 instead of $HOME.
+
+2005-12-11  Tor Lillqvist  <tml@novell.com>
+
+	* camel-gpg-context.c: Use gstdio wrappers. Ifdef out
+	implementation on Win32 for now. Will have to come back to this
+	later. Probably running a gpg subprocess is not the right way to
+	do this on Windows.
+	(swrite): Use g_get_tmp_dir(), g_build_filename(), g_mkstemp().
+
+	* camel-net-utils.c (gai_strerror): Implement gai_strerror() for
+	Win32.
+	(cs_waitinfo): Use select() instead of poll() on Win32. Use
+	g_win32_error_message(WSAGetLastError()) for socket API error
+	messages on Win32.
+
+	* camel-net-utils.h: Include the Winsock2 headers on Win3.
+
+	* camel-session.c (get_storage_path): No need to have ifdefs for
+	g_access() here, camel-private #defines g_access as access when
+	builing against an older GLib.
+
 2005-12-07  Jeff Cai <jeff.cai@sun.com>
 
-        * camel-vee-folder.c: (vee_search_by_expression),
-        (vee_search_by_uids):
-        if search expression of a vfolder is null, make it an empty string.
-        Fix #323433
+	* camel-vee-folder.c (vee_search_by_expression),
+	(vee_search_by_uids): if search expression of a vfolder is null,
+	make it an empty string.  Fix #323433
+	
+2005-12-08  Tor Lillqvist  <tml@novell.com>
 
-2005-12-01 Shi Pu <shi.pu@sun.com>
+	* camel-file-utils.c: Win32 port: Include <winsock2.h>. Use
+	g_htonl() and g_ntohl().
+	(camel_mkdir): Implement using g_mkdir_with_parents() when
+	compiling against GLib 2.8 or later.
+	(camel_file_util_safe_filename): Need to encode more unsafe chars
+	on Win32.
+	(camel_read, camel_write): Not cancellable on Win32. But then
+	these functions should be used only with regular files, not
+	sockets.
+	(camel_read_socket, camel_write_socket): New functions, to be used
+	for sockets. On Unix just call camel_read() and camel_write(). On
+	Win32 use recv() and write(). read() and write() can not be used
+	on sockets in Windows. read() and write() are in the C library,
+	which knows nothing about sockets.
+	(camel_file_util_savename): Clarify doc comment. Use
+	g_path_get_dirname() instead of looking for '/'. Use
+	g_path_get_basename(), and g_build_filename() to construct the
+	savename.
 
-	** See bug #321139 
+2005-12-06  Tor Lillqvist  <tml@novell.com>
 
+	* camel-index.c
+	* camel-mime-filter-basic.c
+	* camel-mime-filter-charset.c
+	* camel-mime-filter-from.c
+	* camel-mime-filter-index.c
+	* camel-mime-filter-windows.c
+	* camel-mime-filter.c
+	* camel-mime-part-utils.c
+	* camel-multipart-encrypted.c
+	* camel-multipart-signed.c
+	* camel-multipart.c
+	* camel-offline-folder.c
+	* camel-offline-store.c
+	* camel-operation.c
+	* camel-sasl-anonymous.c
+	* camel-sasl-cram-md5.c
+	* camel-sasl-digest-md5.c
+	* camel-sasl-kerberos4.c
+	* camel-sasl-login.c
+	* camel-sasl-ntlm.c
+	* camel-sasl-plain.c
+	* camel-sasl.c
+	* camel-search-private.c
+	* camel-service.c
+	* camel-smime-context.c
+	* camel-store.c
+	* camel-stream-buffer.c
+	* camel-stream-filter.c
+	* camel-stream-process.c
+	* camel-stream.c
+	* camel-transport.c
+	* camel-url-scanner.c
+	* camel-vee-folder.c
+	* camel-vee-summary.c
+	* camel-vtrash-folder.c
+	* camel.c: Unify header inclusion order and style purely for
+	cosmetic reasons.
+	
+2005-12-02  Shi Pu <shi.pu@sun.com>
+
+	** See bug #321139
+
 	* camel-exception.c: (camel_exception_get_description):
 	Don't return NULL.
 
+2005-12-01  Tor Lillqvist  <tml@novell.com>
+
+	* camel-private.h: If building against a GLib older than 2.8, map
+	those gstdio wrappers that were introduced only in 2.8 to their
+	normal counterparts here. (When building for Win32, we require
+	GLib and GTK+ 2.8, so this is for Unix only.)
+
+2005-12-01  Chenthill Palanisamy  <pchenthill@novell.com>
+
+	* camel-data-cache.c:
+	* camel-session.c: (get_storage_path):Use the functions
+	defined in glib -2.8 only for win32 as it fails to build
+	for OS which has glib 2.4.
+
+2005-12-01  Tor Lillqvist  <tml@novell.com>
+
+	* camel-mime-message.c: Add gmtime_r() implementation (a simple
+	macro) for Win32.
+
+	* camel-win32.c: Drop the realpath() implementation. realpath() is
+	only used in one place in providers/local/camel-local-folder.c,
+	and it's better to just enclose that code snippet (which isn't
+	needed on Win32 anyway) in an ifdef.
+
+	* camel-private.h: Drop the realpath() declaration from
+	here. Remove the S_ISLNK() and lstat() dummy definitions. They are
+	also used only in the place mentioned above.
+
+2005-12-01  Chenthill Palanisamy  <pchenthill@novell.com>
+
+	reviewed by Srinivasa Ragavan  <sragavan@novell.com> 
+
+	* camel-private.h: Declare the functions _camel_get_*
+	only for win32 as camel-win32.c is inlcuded only for
+	win32. Fixes a build break.
+
+2005-11-30  Tor Lillqvist  <tml@novell.com>
+
+	* camel-file-utils.h: Define O_BINARY as 0 on Unix. Add
+	declarations for camel_read_socket() and camel_write_socket(). (In
+	a not yet committed addition to camel-file-utils.c.)
+
+	* camel-block-file.c
+	* camel-certdb.c
+	* camel-data-cache.c
+	* camel-disco-diary.c
+	* camel-folder-summary.c
+	* camel-mime-parser.c
+	* camel-offline-journal.c
+	* camel-provider.c
+	* camel-session.c
+	* camel-store-summary.c
+	* camel-stream-fs.c
+	* camel-text-index.c
+	* camel-uid-cache.c
+	* camel-vee-store.c: Use gstdio wrappers for full non-ASCII
+	filename support on Windows.
+
+	* camel-block-file.c (key_file_use)
+	* camel-certdb.c (camel_certdb_save)
+	* camel-disco-diary.c (camel_disco_diary_new)
+	* camel-folder-summary.c (camel_folder_summary_load)
+	* camel-offline-journal.c (camel_offline_journal_construct)
+	* camel-store-summary.c (camel_store_summary_load,
+	camel_store_summary_save, camel_store_summary_header_load)
+	* camel-stream-fs.c (camel_stream_fs_new_with_name)
+	* camel-text-index.c (dump_raw)
+	* camel-uid-cache.c (camel_uid_cache_new, camel_uid_cache_save):
+	Open file in binary mode.
+
+	* camel-data-cache.c (data_cache_expire)
+	* camel-provider.c (camel_provider_init): Use GDir instead of
+	dirent API for portability and full non-ASCII filename support on
+	Windows.
+	
+	* camel-folder-summary.c (camel_folder_summary_load): On Win32
+	unlink destination before attempting a rename.
+
+	* camel-mime-parser.c: Drop unused includes. Use
+	g_ascii_strcasecmp() instead of strcasecmp() for well-definedness,
+	and the other string being compared is an ASCII literal anyway.
+
+	* camel-provider.c (camel_provider_init) Use G_MODULE_SUFFIX
+	instead of hardcoding .so.
+
+	* camel-session.c (session_thread_wait): Use g_usleep() instead of
+	usleep() for portability.
+
+	* camel-utf8.c: Use g_htons() and g_ntohs() instead of htons() and
+	ntohs() for portability.
+	
+2005-11-25  Tor Lillqvist  <tml@novell.com>
+
+	* camel-private.h: Add declaration for our Win32-only fsync() and
+	realpath() implementations. Define S_ISLNK() as 0 and lstat() as
+	stat().
+	(realpath): Use gstdio wrappers.
+
+	* camel-win32.c (_camel_get_localedir, _camel_get_libexecdir,
+	_camel_get_providerdir): Run-time path construction
+	machinery. Maybe these should just be in libedataserver instead,
+	like _libedataserver_get_extensiondir() etc.
+
 2005-11-18  Jeff Cai  <jeff.cai@sun.com>
 
 	* camel-disco-store.c: (disco_connect):
 	If no diary is created, no need to do resync.
 
-2005-10-28  Parthasarathi Susarla <sparthasarathi@novell.com>
+2005-11-15  Ross Burton  <ross@burtonini.com>
 
+	* camel-provider.c:
+	Use lazy bindings (#321515)
+
+2005-11-15  Harish Krishnaswamy  <kharish@novell.com>
+
+	* providers/Makefile.am: Add hula to SUBDIRS.
+
+2005-10-23  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
 	** See bug #218177
 
 	* camel-vtrash-folder.c: (vtrash_remove_folder):
-	  check if mi->real exists, continue otherwise.
-
+	check if mi->real exists, continue otherwise. 
+	
 2005-10-11 Vivek Jain <jvivek@novell.com>
 
 	** See bug #318508
@@ -31,19 +550,44 @@
 	* camel-folder-summary.c : (camel_folder_summary_info_new_from_parser)
 	Null check for p->index before using it.
 
+2005-09-22  Parthasarathi Susarla <sparthasarathi@novell.com>
+	
+	** See bug #316287
+	
+	* camel-mime-filter-bestenc.c:(camel_mime_filter_bestenc_get_best_encode):
+	Remove the last return statement that can never be reached.
+	
 2005-09-15  Sankar P  <psankar@novell.com>
 
 	* camel-store.h:
 	Defined new macro CAMEL_FOLDER_TYPE_SENT for identifying sent-folder.
 	Needed for fixing #257321
 	
+2005-09-15  Tor Lillqvist  <tml@novell.com>
+
+	* broken-date-parser.c (get_wday, get_month)
+	* camel-folder-search.c (check_header)
+	* camel-http-stream.c (http_connect, http_get_statuscode)
+	* camel-mime-filter-enriched.c (param_parse_colour, enriched_to_html)
+	* camel-mime-part.c
+	* camel-mime-utils.c
+	* camel-movemail.c
+	* camel-sasl-popb4smtp.c
+	* camel-string-utils.c
+	* camel-url.c: Use g_ascii_str(n)casecmp() instead of
+	str(n)casecmp(). The strings we are comparing in these cases
+	should be just ASCII anyway, so spell it out that we really do
+	need ASCII casefolding only.
+
+	* camel-debug.c: Use e_util_pthread_id() to identify threads.
+
 2005-09-12  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
 	** See bug #314574
 
 	* camel-lock-client.c: (camel_lock_helper_init):
 	remove an spurious ','.
-
+	
 2005-09-01  Parthasarathi Susarla <sparthasarathi@novell.com>
 	
 	* camel-lock-client.c: (camel_lock_helper_init):
@@ -1064,29 +1608,30 @@
 	once connector plugin is made external.
 
 2005-01-10  Parthasarathi Susarla <sparthasarathi@novell.com>
-	
+
 	* providers/groupwise/camel-groupwise-folder.c
-	  (groupwise_folder_get_message),
-	  (groupwise_refresh_info): included default and notification
-	  in the view list for e_gw_connection_get_item.
+	(groupwise_folder_get_message),
+	(groupwise_refresh_info): included default and notification in
+	the view list for e_gw_connection_get_item.
 	
 	* providers/groupwise/camel-groupwise-store.c
-	  (groupwise_get_folder_online):included default and notification
-	  in the view list for e_gw_connection_get_items.
+	(groupwise_get_folder_online):included default and notification
+	in the view list for e_gw_connection_get_items.
 	
 	* providers/groupwis/camel-groupwise-transport.[ch]
-	  (groupwise_send_to): sets send options in EGwItem by parsing the
-	  camelmimemessage for send-option headers
+	(groupwise_send_to): sets send options in EGwItem by parsing the
+	camelmimemessage for send-option headers
 
 2005-01-10  Parthasarathi Susarla <sparthasarathi@novell.com>
 
 	* providers/groupwise/camel-groupwise-store-summary.[ch]:
-	  implements the CamelStoreSummary Class providing support
-	  for store summary for the soap provider.
+	implements the CamelStoreSummary Class providing support
+	for store summary for the soap provider.
+
 	* providers/groupwise/camel-groupwise-store.c
-	  (groupwise_get_folder_info_online): saves the store summary
-	  after building folder info.
-	  
+	(groupwise_get_folder_info_online): saves the store summary
+	after building folder info.
+  
 2005-01-07  Jeffrey Stedfast  <fejj@novell.com>
 
 	* providers/imap4/camel-imap4-store.c (imap4_connect): Same as
@@ -1110,10 +1655,10 @@
 	(imap4_transfer_messages_to): Same.
 
 2005-01-07  Parthasarathi Susarla <sparthasarathi@novell.com>
-	
+
 	* providers/groupwise/camel-groupwise-transport.c
-	  (groupwise_send_to): fixed the problem of the mail
-	   message (body) being treated as an attachment
+	(groupwise_send_to): fixed the problem of the mail message (body)
+	being treated as an attachment
 
 2005-01-07  JP Rosevear  <jpr@novell.com>
 
@@ -1152,42 +1697,43 @@
 2005-01-06 Parthasarathi Susarla <sparthasarathi@novell.com>
 
 	* providers/groupwise/camel-groupwise-store.[ch]
-	  (groupwise_get_folder_info_online): update the total and
-	   unread mail count from soap response
-	  (groupwise_rename_folder): fixed problems in renaming 
-	   groupwise folders
-	  (storage_path_lookup): returns the storage path for the
-	   groupwise account
+	(groupwise_get_folder_info_online): update the total and unread
+	mail count from soap response
+	(groupwise_rename_folder): fixed problems in renaming groupwise
+	folders
+	(storage_path_lookup): returns the storage path for the groupwise
+	account
+
 	* providers/groupwise/camel-groupwise-folder.c
-	  (groupwise_folder_get_message): support for shared folder
-	   notification type. displaying the itip control for 
-	   appoinments.
-	  (groupwise_folder_rename): support function for renaming
-	   cache and summary when a groupwise folder is renamed
-	  (groupwise_transfer_online): function for copying/moving
-	   messages between folders
-	  (convert_to_calendar): function to populate data for
-	   displaying appointments by itip control
+	(groupwise_folder_get_message): support for shared folder
+	notification type. displaying the itip control for appoinments.
+	(groupwise_folder_rename): support function for renaming cache and
+	summary when a groupwise folder is renamed
+	(groupwise_transfer_online): function for copying/moving messages
+	between folders
+	(convert_to_calendar): function to populate data for displaying
+	appointments by itip control
+
 	* providers/groupwise/camel-groupwise-transport.c
-	   (groupwise_send_to): support for sending attachments
-	   
+	(groupwise_send_to): support for sending attachments
+
 2005-01-04  Sivaiah Nallagatla     <snallagatla@novell.com>
 
 	* providers/groupwise/camel-groupwise-store.c
-	(groupwise_create_folder) (groupwise_delete_folder) 
-	(groupwise_rename_folder) : prevent these operations in 
-	offline mode 
+	(groupwise_create_folder, groupwise_delete_folder),
+	(groupwise_rename_folder): prevent these operations in offline
+	mode
 
 2005-01-04  Parthasarathi Susarla <sparthasarathi@novell.com>
 
 	* providers/groupwise/camel-groupwise-store.c
-	  (groupwise_store_construct): initialise the store summary.
+	(groupwise_store_construct): initialise the store summary.
 
 2005-01-04  Parthasarathi Susarla <sparthasarathi@novell.com>
 
-	 * providers/groupwise/camel-groupwise-transport.c
-	  (groupwise_send_to): freeing the recipient list and assigning
-	   to NULL, which was causing a crash while sending mails.
+	* providers/groupwise/camel-groupwise-transport.c
+	(groupwise_send_to): freeing the recipient list and assigning to
+	NULL, which was causing a crash while sending mails.
 
 2004-12-31  JP Rosevear  <jpr@novell.com>
 
@@ -1217,6 +1763,7 @@
 	  Added the file which was missed out in the previous commit.
 
 2004-12-23  Parthasarathi Susarla <sparthasarathi@novell.com>
+
 	* providers/groupwise/camel-groupwise-store.[ch]
 	* providers/groupwise/camel-groupwise-transport.[ch]
 	* providers/groupwise/camel-groupwise-utils.[ch]
@@ -1240,23 +1787,23 @@
 
 2004-12-20  David Mosberger-Tang  <David.Mosberger@acm.org>
 
-        * camel-mime-parser.c: Include "libedataserver/e-memory.h".
-        (STRUCT_ALIGN): Remove.
-        (MemPoolNode): Likewise.
-        (MemPoolThresholdNode): Likewise.
-        (MemPool): Likewise.
-        (mempool_new): Likewise.
-        (mempool_alloc): Likewise.
-        (mempool_flush): Likewise.
-        (mempool_free): Likewise.
-        (struct _header_scan_stack): Change type of "pool" from MemPool to
-        EMemPool.
-        (folder_pull_part): Call e_mempool_destroy() instead of
-        mempool_free().
-        (header_append_mempool): Call e_mempool_alloc() instead of
-        mempool_alloc().
-        (folder_scan_header): Call e_mempool_new() instead of
-        mempool_new().
+	* camel-mime-parser.c: Include "libedataserver/e-memory.h".
+	(STRUCT_ALIGN): Remove.
+	(MemPoolNode): Likewise.
+	(MemPoolThresholdNode): Likewise.
+	(MemPool): Likewise.
+	(mempool_new): Likewise.
+	(mempool_alloc): Likewise.
+	(mempool_flush): Likewise.
+	(mempool_free): Likewise.
+	(struct _header_scan_stack): Change type of "pool" from MemPool to
+	EMemPool.
+	(folder_pull_part): Call e_mempool_destroy() instead of
+	mempool_free().
+	(header_append_mempool): Call e_mempool_alloc() instead of
+	mempool_alloc().
+	(folder_scan_header): Call e_mempool_new() instead of
+	mempool_new().
 
 2004-12-20  Not Zed  <NotZed@Ximian.com>
 
Index: camel/camel-mime-filter-linewrap.c
===================================================================
--- camel/camel-mime-filter-linewrap.c	(revision 444)
+++ camel/camel-mime-filter-linewrap.c	(working copy)
@@ -71,7 +71,7 @@
 	char **out, size_t *outlen, size_t *outprespace)
 {
 	CamelMimeFilterLinewrap *linewrap = (CamelMimeFilterLinewrap *)f;
-	char *inend, *last, *p, *q;
+	char *inend, *p, *q;
 	int nchars = linewrap->nchars;
 	
 	/* we'll be adding chars here so we need a bigger buffer */
@@ -83,12 +83,9 @@
 	
 	while (p < inend) {
 		if (*p == '\n') {
-			last = q;
 			*q++ = *p++;
 			nchars = 0;
 		} else if (isspace (*p)) {
-			last = q;
-			
 			if (nchars >= linewrap->wrap_len) {
 				*q++ = '\n';
 				p++;
Index: camel/camel-mime-filter-bestenc.c
===================================================================
--- camel/camel-mime-filter-bestenc.c	(revision 444)
+++ camel/camel-mime-filter-bestenc.c	(working copy)
@@ -270,7 +270,6 @@
 			return bestenc;
 	}
 
-	return CAMEL_TRANSFER_ENCODING_DEFAULT;
 }
 
 
Index: camel/camel-smime-context.c
===================================================================
--- camel/camel-smime-context.c	(revision 444)
+++ camel/camel-smime-context.c	(working copy)
@@ -43,20 +43,18 @@
 
 #include <errno.h>
 
-#include <camel/camel-exception.h>
-#include <camel/camel-stream-mem.h>
-#include <camel/camel-data-wrapper.h>
-
-#include <camel/camel-mime-part.h>
-#include <camel/camel-multipart-signed.h>
-#include <camel/camel-stream-fs.h>
-#include <camel/camel-stream-filter.h>
-#include <camel/camel-mime-filter-basic.h>
-#include <camel/camel-mime-filter-canon.h>
-
-#include "camel-smime-context.h"
-#include "camel-operation.h"
+#include "camel-data-wrapper.h"
+#include "camel-exception.h"
 #include "camel-i18n.h"
+#include "camel-mime-filter-basic.h"
+#include "camel-mime-filter-canon.h"
+#include "camel-mime-part.h"
+#include "camel-multipart-signed.h"
+#include "camel-operation.h"
+#include "camel-smime-context.h"
+#include "camel-stream-filter.h"
+#include "camel-stream-fs.h"
+#include "camel-stream-mem.h"
 
 #define d(x)
 
@@ -667,7 +665,7 @@
 	NSSCMSDecoderContext *dec;
 	NSSCMSMessage *cmsg;
 	CamelStreamMem *mem;
-	CamelStream *constream;
+	CamelStream *constream = NULL;
 	CamelCipherValidity *valid = NULL;
 	CamelContentType *ct;
 	const char *tmp;
Index: camel/camel-partition-table.c
===================================================================
--- camel/camel-partition-table.c	(revision 444)
+++ camel/camel-partition-table.c	(working copy)
@@ -249,13 +249,10 @@
 camel_partition_table_sync(CamelPartitionTable *cpi)
 {
 	CamelBlock *bl, *bn;
-	struct _CamelPartitionTablePrivate *p;
 	int ret = 0;
-
+	
 	CAMEL_PARTITION_TABLE_LOCK(cpi, lock);
-
-	p = cpi->priv;
-
+	
 	if (cpi->blocks) {
 		bl = (CamelBlock *)cpi->partition.head;
 		bn = bl->next;
@@ -323,7 +320,6 @@
 	CamelPartitionMapBlock *ptb;
 	CamelBlock *block, *ptblock;
 	camel_hash_t hashid;
-	camel_key_t keyid = 0;
 	int index, i;
 
 	hashid = hash_key(key);
@@ -348,8 +344,7 @@
 		if (pkb->keys[i].hashid == hashid) {
 			/* !! need to: lookup and compare string value */
 			/* get_key() if key == key ... */
-			keyid = pkb->keys[i].keyid;
-
+			
 			/* remove this key */
 			pkb->used--;
 			for (;i<pkb->used;i++) {
Index: camel/camel-disco-diary.c
===================================================================
--- camel/camel-disco-diary.c	(revision 444)
+++ camel/camel-disco-diary.c	(working copy)
@@ -29,6 +29,8 @@
 #include <stdio.h>
 #include <errno.h>
 
+#include <glib/gstdio.h>
+
 #include "camel-i18n.h"
 #include "camel-disco-diary.h"
 #include "camel-disco-folder.h"
@@ -124,7 +126,7 @@
 	d(printf("diary log: %s\n", diary->file?"ok":"no file!"));
 
 	/* You may already be a loser. */
-	if (!diary->file)
+	if (!diary && !diary->file)
 		return;
 
 	status = camel_file_util_encode_uint32 (diary->file, action);
@@ -429,7 +431,7 @@
 	   So we must seek ourselves.
 	*/
 
-	diary->file = fopen (filename, "a+");
+	diary->file = g_fopen (filename, "a+b");
 	if (!diary->file) {
 		camel_object_unref (diary);
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
Index: camel/camel-movemail.c
===================================================================
--- camel/camel-movemail.c	(revision 444)
+++ camel/camel-movemail.c	(working copy)
@@ -410,7 +410,7 @@
         iv[3].iov_len = 1;
 
         while (header) {
-		if (strcasecmp(header->name, "Content-Length")) {
+		if (g_ascii_strcasecmp(header->name, "Content-Length")) {
 			iv[0].iov_base = header->name;
 			iv[0].iov_len = strlen(header->name);
 			iv[2].iov_base = header->value;
Index: camel/camel-stream-filter.c
===================================================================
--- camel/camel-stream-filter.c	(revision 444)
+++ camel/camel-stream-filter.c	(working copy)
@@ -26,6 +26,7 @@
 
 #include <stdio.h>
 #include <string.h>
+
 #include "camel-stream-filter.h"
 
 #define d(x) 
@@ -50,8 +51,8 @@
 	char *filtered;		/* the filtered data */
 	size_t filteredlen;
 
-	int last_was_read:1;	/* was the last op read or write? */
-	int flushed:1;          /* were the filters flushed? */
+	guint last_was_read:1;	/* was the last op read or write? */
+	guint flushed:1;        /* were the filters flushed? */
 };
 
 #define READ_PAD (128)		/* bytes padded before buffer */
Index: camel/camel-tcp-stream.h
===================================================================
--- camel/camel-tcp-stream.h	(revision 444)
+++ camel/camel-tcp-stream.h	(working copy)
@@ -30,11 +30,18 @@
 #pragma }
 #endif /* __cplusplus }*/
 
+#include <glibconfig.h>
+
+#ifndef G_OS_WIN32
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <netinet/tcp.h>
 #include <netdb.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
 #include <unistd.h>
 
 #include <camel/camel-stream.h>
Index: camel/camel-net-utils.c
===================================================================
--- camel/camel-net-utils.c	(revision 444)
+++ camel/camel-net-utils.c	(working copy)
@@ -25,22 +25,51 @@
 #include <config.h>
 #endif
 
+#include <glib.h>
+
+#ifndef G_OS_WIN32
 #include <sys/poll.h>
+#endif
 #include <pthread.h>
 #include <stdio.h>
 #include <errno.h>
 
-#include <glib.h>
+#include "libedataserver/e-msgport.h"
 
+#include "camel-exception.h"
 #include "camel-i18n.h"
+#include "camel-net-utils.h"
 #include "camel-operation.h"
-#include "camel-exception.h"
-#include "camel-net-utils.h"
 
-#include "libedataserver/e-msgport.h"
-
 #define d(x)
 
+#ifdef G_OS_WIN32
+
+typedef short in_port_t;
+
+#undef gai_strerror
+#define gai_strerror my_gai_strerror
+
+/* gai_strerror() is implemented as an inline function in Microsoft's
+ * SDK, but mingw lacks that. So implement here. The EAI_* errors can
+ * be handled with the normal FormatMessage() API,
+ * i.e. g_win32_error_message().
+ */
+
+static const char *
+gai_strerror (int error_code)
+{
+	gchar *msg = g_win32_error_message (error_code);
+	GQuark quark = g_quark_from_string (msg);
+	const gchar *retval = g_quark_to_string (quark);
+
+	g_free (msg);
+
+	return retval;
+}
+
+#endif
+
 /* gethostbyname emulation code for emulating getaddrinfo code ...
 
 This should probably go away */
@@ -407,7 +436,7 @@
 	g_free(msg);
 }
 
-/* returns -1 if cancelled */
+/* returns -1 if we didn't wait for reply from thread */
 static int
 cs_waitinfo(void *(worker)(void *), struct _addrinfo_msg *msg, const char *error, CamelException *ex)
 {
@@ -424,8 +453,9 @@
 	reply_port = msg->msg.reply_port = e_msgport_new();
 	fd = e_msgport_fd(msg->msg.reply_port);
 	if ((err = pthread_create(&id, NULL, worker, msg)) == 0) {
+		int status;
+#ifndef G_OS_WIN32
 		struct pollfd polls[2];
-		int status;
 
 		polls[0].fd = fd;
 		polls[0].events = POLLIN;
@@ -438,17 +468,38 @@
 			polls[1].revents = 0;
 			status = poll(polls, 2, -1);
 		} while (status == -1 && errno == EINTR);
+#else
+		fd_set read_set;
 
-		if (status == -1 || (polls[1].revents & POLLIN)) {
+		FD_ZERO(&read_set);
+		FD_SET(fd, &read_set);
+		FD_SET(cancel_fd, &read_set);
+
+		status = select(MAX(fd, cancel_fd) + 1, &read_set, NULL, NULL, NULL);
+#endif
+
+		if (status == -1 ||
+#ifndef G_OS_WIN32
+		    (polls[1].revents & POLLIN)
+#else
+		    FD_ISSET (cancel_fd, &read_set)
+#endif
+						   ) {
 			if (status == -1)
-				camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM, "%s: %s", error, g_strerror(errno));
+				camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM, "%s: %s", error,
+#ifndef G_OS_WIN32
+						     g_strerror(errno)
+#else
+						     g_win32_error_message (WSAGetLastError ())
+#endif
+						     );
 			else
-				camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled"));
+				camel_exception_setv(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled"));
 			
 			/* We cancel so if the thread impl is decent it causes immediate exit.
 			   We detach so we dont need to wait for it to exit if it isn't.
 			   We check the reply port incase we had a reply in the mean time, which we free later */
-			d(printf("Cancelling lookup thread and leaving it\n"));
+			d(printf("Canceling lookup thread and leaving it\n"));
 			msg->cancelled = 1;
 			pthread_detach(id);
 			pthread_cancel(id);
@@ -605,7 +656,7 @@
 	g_return_val_if_fail(name != NULL, NULL);
 	
 	if (camel_operation_cancel_check(NULL)) {
-		camel_exception_set(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled"));
+		camel_exception_set(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled"));
 		return NULL;
 	}
 
@@ -736,7 +787,7 @@
 	int result;
 
 	if (camel_operation_cancel_check(NULL)) {
-		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled"));
+		camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled"));
 		return -1;
 	}
 
@@ -765,12 +816,13 @@
 	if ((result = msg->result) != 0)
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM, _("Name lookup failed: %s"),
 				      gai_strerror (result));
+	else {
+		if (host)
+			*host = g_strdup(msg->host);
+		if (serv)
+			*serv = g_strdup(msg->serv);
+	}
 
-	if (host)
-		*host = g_strdup(msg->host);
-	if (serv)
-		*serv = g_strdup(msg->serv);
-
 	g_free(msg->host);
 	g_free(msg->serv);
 	g_free(msg);
Index: camel/camel-lock.c
===================================================================
--- camel/camel-lock.c	(revision 444)
+++ camel/camel-lock.c	(working copy)
@@ -19,9 +19,7 @@
  * USA
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -51,7 +49,12 @@
 #endif
 
 #include <glib.h>
+#include <glib/gstdio.h>
 
+#ifdef G_OS_WIN32
+#include <windows.h>
+#endif
+
 #include "camel-lock.h"
 #include "camel-i18n.h"
 
@@ -138,7 +141,7 @@
 
 		/* check for stale lock, kill it */
 		if (stat(lock, &st) == 0) {
-			time_t now = time(0);
+			time_t now = time (NULL);
 			(printf("There is an existing lock %ld seconds old\n", now-st.st_ctime));
 			if (st.st_ctime < now - CAMEL_LOCK_DOT_STALE) {
 				d(printf("Removing it now\n"));
@@ -312,7 +315,7 @@
 
 	while (retry < CAMEL_LOCK_RETRY) {
 		if (retry > 0)
-			sleep(CAMEL_LOCK_DELAY);
+			g_usleep(CAMEL_LOCK_DELAY*1000000);
 
 		if (camel_lock_fcntl(fd, type, ex) == 0) {
 			if (camel_lock_flock(fd, type, ex) == 0) {
@@ -371,7 +374,7 @@
 
 	if (camel_lock_fcntl(fd1, CAMEL_LOCK_WRITE, ex) == 0) {
 		printf("got fcntl write lock once\n");
-		sleep(5);
+		g_usleep(5000000);
 		if (camel_lock_fcntl(fd2, CAMEL_LOCK_WRITE, ex) == 0) {
 			printf("got fcntl write lock twice!\n");
 		} else {
@@ -395,7 +398,7 @@
 
 	if (camel_lock_fcntl(fd1, CAMEL_LOCK_READ, ex) == 0) {
 		printf("got fcntl read lock once\n");
-		sleep(5);
+		g_usleep(5000000);
 		if (camel_lock_fcntl(fd2, CAMEL_LOCK_WRITE, ex) == 0) {
 			printf("got fcntl write lock too?!\n");
 		} else {
Index: camel/camel-net-utils.h
===================================================================
--- camel/camel-net-utils.h	(revision 444)
+++ camel/camel-net-utils.h	(working copy)
@@ -29,11 +29,18 @@
 #endif /* __cplusplus */
 
 #include <sys/types.h>
+
+#ifndef _WIN32
 #include <sys/socket.h>
 #include <netdb.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
 
 struct _CamelException;
 
+#ifndef _WIN32
 #ifdef NEED_ADDRINFO
 /* Some of this is copied from GNU's netdb.h
 
@@ -82,6 +89,7 @@
 #define NI_NAMEREQD	8	/* Don't return numeric addresses.  */
 #define NI_DGRAM	16	/* Look up UDP service rather than TCP.  */
 #endif
+#endif
 
 struct addrinfo *camel_getaddrinfo(const char *name, const char *service,
 				   const struct addrinfo *hints, struct _CamelException *ex);
Index: camel/camel-provider.c
===================================================================
--- camel/camel-provider.c	(revision 444)
+++ camel/camel-provider.c	(working copy)
@@ -30,19 +30,22 @@
 #endif
 
 #include <sys/types.h>
-#include <dirent.h>
 #include <errno.h>
 #include <stdio.h>
 #include <string.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
 #include <gmodule.h>
 
+#include "libedataserver/e-msgport.h"
+
+#include "camel-exception.h"
+#include "camel-i18n.h"
 #include "camel-provider.h"
-#include "camel-exception.h"
 #include "camel-string-utils.h"
 #include "camel-vee-store.h"
-#include "libedataserver/e-msgport.h"
-#include "camel-i18n.h"
+#include "camel-private.h"
 
 /* table of CamelProviderModule's */
 static GHashTable *module_table;
@@ -100,8 +103,8 @@
 void
 camel_provider_init (void)
 {
-	DIR *dir;
-	struct dirent *d;
+	GDir *dir;
+	const char *entry;
 	char *p, *name, buf[80];
 	CamelProviderModule *m;
 	static int loaded = 0;
@@ -113,22 +116,22 @@
 
 	loaded = 1;
 
-	dir = opendir (CAMEL_PROVIDERDIR);
+	dir = g_dir_open (CAMEL_PROVIDERDIR, 0, NULL);
 	if (!dir) {
 		g_warning("Could not open camel provider directory (%s): %s",
 			  CAMEL_PROVIDERDIR, g_strerror (errno));
 		return;
 	}
 	
-	while ((d = readdir (dir))) {
+	while ((entry = g_dir_read_name (dir))) {
 		FILE *fp;
 		
-		p = strrchr (d->d_name, '.');
+		p = strrchr (entry, '.');
 		if (!p || strcmp (p, ".urls") != 0)
 			continue;
 		
-		name = g_strdup_printf ("%s/%s", CAMEL_PROVIDERDIR, d->d_name);
-		fp = fopen (name, "r");
+		name = g_strdup_printf ("%s/%s", CAMEL_PROVIDERDIR, entry);
+		fp = g_fopen (name, "r");
 		if (!fp) {
 			g_warning ("Could not read provider info file %s: %s",
 				   name, g_strerror (errno));
@@ -137,7 +140,7 @@
 		}
 		
 		p = strrchr (name, '.');
-		strcpy (p, ".so");
+		strcpy (p, "." G_MODULE_SUFFIX);
 
 		m = g_malloc0(sizeof(*m));
 		m->path = name;
@@ -159,7 +162,7 @@
 		fclose (fp);
 	}
 
-	closedir (dir);
+	g_dir_close (dir);
 }
 
 /**
Index: camel/camel-offline-folder.c
===================================================================
--- camel/camel-offline-folder.c	(revision 444)
+++ camel/camel-offline-folder.c	(working copy)
@@ -25,12 +25,11 @@
 #include <config.h>
 #endif
 
-#include <camel/camel-i18n.h>
-#include <camel/camel-service.h>
-#include <camel/camel-session.h>
-#include <camel/camel-operation.h>
-
+#include "camel-i18n.h"
 #include "camel-offline-folder.h"
+#include "camel-operation.h"
+#include "camel-service.h"
+#include "camel-session.h"
 
 #define CAMEL_OFFLINE_FOLDER_GET_CLASS(f) (CAMEL_OFFLINE_FOLDER_CLASS (CAMEL_OBJECT_GET_CLASS (f)))
 
Index: camel/camel-provider.h
===================================================================
--- camel/camel-provider.h	(revision 444)
+++ camel/camel-provider.h	(working copy)
@@ -219,7 +219,7 @@
 struct _CamelProviderModule {
 	char *path;
 	GSList *types;
-	int loaded:1;
+	guint loaded:1;
 };
 
 void camel_provider_init(void);
Index: camel/camel-operation.c
===================================================================
--- camel/camel-operation.c	(revision 444)
+++ camel/camel-operation.c	(working copy)
@@ -34,9 +34,10 @@
 #include <nspr.h>
 #endif
 
-#include "camel-operation.h"
 #include "libedataserver/e-msgport.h"
 
+#include "camel-operation.h"
+
 #define d(x)
 
 /* ********************************************************************** */
Index: camel/broken-date-parser.c
===================================================================
--- camel/broken-date-parser.c	(revision 444)
+++ camel/broken-date-parser.c	(working copy)
@@ -74,7 +74,7 @@
 };
 
 /* hrm, is there a library for this shit? */
-static const struct {
+static struct {
 	char *name;
 	int offset;
 } tz_offsets [] = {
@@ -193,7 +193,7 @@
 		return -1;
 	
 	for (wday = 0; wday < 7; wday++)
-		if (!strncasecmp (in, tm_days[wday], 3))
+		if (!g_ascii_strncasecmp (in, tm_days[wday], 3))
 			return wday;
 	
 	return -1;  /* unknown week day */
@@ -221,7 +221,7 @@
 		return -1;
 	
 	for (i = 0; i < 12; i++)
-		if (!strncasecmp (in, tm_months[i], 3))
+		if (!g_ascii_strncasecmp (in, tm_months[i], 3))
 			return i;
 	
 	return -1;  /* unknown month */
Index: camel/camel-sasl-ntlm.c
===================================================================
--- camel/camel-sasl-ntlm.c	(revision 444)
+++ camel/camel-sasl-ntlm.c	(working copy)
@@ -25,8 +25,8 @@
 #include <ctype.h>
 #include <string.h>
 
-#include "camel-sasl-ntlm.h"
 #include "camel-i18n.h"
+#include "camel-sasl-ntlm.h"
 
 CamelServiceAuthType camel_sasl_ntlm_authtype = {
 	N_("NTLM / SPA"),
@@ -524,13 +524,12 @@
 	l ^= Spbox[3][(work >> 16) & 0x3f];\
 	l ^= Spbox[1][(work >> 24) & 0x3f];\
 }
+
 /* Encrypt or decrypt a block of data in ECB mode */
 static void
-des(ks,block)
-guint32 ks[16][2];	/* Key schedule */
-unsigned char block[8];		/* Data block */
+des (guint32 ks[16][2], unsigned char block[8])
 {
-	guint32 left,right,work;
+	guint32 left, right, work;
 	
 	/* Read input block and place in left/right in big-endian order */
 	left = ((guint32)block[0] << 24)
@@ -663,10 +662,7 @@
  * depending on the value of "decrypt"
  */
 static void
-deskey(k,key,decrypt)
-DES_KS k;			/* Key schedule array */
-unsigned char *key;		/* 64 bits (will use only 56) */
-int decrypt;			/* 0 = encrypt, 1 = decrypt */
+deskey (DES_KS k, unsigned char *key, int decrypt)
 {
 	unsigned char pc1m[56];		/* place to modify pc1 into */
 	unsigned char pcr[56];		/* place to rotate pc1 into */
Index: camel/camel-folder.c
===================================================================
--- camel/camel-folder.c	(revision 444)
+++ camel/camel-folder.c	(working copy)
@@ -22,18 +22,17 @@
  * USA
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <string.h>
 
+#include "libedataserver/e-memory.h"
+
 #include "camel-folder.h"
 #include "camel-exception.h"
 #include "camel-store.h"
 #include "camel-mime-message.h"
 #include "camel-debug.h"
-#include "libedataserver/e-memory.h"
 #include "camel-operation.h"
 #include "camel-session.h"
 #include "camel-filter-driver.h"
@@ -41,7 +40,7 @@
 #include "camel-vtrash-folder.h"
 #include "camel-i18n.h"
 
-#define d(x) 
+#define d(x)
 #define w(x)
 
 extern int camel_verbose_debug;
@@ -1276,7 +1275,7 @@
 search_by_uids(CamelFolder *folder, const char *exp, GPtrArray *uids, CamelException *ex)
 {
 	camel_exception_setv (ex, CAMEL_EXCEPTION_FOLDER_INVALID,
-			      _("Unsupported operation: search by uids: for %s"),
+			      _("Unsupported operation: search by UIDs: for %s"),
 			      camel_type_to_name (CAMEL_OBJECT_GET_TYPE (folder)));
 	
 	w(g_warning ("CamelFolder::search_by_expression not implemented for "
@@ -1635,9 +1634,9 @@
 };
 
 static void
-filter_filter(CamelSession *session, CamelSessionThreadMsg *msg)
+filter_filter(CamelSession *session, CamelSessionThreadMsg *tmsg)
 {
-	struct _folder_filter_msg *m = (struct _folder_filter_msg *)msg;
+	struct _folder_filter_msg *m = (struct _folder_filter_msg *) tmsg;
 	CamelMessageInfo *info;
 	int i, status = 0;
 	CamelURL *uri;
Index: camel/camel-mime-filter-from.c
===================================================================
--- camel/camel-mime-filter-from.c	(revision 444)
+++ camel/camel-mime-filter-from.c	(working copy)
@@ -25,6 +25,7 @@
 #endif
 
 #include <string.h>
+
 #include "camel-mime-filter-from.h"
 
 #define d(x)
Index: camel/camel-file-utils.c
===================================================================
--- camel/camel-file-utils.c	(revision 444)
+++ camel/camel-file-utils.c	(working copy)
@@ -30,153 +30,136 @@
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <netinet/in.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <errno.h>
 
+#include <glib.h>
+
+#ifdef G_OS_WIN32
+#include <winsock2.h>
+#define EWOULDBLOCK EAGAIN
+#endif
+
+#include "libedataserver/e-data-server-util.h"
+
 #include "camel-file-utils.h"
 #include "camel-operation.h"
 #include "camel-url.h"
 
-#ifndef MAX
-#define MAX(a,b) ((a) > (b) ? (a) : (b))
-#endif
-
 #define IO_TIMEOUT (60*4)
 
+
 /**
- * camel_file_util_encode_uint32:
+ * camel_file_util_encode_fixed_int32:
  * @out: file to output to
  * @value: value to output
  * 
- * Utility function to save an uint32 to a file.
+ * Encode a gint32, performing no compression, but converting
+ * to network order.
  * 
  * Return value: 0 on success, -1 on error.
  **/
 int
-camel_file_util_encode_uint32 (FILE *out, guint32 value)
+camel_file_util_encode_fixed_int32 (FILE *out, gint32 value)
 {
-	int i;
+	guint32 save;
 
-	for (i = 28; i > 0; i -= 7) {
-		if (value >= (1 << i)) {
-			unsigned int c = (value >> i) & 0x7f;
-			if (fputc (c, out) == -1)
-				return -1;
-		}
-	}
-	return fputc (value | 0x80, out);
+	save = g_htonl (value);
+	if (fwrite (&save, sizeof (save), 1, out) != 1)
+		return -1;
+	return 0;
 }
 
 
 /**
- * camel_file_util_decode_uint32:
+ * camel_file_util_decode_fixed_int32:
  * @in: file to read from
  * @dest: pointer to a variable to store the value in
  * 
- * Retrieve an encoded uint32 from a file.
+ * Retrieve a gint32.
  * 
- * Return value: 0 on success, -1 on error.  @*dest will contain the
- * decoded value.
+ * Return value: 0 on success, -1 on error.
  **/
 int
-camel_file_util_decode_uint32 (FILE *in, guint32 *dest)
+camel_file_util_decode_fixed_int32 (FILE *in, gint32 *dest)
 {
-        guint32 value = 0;
-	int v;
+	guint32 save;
 
-        /* until we get the last byte, keep decoding 7 bits at a time */
-        while ( ((v = fgetc (in)) & 0x80) == 0 && v!=EOF) {
-                value |= v;
-                value <<= 7;
-        }
-	if (v == EOF) {
-		*dest = value >> 7;
+	if (fread (&save, sizeof (save), 1, in) == 1) {
+		*dest = g_ntohl (save);
+		return 0;
+	} else {
 		return -1;
 	}
-	*dest = value | (v & 0x7f);
-
-        return 0;
 }
 
 
 /**
- * camel_file_util_encode_fixed_int32:
+ * camel_file_util_encode_uint32:
  * @out: file to output to
  * @value: value to output
  * 
- * Encode a gint32, performing no compression, but converting
- * to network order.
+ * Utility function to save an uint32 to a file.
  * 
  * Return value: 0 on success, -1 on error.
  **/
 int
-camel_file_util_encode_fixed_int32 (FILE *out, gint32 value)
+camel_file_util_encode_uint32 (FILE *out, guint32 value)
 {
-	guint32 save;
-
-	save = htonl (value);
-	if (fwrite (&save, sizeof (save), 1, out) != 1)
-		return -1;
-	return 0;
+	return camel_file_util_encode_fixed_int32 (out, value);
 }
 
 
 /**
- * camel_file_util_decode_fixed_int32:
+ * camel_file_util_decode_uint32:
  * @in: file to read from
  * @dest: pointer to a variable to store the value in
  * 
- * Retrieve a gint32.
+ * Retrieve an encoded uint32 from a file.
  * 
- * Return value: 0 on success, -1 on error.
+ * Return value: 0 on success, -1 on error.  @*dest will contain the
+ * decoded value.
  **/
 int
-camel_file_util_decode_fixed_int32 (FILE *in, gint32 *dest)
+camel_file_util_decode_uint32 (FILE *in, guint32 *dest)
 {
-	guint32 save;
+	return camel_file_util_decode_fixed_int32 (in, (gint32*)dest);
+}
 
-	if (fread (&save, sizeof (save), 1, in) == 1) {
-		*dest = ntohl (save);
-		return 0;
-	} else {
-		return -1;
-	}
+
+unsigned char*
+camel_file_util_mmap_decode_uint32 (unsigned char *start, guint32 *dest, gboolean is_string)
+{
+	guint32 value = 0;
+	value = g_ntohl(get_unaligned_u32(start)); start += 4;
+	*dest = value;
+	return start;
 }
 
-#define CFU_ENCODE_T(type)						\
-int									\
-camel_file_util_encode_##type(FILE *out, type value)			\
-{									\
-	int i;								\
-									\
-	for (i = sizeof (type) - 1; i >= 0; i--) {			\
-		if (fputc((value >> (i * 8)) & 0xff, out) == -1)	\
-			return -1;					\
-	}								\
-	return 0;							\
+#define CFU_ENCODE_T(type)						  \
+int									  \
+camel_file_util_encode_##type(FILE *out, type value)			  \
+{									  \
+	return camel_file_util_encode_fixed_int32 (out, (guint32) value); \
 }
 
-#define CFU_DECODE_T(type)				\
-int							\
-camel_file_util_decode_##type(FILE *in, type *dest)	\
-{							\
-	type save = 0;					\
-	int i = sizeof(type) - 1;			\
-	int v = EOF;					\
-							\
-        while (i >= 0 && (v = fgetc (in)) != EOF) {	\
-		save |= ((type)v) << (i * 8);		\
-		i--;					\
-	}						\
-	*dest = save;					\
-	if (v == EOF)					\
-		return -1;				\
-	return 0;					\
+#define CFU_DECODE_T(type)						  \
+int									  \
+camel_file_util_decode_##type(FILE *in, type *dest)			  \
+{									  \
+	return camel_file_util_decode_fixed_int32 (in, (gint32*) dest);  \
 }
 
 
+#define MMAP_DECODE_T(type)						    \
+unsigned char*								    \
+camel_file_util_mmap_decode_##type(unsigned char *start, type *dest)	    \
+{									    \
+	return camel_file_util_mmap_decode_uint32 (start, (guint32*) dest, FALSE); \
+}
+
+
 /**
  * camel_file_util_encode_time_t:
  * @out: file to output to
@@ -198,6 +181,7 @@
  * Return value: 0 on success, -1 on error.
  **/
 CFU_DECODE_T(time_t)
+MMAP_DECODE_T(time_t)
 
 /**
  * camel_file_util_encode_off_t:
@@ -221,6 +205,7 @@
  * Return value: 0 on success, -1 on failure.
  **/
 CFU_DECODE_T(off_t)
+MMAP_DECODE_T(off_t)
 
 /**
  * camel_file_util_encode_size_t:
@@ -244,6 +229,7 @@
  * Return value: 0 on success, -1 on failure.
  **/
 CFU_DECODE_T(size_t)
+MMAP_DECODE_T(size_t)
 
 
 /**
@@ -258,18 +244,34 @@
 int
 camel_file_util_encode_string (FILE *out, const char *str)
 {
-	register int len;
+	register int lena, len;
 
 	if (str == NULL)
-		return camel_file_util_encode_uint32 (out, 1);
-	
-	if ((len = strlen (str)) > 65536)
-		len = 65536;
-	
-	if (camel_file_util_encode_uint32 (out, len+1) == -1)
+	{
+		if (camel_file_util_encode_uint32 (out, 0) == -1)
+			return -1;
+
+		return 0;
+	}
+
+	lena = len = strlen (str) + 1;
+
+	if (lena % G_MEM_ALIGN)
+		lena += G_MEM_ALIGN - (lena % G_MEM_ALIGN);
+
+	if (camel_file_util_encode_uint32 (out, lena) == -1)
 		return -1;
-	if (len == 0 || fwrite (str, len, 1, out) == 1)
-		return 0;
+
+	if (fwrite (str, len, 1, out) == 1)
+	{
+		if (lena > len)
+		{
+			if (fwrite ("\0\0\0\0\0\0\0\0", lena-len, 1, out) == 1)
+				return 0;
+			else return -1;
+		}
+	}
+
 	return -1;
 }
 
@@ -294,12 +296,6 @@
 		return -1;
 	}
 
-	len--;
-	if (len > 65536) {
-		*str = NULL;
-		return -1;
-	}
-
 	ret = g_malloc (len+1);
 	if (len > 0 && fread (ret, len, 1, in) != 1) {
 		g_free (ret);
@@ -309,42 +305,7 @@
 
 	ret[len] = 0;
 	*str = ret;
-	return 0;
-}
 
-
-/**
- * camel_mkdir:
- * @path: directory path to create
- * @mode: permissions
- *
- * Creates the directory path described in @path, creating any parent
- * directories as necessary.
- *
- * Returns 0 on success or -1 on fail. In the case of failure, errno
- * will be set appropriately.
- **/
-int
-camel_mkdir (const char *path, mode_t mode)
-{
-	char *copy, *p;
-	
-	g_assert(path && path[0] == '/');
-	
-	p = copy = g_alloca (strlen (path) + 1);
-	strcpy(copy, path);
-	do {
-		p = strchr(p + 1, '/');
-		if (p)
-			*p = '\0';
-		if (access(copy, F_OK) == -1) {
-			if (mkdir(copy, mode) == -1)
-				return -1;
-		}
-		if (p)
-			*p = '/';
-	} while (p);
-	
 	return 0;
 }
 
@@ -361,10 +322,16 @@
 char *
 camel_file_util_safe_filename (const char *name)
 {
+#ifdef G_OS_WIN32
+	const char *unsafe_chars = "/?()'*<>:\"\\|";
+#else
+	const char *unsafe_chars = "/?()'*";
+#endif
+
 	if (name == NULL)
 		return NULL;
 	
-	return camel_url_encode(name, "/?()'*");
+	return camel_url_encode(name, unsafe_chars);
 }
 
 
@@ -378,6 +345,9 @@
  *
  * Cancellable libc read() replacement.
  *
+ * Code that intends to be portable to Win32 should call this function
+ * only on file descriptors returned from open(), not on sockets.
+ *
  * Returns number of bytes read or -1 on fail. On failure, errno will
  * be set appropriately.
  **/
@@ -391,13 +361,17 @@
 		errno = EINTR;
 		return -1;
 	}
-	
+#ifndef G_OS_WIN32
 	cancel_fd = camel_operation_cancel_fd (NULL);
+#else
+	cancel_fd = -1;
+#endif
 	if (cancel_fd == -1) {
 		do {
 			nread = read (fd, buf, n);
 		} while (nread == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
 	} else {
+#ifndef G_OS_WIN32
 		int errnosav, flags, fdmax;
 		fd_set rdset;
 		
@@ -434,6 +408,7 @@
 		errnosav = errno;
 		fcntl (fd, F_SETFL, flags);
 		errno = errnosav;
+#endif
 	}
 	
 	return nread;
@@ -448,6 +423,9 @@
  *
  * Cancellable libc write() replacement.
  *
+ * Code that intends to be portable to Win32 should call this function
+ * only on file descriptors returned from open(), not on sockets.
+ *
  * Returns number of bytes written or -1 on fail. On failure, errno will
  * be set appropriately.
  **/
@@ -461,18 +439,21 @@
 		errno = EINTR;
 		return -1;
 	}
-	
+#ifndef G_OS_WIN32
 	cancel_fd = camel_operation_cancel_fd (NULL);
+#else
+	cancel_fd = -1;
+#endif
 	if (cancel_fd == -1) {
 		do {
 			do {
 				w = write (fd, buf + written, n - written);
 			} while (w == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
-			
 			if (w > 0)
 				written += w;
 		} while (w != -1 && written < n);
 	} else {
+#ifndef G_OS_WIN32
 		int errnosav, flags, fdmax;
 		fd_set rdset, wrset;
 		
@@ -516,6 +497,7 @@
 		errnosav = errno;
 		fcntl (fd, F_SETFL, flags);
 		errno = errnosav;
+#endif
 	}
 	
 	if (w == -1)
@@ -525,31 +507,188 @@
 }
 
 /**
+ * camel_read_socket:
+ * @fd: a socket
+ * @buf: buffer to fill
+ * @n: number of bytes to read into @buf
+ *
+ * Cancellable read() replacement for sockets. Code that intends to be
+ * portable to Win32 should call this function only on sockets
+ * returned from socket(), or accept().
+ *
+ * Returns number of bytes read or -1 on fail. On failure, errno will
+ * be set appropriately. If the socket is nonblocking
+ * camel_read_socket() will retry the read until it gets something.
+ **/
+ssize_t
+camel_read_socket (int fd, char *buf, size_t n)
+{
+#ifndef G_OS_WIN32
+	return camel_read (fd, buf, n);
+#else
+	ssize_t nread;
+	int cancel_fd;
+	
+	if (camel_operation_cancel_check (NULL)) {
+		errno = EINTR;
+		return -1;
+	}
+	cancel_fd = camel_operation_cancel_fd (NULL);
+
+	if (cancel_fd == -1) {
+		do {
+			nread = recv (fd, buf, n, 0);
+		} while (nread == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK);
+	} else {
+		int fdmax;
+		fd_set rdset;
+		u_long yes = 1;
+
+		ioctlsocket (fd, FIONBIO, &yes);
+		fdmax = MAX (fd, cancel_fd) + 1;
+		do {
+			struct timeval tv;
+			int res;
+
+			FD_ZERO (&rdset);
+			FD_SET (fd, &rdset);
+			FD_SET (cancel_fd, &rdset);
+			tv.tv_sec = IO_TIMEOUT;
+			tv.tv_usec = 0;
+			nread = -1;
+
+			res = select(fdmax, &rdset, 0, 0, &tv);
+			if (res == -1)
+				;
+			else if (res == 0)
+				errno = ETIMEDOUT;
+			else if (FD_ISSET (cancel_fd, &rdset)) {
+				errno = EINTR;
+				goto failed;
+			} else {				
+				nread = recv (fd, buf, n, 0);
+			}
+		} while (nread == -1 && WSAGetLastError () == WSAEWOULDBLOCK);
+	failed:
+		;
+	}
+	
+	return nread;
+#endif
+}
+
+/**
+ * camel_write_socket:
+ * @fd: file descriptor
+ * @buf: buffer to write
+ * @n: number of bytes of @buf to write
+ *
+ * Cancellable write() replacement for sockets. Code that intends to
+ * be portable to Win32 should call this function only on sockets
+ * returned from socket() or accept().
+ *
+ * Returns number of bytes written or -1 on fail. On failure, errno will
+ * be set appropriately.
+ **/
+ssize_t
+camel_write_socket (int fd, const char *buf, size_t n)
+{
+#ifndef G_OS_WIN32
+	return camel_write (fd, buf, n);
+#else
+	ssize_t w, written = 0;
+	int cancel_fd;
+	
+	if (camel_operation_cancel_check (NULL)) {
+		errno = EINTR;
+		return -1;
+	}
+
+	cancel_fd = camel_operation_cancel_fd (NULL);
+	if (cancel_fd == -1) {
+		do {
+			do {
+				w = send (fd, buf + written, n - written, 0);
+			} while (w == SOCKET_ERROR && WSAGetLastError () == WSAEWOULDBLOCK);
+			if (w > 0)
+				written += w;
+		} while (w != -1 && written < n);
+	} else {
+		int fdmax;
+		fd_set rdset, wrset;
+		u_long arg = 1;
+
+		ioctlsocket (fd, FIONBIO, &arg);
+		fdmax = MAX (fd, cancel_fd) + 1;
+		do {
+			struct timeval tv;
+			int res;
+
+			FD_ZERO (&rdset);
+			FD_ZERO (&wrset);
+			FD_SET (fd, &wrset);
+			FD_SET (cancel_fd, &rdset);
+			tv.tv_sec = IO_TIMEOUT;
+			tv.tv_usec = 0;			
+			w = -1;
+
+			res = select (fdmax, &rdset, &wrset, 0, &tv);
+			if (res == SOCKET_ERROR) {
+				/* w still being -1 will catch this */
+			} else if (res == 0)
+				errno = ETIMEDOUT;
+			else if (FD_ISSET (cancel_fd, &rdset))
+				errno = EINTR;
+			else {
+				w = send (fd, buf + written, n - written, 0);
+				if (w == SOCKET_ERROR) {
+					if (WSAGetLastError () == WSAEWOULDBLOCK)
+						w = 0;
+				} else
+					written += w;
+			}
+		} while (w != -1 && written < n);
+		arg = 0;
+		ioctlsocket (fd, FIONBIO, &arg);
+	}
+	
+	if (w == -1)
+		return -1;
+	
+	return written;
+#endif
+}
+
+
+/**
  * camel_file_util_savename:
- * @filename: 
+ * @filename: a pathname
  * 
- * Builds a filename of the form ".#" + @filename, used to create
- * a two-stage commit file write.
+ * Builds a pathname where the basename is of the form ".#" + the
+ * basename of @filename, for instance used in a two-stage commit file
+ * write.
  * 
- * Return value: ".#" + filename.  It must be free'd with g_free().
+ * Return value: The new pathname.  It must be free'd with g_free().
  **/
 char *
 camel_file_util_savename(const char *filename)
 {
-	char *name, *slash;
-	int off;
+	char *dirname, *retval;
 
-	name = g_malloc(strlen(filename)+3);
-	slash = strrchr(filename, '/');
-	if (slash) {
-		off = slash-filename;
+	dirname = g_path_get_dirname(filename);
 
-		memcpy(name, filename, off+1);
-		memcpy(name + off+1, ".#", 2);
-		strcpy(name + off+3, filename+off+1);
+	if (strcmp (dirname, ".") == 0) {
+		retval = g_strconcat (".#", filename, NULL);
 	} else {
-		sprintf(name, ".#%s", filename);
+		char *basename = g_path_get_basename(filename);
+		char *newbasename = g_strconcat (".#", basename, NULL);
+
+		retval = g_build_filename (dirname, newbasename, NULL);
+
+		g_free (newbasename);
+		g_free (basename);
 	}
+	g_free (dirname);
 
-	return name;
+	return retval;
 }
Index: camel/camel-search-private.c
===================================================================
--- camel/camel-search-private.c	(revision 444)
+++ camel/camel-search-private.c	(working copy)
@@ -29,22 +29,23 @@
 #include <config.h>
 #endif
 
-#include <glib.h>
 #include <sys/types.h>
 #include <regex.h>
 #include <string.h>
 #include <ctype.h>
 #include <stdio.h>
 
+#include <glib.h>
+
+#include "libedataserver/e-sexp.h"
+
 #include "camel-exception.h"
+#include "camel-i18n.h"
 #include "camel-mime-message.h"
 #include "camel-multipart.h"
+#include "camel-search-private.h"
 #include "camel-stream-mem.h"
-#include "libedataserver/e-sexp.h"
-#include "camel-search-private.h"
-#include "camel-i18n.h"
 
-#include <glib/gunicode.h>
 
 #define d(x)
 
@@ -280,7 +281,7 @@
 			}
 			
 			if (nuni + npos == puni)
-				return p;
+				return (const char *) p;
 		}
 	}
 	
@@ -367,6 +368,7 @@
 {
 	const unsigned char *p;
 	int vlen, mlen;
+	gunichar c;
 	
 	if (how == CAMEL_SEARCH_MATCH_SOUNDEX)
 		return header_soundex (value, match);
@@ -379,8 +381,8 @@
 	/* from dan the man, if we have mixed case, perform a case-sensitive match,
 	   otherwise not */
 	p = (const unsigned char *)match;
-	while (*p) {
-		if (isupper(*p)) {
+	while (c = camel_utf8_getc(&p)) {
+		if (g_unichar_isupper(c)) {
 			switch (how) {
 			case CAMEL_SEARCH_MATCH_EXACT:
 				return strcmp(value, match) == 0;
@@ -395,7 +397,6 @@
 			}
 			return FALSE;
 		}
-		p++;
 	}
 	
 	switch (how) {
@@ -419,13 +420,15 @@
 gboolean
 camel_search_header_match (const char *value, const char *match, camel_search_match_t how, camel_search_t type, const char *default_charset)
 {
-	const char *name, *addr;
+	const char *name, *addr, *ptr;
 	int truth = FALSE, i;
 	CamelInternetAddress *cia;
 	char *v, *vdom, *mdom;
+	gunichar c;
 
-	while (*value && isspace (*value))
-		value++;
+	ptr = value;
+	while ((c = camel_utf8_getc((const unsigned char **)&ptr)) && g_unichar_isspace(c))
+		value = ptr;
 	
 	switch(type) {
 	case CAMEL_SEARCH_TYPE_ENCODED:
Index: camel/camel-mime-filter-index.c
===================================================================
--- camel/camel-mime-filter-index.c	(revision 444)
+++ camel/camel-mime-filter-index.c	(working copy)
@@ -19,7 +19,6 @@
  */
 
 #include "camel-mime-filter-index.h"
-
 #include "camel-text-index.h"
 
 static void camel_mime_filter_index_class_init (CamelMimeFilterIndexClass *klass);
Index: camel/camel-vtrash-folder.c
===================================================================
--- camel/camel-vtrash-folder.c	(revision 444)
+++ camel/camel-vtrash-folder.c	(working copy)
@@ -23,15 +23,16 @@
 
 #include <config.h>
 
+#include <string.h>
+
 #include "camel-exception.h"
-#include "camel-vtrash-folder.h"
+#include "camel-i18n.h"
+#include "camel-mime-message.h"
+#include "camel-private.h"
 #include "camel-store.h"
 #include "camel-vee-store.h"
-#include "camel-mime-message.h"
-#include "camel-i18n.h"
-#include "camel-private.h"
+#include "camel-vtrash-folder.h"
 
-#include <string.h>
 
 /* Returns the class for a CamelFolder */
 #define CF_CLASS(so) ((CamelFolderClass *)((CamelObject *)(so))->klass)
Index: camel/camel-multipart.c
===================================================================
--- camel/camel-multipart.c	(revision 444)
+++ camel/camel-multipart.c	(working copy)
@@ -31,11 +31,12 @@
 #include <time.h>   /* for time */
 #include <errno.h>
 
+#include "libedataserver/md5-utils.h"
+
 #include "camel-stream-mem.h"
 #include "camel-multipart.h"
+#include "camel-exception.h"
 #include "camel-mime-part.h"
-#include "camel-exception.h"
-#include "libedataserver/md5-utils.h"
 
 #define d(x)
 
Index: camel/camel-file-utils.h
===================================================================
--- camel/camel-file-utils.h	(revision 444)
+++ camel/camel-file-utils.h	(working copy)
@@ -36,11 +36,17 @@
 #include <stdio.h>
 #include <sys/types.h>
 #include <time.h>
+#include <fcntl.h>
 
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
 int camel_file_util_encode_fixed_int32 (FILE *out, gint32);
 int camel_file_util_decode_fixed_int32 (FILE *in, gint32 *);
 int camel_file_util_encode_uint32 (FILE *out, guint32);
 int camel_file_util_decode_uint32 (FILE *in, guint32 *);
+
 int camel_file_util_encode_time_t (FILE *out, time_t);
 int camel_file_util_decode_time_t (FILE *in, time_t *);
 int camel_file_util_encode_off_t (FILE *out, off_t);
@@ -50,14 +56,33 @@
 int camel_file_util_encode_string (FILE *out, const char *);
 int camel_file_util_decode_string (FILE *in, char **);
 
-int camel_mkdir (const char *path, mode_t mode);
+unsigned char* camel_file_util_mmap_decode_time_t(unsigned char *start, time_t *dest);
+unsigned char* camel_file_util_mmap_decode_off_t(unsigned char *start, off_t *dest);
+unsigned char* camel_file_util_mmap_decode_size_t(unsigned char *start, size_t *dest);
+unsigned char* camel_file_util_mmap_decode_uint32 (unsigned char *start, guint32 *dest, gboolean is_string);
+
 char *camel_file_util_safe_filename (const char *name);
 
+/* Code that intends to be portable to Win32 should use camel_read()
+ * and camel_write() only on file descriptors returned from open(),
+ * creat(), pipe() or fileno(). On Win32 camel_read() and
+ * camel_write() calls will not be cancellable. For sockets, use
+ * camel_read_socket() and camel_write_socket(). These are cancellable
+ * also on Win32.
+ */
 ssize_t camel_read (int fd, char *buf, size_t n);
 ssize_t camel_write (int fd, const char *buf, size_t n);
 
+ssize_t camel_read_socket (int fd, char *buf, size_t n);
+ssize_t camel_write_socket (int fd, const char *buf, size_t n);
+
 char *camel_file_util_savename(const char *filename);
 
+#define get_unaligned_u32(p) ((((unsigned char*)(p))[0]) | \
+	(((unsigned char*)(p))[1] << 8) | \
+	(((unsigned char*)(p))[2] << 16) | \
+	(((unsigned char*)(p))[3] << 24))
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
Index: camel/camel-debug.c
===================================================================
--- camel/camel-debug.c	(revision 444)
+++ camel/camel-debug.c	(working copy)
@@ -25,6 +25,7 @@
 
 #include <pthread.h>
 
+#include "libedataserver/e-data-server-util.h"
 #include "camel-debug.h"
 
 int camel_verbose_debug;
@@ -133,7 +134,7 @@
 {
 	if (camel_debug(mode)) {
 		pthread_mutex_lock(&debug_lock);
-		printf("Thread %lx >\n", pthread_self());
+		printf("Thread %" G_GINT64_MODIFIER "x >\n", e_util_pthread_id(pthread_self()));
 		return TRUE;
 	}
 
@@ -149,7 +150,7 @@
 void
 camel_debug_end(void)
 {
-	printf("< %lx >\n", pthread_self());
+	printf("< %" G_GINT64_MODIFIER "x >\n", e_util_pthread_id(pthread_self()));
 	pthread_mutex_unlock(&debug_lock);
 }
 
Index: camel/camel-digest-folder.c
===================================================================
--- camel/camel-digest-folder.c	(revision 444)
+++ camel/camel-digest-folder.c	(working copy)
@@ -196,6 +196,7 @@
 		}
 		
 		info = camel_folder_summary_info_new_from_message (folder->summary, CAMEL_MIME_MESSAGE (wrapper));
+		g_free(info->uid);
 		info->uid = g_strdup_printf ("%s%d", preuid, i);
 		camel_folder_summary_add (folder->summary, info);
 	}
Index: camel/camel-vee-folder.c
===================================================================
--- camel/camel-vee-folder.c	(revision 444)
+++ camel/camel-vee-folder.c	(working copy)
@@ -26,25 +26,25 @@
 
 #include <string.h>
 
+#include "libedataserver/md5-utils.h"
+
+#if defined (DOEPOOLV) || defined (DOESTRV)
+#include "libedataserver/e-memory.h"
+#endif
+
+#include "camel-debug.h"
 #include "camel-exception.h"
-#include "camel-vee-folder.h"
-#include "camel-store.h"
+#include "camel-folder-search.h"
+#include "camel-i18n.h"
 #include "camel-mime-message.h"
-#include "camel-folder-search.h"
-#include "camel-vee-summary.h"
-
+#include "camel-private.h"
 #include "camel-session.h"
+#include "camel-store.h"
+#include "camel-vee-folder.h"
 #include "camel-vee-store.h"	/* for open flags */
-#include "camel-private.h"
-#include "camel-debug.h"
-#include "camel-i18n.h"
+#include "camel-vee-summary.h"
 
-#include "libedataserver/md5-utils.h"
 
-#if defined (DOEPOOLV) || defined (DOESTRV)
-#include "libedataserver/e-memory.h"
-#endif
-
 #define d(x) 
 #define dd(x) (camel_debug("vfolder")?(x):0)
 
@@ -1271,7 +1271,7 @@
 		CAMEL_VEE_FOLDER_LOCK(folder_unmatched, summary_lock);
 
 	dd(printf("Vfolder '%s' subfolder changed '%s'\n", folder->full_name, sub->full_name));
-	dd(printf(" changed %d added %d removed %d\n", changes->uid_changed->len, changes->uid_added->len, changes->uid_removed->len));
+	dd(printf(" changed %u added %u removed %u\n", changes->uid_changed->len, changes->uid_added->len, changes->uid_removed->len));
 
 	/* Always remove removed uid's, in any case */
 	for (i=0;i<changes->uid_removed->len;i++) {
Index: camel/camel-mime-part-utils.c
===================================================================
--- camel/camel-mime-part-utils.c	(revision 444)
+++ camel/camel-mime-part-utils.c	(working copy)
@@ -32,23 +32,23 @@
 #include <ctype.h>
 #include <errno.h>
 
-#include <libedataserver/e-iconv.h>
+#include "libedataserver/e-iconv.h"
 
 #include "camel-charset-map.h"
+#include "camel-html-parser.h"
+#include "camel-mime-filter-basic.h"
+#include "camel-mime-filter-charset.h"
+#include "camel-mime-filter-crlf.h"
+#include "camel-mime-filter-save.h"
+#include "camel-mime-message.h"
 #include "camel-mime-part-utils.h"
-#include "camel-mime-message.h"
+#include "camel-multipart-encrypted.h"
+#include "camel-multipart-signed.h"
 #include "camel-multipart.h"
-#include "camel-multipart-signed.h"
-#include "camel-multipart-encrypted.h"
 #include "camel-seekable-substream.h"
+#include "camel-stream-filter.h"
 #include "camel-stream-fs.h"
-#include "camel-stream-filter.h"
 #include "camel-stream-mem.h"
-#include "camel-mime-filter-basic.h"
-#include "camel-mime-filter-charset.h"
-#include "camel-mime-filter-crlf.h"
-#include "camel-mime-filter-save.h"
-#include "camel-html-parser.h"
 
 #define d(x) /*(printf("%s(%d): ", __FILE__, __LINE__),(x))
 	       #include <stdio.h>*/
@@ -120,7 +120,7 @@
 		d(printf("Created multi-part\n"));
 		break;
 	default:
-		g_warning("Invalid state encountered???: %d", camel_mime_parser_state (mp));
+		g_warning("Invalid state encountered???: %u", camel_mime_parser_state (mp));
 	}
 	
 	if (content) {
Index: camel/camel-mime-part.c
===================================================================
--- camel/camel-mime-part.c	(revision 444)
+++ camel/camel-mime-part.c	(working copy)
@@ -33,19 +33,19 @@
 #include <ctype.h>
 #include <errno.h>
 
-#include <libedataserver/e-iconv.h>
+#include "libedataserver/e-iconv.h"
 
-#include "camel-mime-parser.h"
-#include "camel-stream-mem.h"
-#include "camel-stream-filter.h"
+#include "camel-charset-map.h"
+#include "camel-exception.h"
 #include "camel-mime-filter-basic.h"
+#include "camel-mime-filter-charset.h"
 #include "camel-mime-filter-crlf.h"
-#include "camel-mime-filter-charset.h"
+#include "camel-mime-parser.h"
+#include "camel-mime-part-utils.h"
 #include "camel-mime-part.h"
-#include "camel-mime-part-utils.h"
 #include "camel-mime-utils.h"
-#include "camel-exception.h"
-#include "camel-charset-map.h"
+#include "camel-stream-filter.h"
+#include "camel-stream-mem.h"
 #include "camel-string-utils.h"
 
 #define d(x) /*(printf("%s(%d): ", __FILE__, __LINE__),(x))*/
@@ -950,7 +950,7 @@
 			process_header((CamelMedium *)dw, "content-type", content);
 
 		while (headers) {
-			if (strcasecmp(headers->name, "content-type") == 0
+			if (g_ascii_strcasecmp(headers->name, "content-type") == 0
 			    && headers->value != content)
 				camel_medium_add_header((CamelMedium *)dw, "X-Invalid-Content-Type", headers->value);
 			else
@@ -961,7 +961,7 @@
 		camel_mime_part_construct_content_from_parser (mime_part, mp);
 		break;
 	default:
-		g_warning("Invalid state encountered???: %d", camel_mime_parser_state(mp));
+		g_warning("Invalid state encountered???: %u", camel_mime_parser_state(mp));
 	}
 
 	d(printf("mime_part::construct_from_parser() leaving\n"));
Index: camel/camel-disco-store.c
===================================================================
--- camel/camel-disco-store.c	(revision 444)
+++ camel/camel-disco-store.c	(working copy)
@@ -296,6 +296,8 @@
 set_status(CamelDiscoStore *disco_store, CamelDiscoStoreStatus status, CamelException *ex)
 {
 	CamelException x;
+	CamelService *service = CAMEL_SERVICE (disco_store);
+	gboolean network_state = camel_session_get_network_state (service->session);
 
 	if (disco_store->status == status)
 		return;
@@ -303,32 +305,36 @@
 	camel_exception_init(&x);
 	/* Sync the folder fully if we've been told to sync online for this store or this folder
 	   and we're going offline */
-	if (disco_store->status == CAMEL_DISCO_STORE_ONLINE
-	    && status == CAMEL_DISCO_STORE_OFFLINE) {
-		if (((CamelStore *)disco_store)->folders) {
-			GPtrArray *folders;
-			CamelFolder *folder;
-			int i, sync;
-			
-			sync =  camel_url_get_param(((CamelService *)disco_store)->url, "offline_sync") != NULL;
 
-			folders = camel_object_bag_list(((CamelStore *)disco_store)->folders);
-			for (i=0;i<folders->len;i++) {
-				folder = folders->pdata[i];
-				if (CAMEL_CHECK_TYPE(folder, CAMEL_DISCO_FOLDER_TYPE)
-				    && (sync || ((CamelDiscoFolder *)folder)->offline_sync)) {
-					camel_disco_folder_prepare_for_offline((CamelDiscoFolder *)folder, "(match-all)", &x);
-					camel_exception_clear(&x);
+	if (network_state) {
+		if (disco_store->status == CAMEL_DISCO_STORE_ONLINE
+		    && status == CAMEL_DISCO_STORE_OFFLINE) {
+			if (((CamelStore *)disco_store)->folders) {
+				GPtrArray *folders;
+				CamelFolder *folder;
+				int i, sync;
+				
+				sync =  camel_url_get_param(((CamelService *)disco_store)->url, "offline_sync") != NULL;
+				
+				folders = camel_object_bag_list(((CamelStore *)disco_store)->folders);
+				for (i=0;i<folders->len;i++) {
+					folder = folders->pdata[i];
+					if (CAMEL_CHECK_TYPE(folder, CAMEL_DISCO_FOLDER_TYPE)
+					    && (sync || ((CamelDiscoFolder *)folder)->offline_sync)) {
+						camel_disco_folder_prepare_for_offline((CamelDiscoFolder *)folder, "(match-all)", &x);
+						camel_exception_clear(&x);
+					}
+					camel_object_unref(folder);
 				}
-				camel_object_unref(folder);
+				g_ptr_array_free(folders, TRUE);
 			}
-			g_ptr_array_free(folders, TRUE);
 		}
+		
+		camel_store_sync(CAMEL_STORE (disco_store), FALSE, &x);
+		camel_exception_clear(&x);
 	}
-
-	camel_store_sync(CAMEL_STORE (disco_store), FALSE, &x);
-	camel_exception_clear(&x);
-	if (!camel_service_disconnect (CAMEL_SERVICE (disco_store), TRUE, ex))
+	
+	if (!camel_service_disconnect (CAMEL_SERVICE (disco_store), network_state, ex))
 		return;
 
 	disco_store->status = status;
Index: camel/camel-html-parser.c
===================================================================
--- camel/camel-html-parser.c	(revision 444)
+++ camel/camel-html-parser.c	(working copy)
@@ -179,8 +179,8 @@
 }
 
 /* this map taken out of libxml */
-static const struct {
-	const unsigned int val;
+static struct {
+	unsigned int val;
 	const char *name;
 } entity_map[] = {
 /*
Index: camel/camel-mime-filter-windows.c
===================================================================
--- camel/camel-mime-filter-windows.c	(revision 444)
+++ camel/camel-mime-filter-windows.c	(working copy)
@@ -29,10 +29,9 @@
 #include <string.h>
 #include <ctype.h>
 
+#include "camel-charset-map.h"
 #include "camel-mime-filter-windows.h"
 
-#include "camel-charset-map.h"
-
 #define d(x)
 #define w(x)
 
Index: camel/camel-url.c
===================================================================
--- camel/camel-url.c	(revision 444)
+++ camel/camel-url.c	(working copy)
@@ -32,12 +32,12 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include "camel-url.h"
 #include "camel-exception.h"
+#include "camel-i18n.h"
 #include "camel-mime-utils.h"
 #include "camel-object.h"
 #include "camel-string-utils.h"
-#include "camel-i18n.h"
+#include "camel-url.h"
 
 static void copy_param (GQuark key_id, gpointer data, gpointer user_data);
 static void output_param (GQuark key_id, gpointer data, gpointer user_data);
@@ -110,7 +110,7 @@
 
 			semi = strchr(url_string, ';');
 			if (semi && semi < colon &&
-			    !strncasecmp (semi, ";auth=", 6)) {
+			    !g_ascii_strncasecmp (semi, ";auth=", 6)) {
 				url->authmech = g_strndup (semi + 6,
 							   colon - semi - 6);
 				camel_url_decode (url->authmech);
Index: camel/camel-object.c
===================================================================
--- camel/camel-object.c	(revision 444)
+++ camel/camel-object.c	(working copy)
@@ -20,21 +20,22 @@
  * USA
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <stdio.h>
 #include <string.h>
 #include <pthread.h>
 #include <errno.h>
 
+#include <glib/gstdio.h>
+
+#include "libedataserver/e-memory.h"
+#include "libedataserver/e-msgport.h"
+#include "libedataserver/e-data-server-util.h"
+
+#include "camel-file-utils.h"
 #include "camel-object.h"
-#include "camel-file-utils.h"
 
-#include <libedataserver/e-memory.h>
-#include <libedataserver/e-msgport.h>
-
 #define d(x)
 #define b(x) 			/* object bag */
 #define h(x) 			/* hooks */
@@ -90,6 +91,7 @@
 	void *key;		/* the key reserved */
 	int waiters;		/* count of threads waiting for key */
 	pthread_t owner;	/* the thread that has reserved the bag for a new entry */
+	int have_owner;
 	GCond *cond;
 };
 
@@ -239,7 +241,8 @@
 {
 	/*printf("%p: finalise %s\n", o, o->klass->name);*/
 
-	g_assert(o->ref_count == 0);
+	if (o->ref_count == 0)
+		return;
 
 	camel_object_free_hooks(o);
 
@@ -577,7 +580,7 @@
 
 	res = 0;
 abort:
-	for (i=0;i<argv->argc;i++) {
+/*	for (i=0;i<argv->argc;i++) {
 		CamelArg *arg = &argv->argv[i];
 
 		if ((argv->argv[i].tag & CAMEL_ARG_TYPE) == CAMEL_ARG_STR)
@@ -592,7 +595,7 @@
 
 	if (meta)
 		camel_object_free(obj, CAMEL_OBJECT_METADATA, meta);
-
+*/
 	return res;
 }
 
@@ -1350,7 +1353,7 @@
 	g_return_if_fail (id != 0);
 
 	if (obj->hooks == NULL) {
-		g_warning("camel_object_unhook_event: trying to unhook `%d` from an instance of `%s' with no hooks",
+		g_warning("camel_object_unhook_event: trying to unhook `%u` from an instance of `%s' with no hooks",
 			  id, obj->klass->name);
 		return;
 	}
@@ -1380,7 +1383,7 @@
 	}
 	camel_object_unget_hooks(obj);
 
-	g_warning("camel_object_unhook_event: cannot find hook id %d in instance of `%s'",
+	g_warning("camel_object_unhook_event: cannot find hook id %u in instance of `%s'",
 		  id, obj->klass->name);
 }
 
@@ -1455,8 +1458,7 @@
 	pair = co_find_pair_ptr(obj->klass, interface_name);
 	if (pair) {
 		GPtrArray *interfaces = pair->data;
-		int i;
-
+		
 		for (i=0;i<interfaces->len;i++) {
 			hook = co_find_pair(interfaces->pdata[i], name);
 			if (hook)
@@ -1807,7 +1809,7 @@
 	if (file == NULL)
 		return 0;
 
-	fp = fopen(file, "r");
+	fp = g_fopen(file, "rb");
 	if (fp != NULL) {
 		if (fread(magic, 4, 1, fp) == 1
 		    && memcmp(magic, CAMEL_OBJECT_STATE_FILE_MAGIC, 4) == 0)
@@ -1834,7 +1836,7 @@
 {
 	CamelObject *obj = vo;
 	int res = -1;
-	char *file, *savename, *tmp;
+	char *file, *savename, *dirname;
 	FILE *fp;
 
 	camel_object_get(vo, NULL, CAMEL_OBJECT_STATE_FILE, &file, NULL);
@@ -1842,19 +1844,16 @@
 		return 0;
 
 	savename = camel_file_util_savename(file);
-	tmp = strrchr(savename, '/');
-	if (tmp) {
-		*tmp = 0;
-		camel_mkdir(savename, 0777);
-		*tmp = '/';
-	}
-	fp = fopen(savename, "w");
+	dirname = g_path_get_dirname(savename);
+	e_util_mkdir_hier(dirname, 0777);
+	g_free(dirname);
+	fp = g_fopen(savename, "wb");
 	if (fp != NULL) {
 		if (fwrite(CAMEL_OBJECT_STATE_FILE_MAGIC, 4, 1, fp) == 1
 		    && obj->klass->state_write(obj, fp) == 0) {
 			if (fclose(fp) == 0) {
 				res = 0;
-				rename(savename, file);
+				g_rename(savename, file);
 			}
 		} else {
 			fclose(fp);
@@ -2017,11 +2016,11 @@
 	}
 
 	g_assert(res != NULL);
-	g_assert(res->owner == pthread_self());
+	g_assert(res->have_owner && pthread_equal(res->owner, pthread_self()));
 
 	if (res->waiters > 0) {
 		b(printf("unreserve bag '%s', waking waiters\n", (char *)key));
-		res->owner = 0;
+		res->have_owner = FALSE;
 		g_cond_signal(res->cond);
 	} else {
 		b(printf("unreserve bag '%s', no waiters, freeing reservation\n", (char *)key));
@@ -2121,7 +2120,7 @@
 			b(printf("object bag get '%s', reserved, waiting\n", (char *)key));
 
 			res->waiters++;
-			g_assert(res->owner != pthread_self());
+			g_assert(!res->have_owner || !pthread_equal(res->owner, pthread_self()));
 			g_cond_wait(res->cond, ref_lock);
 			res->waiters--;
 
@@ -2134,6 +2133,7 @@
 
 			/* we don't actually reserve it */
 			res->owner = pthread_self();
+			res->have_owner = TRUE;
 			co_bag_unreserve(bag, key);
 		}
 	}
@@ -2215,7 +2215,7 @@
 
 		if (res) {
 			b(printf("bag reserve %s, already reserved, waiting\n", (char *)key));
-			g_assert(res->owner != pthread_self());
+			g_assert(!res->have_owner || !pthread_equal(res->owner, pthread_self()));
 			res->waiters++;
 			g_cond_wait(res->cond, ref_lock);
 			res->waiters--;
@@ -2226,10 +2226,12 @@
 				o->ref_count++;
 				/* in which case we dont need to reserve the bag either */
 				res->owner = pthread_self();
+				res->have_owner = TRUE;
 				co_bag_unreserve(bag, key);
 			} else {
 				b(printf("finished wait, now owner of '%s'\n", (char *)key));
 				res->owner = pthread_self();
+				res->have_owner = TRUE;
 			}
 		} else {
 			b(printf("bag reserve %s, no key, reserving\n", (char *)key));
@@ -2238,6 +2240,7 @@
 			res->key = bag->copy_key(key);
 			res->cond = g_cond_new();
 			res->owner = pthread_self();
+			res->have_owner = TRUE;
 			res->next = bag->reserved;
 			bag->reserved = res;
 		}
Index: camel/camel-tcp-stream-raw.c
===================================================================
--- camel/camel-tcp-stream-raw.c	(revision 444)
+++ camel/camel-tcp-stream-raw.c	(working copy)
@@ -20,23 +20,32 @@
  *
  */
 
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 
 #include <stdio.h>
 #include <string.h>
 #include <sys/time.h>
 #include <sys/types.h>
-#include <sys/stat.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <errno.h>
 
-#include "camel-tcp-stream-raw.h"
 #include "camel-file-utils.h"
 #include "camel-operation.h"
+#include "camel-tcp-stream-raw.h"
 
+#ifndef G_OS_WIN32
+#define SOCKET_ERROR_CODE() errno
+#define SOCKET_CLOSE(fd) close (fd)
+#define SOCKET_ERROR_IS_EINPROGRESS() (errno == EINPROGRESS)
+#define SOCKET_ERROR_IS_EINTR() (errno == EINTR)
+#else
+#define SOCKET_ERROR_CODE() WSAGetLastError ()
+#define SOCKET_CLOSE(fd) closesocket (fd)
+#define SOCKET_ERROR_IS_EINPROGRESS() (WSAGetLastError () == WSAEWOULDBLOCK)
+#define SOCKET_ERROR_IS_EINTR() 0 /* No WSAEINTR in WinSock2 */
+#endif
+
 static CamelTcpStreamClass *parent_class = NULL;
 
 /* Returns the class for a CamelTcpStreamRaw */
@@ -90,7 +99,7 @@
 	CamelTcpStreamRaw *stream = CAMEL_TCP_STREAM_RAW (object);
 	
 	if (stream->sockfd != -1)
-		close (stream->sockfd);
+		SOCKET_CLOSE (stream->sockfd);
 }
 
 
@@ -238,7 +247,7 @@
 {
 	CamelTcpStreamRaw *raw = CAMEL_TCP_STREAM_RAW (stream);
 	
-	return camel_read (raw->sockfd, buffer, n);
+	return camel_read_socket (raw->sockfd, buffer, n);
 }
 
 static ssize_t
@@ -246,7 +255,7 @@
 {
 	CamelTcpStreamRaw *raw = CAMEL_TCP_STREAM_RAW (stream);
 	
-	return camel_write (raw->sockfd, buffer, n);
+	return camel_write_socket (raw->sockfd, buffer, n);
 }
 
 static int
@@ -258,7 +267,7 @@
 static int
 stream_close (CamelStream *stream)
 {
-	if (close (((CamelTcpStreamRaw *)stream)->sockfd) == -1)
+	if (SOCKET_CLOSE (((CamelTcpStreamRaw *)stream)->sockfd) == -1)
 		return -1;
 	
 	((CamelTcpStreamRaw *)stream)->sockfd = -1;
@@ -293,32 +302,52 @@
 	cancel_fd = camel_operation_cancel_fd (NULL);
 	if (cancel_fd == -1) {
 		if (connect (fd, h->ai_addr, h->ai_addrlen) == -1) {
+			/* Yeah, errno is meaningless on Win32 after a
+			 * Winsock call fails, but I doubt the callers
+			 * check errno anyway.
+			 */
 			errnosav = errno;
-			close (fd);
+			SOCKET_CLOSE (fd);
 			errno = errnosav;
 			return -1;
 		}
 		
 		return fd;
 	} else {
-		int flags, fdmax, status;
+#ifndef G_OS_WIN32
+		int flags;
+#endif
+		int fdmax, status;
 		fd_set rdset, wrset;
 		
+#ifndef G_OS_WIN32
 		flags = fcntl (fd, F_GETFL);
 		fcntl (fd, F_SETFL, flags | O_NONBLOCK);
-		
+#else
+		{
+			u_long yes = 1;
+			ioctlsocket (fd, FIONBIO, &yes);
+		}
+#endif
 		if (connect (fd, h->ai_addr, h->ai_addrlen) == 0) {
+#ifndef G_OS_WIN32
 			fcntl (fd, F_SETFL, flags);
+#else
+			{
+				u_long no = 0;
+				ioctlsocket (fd, FIONBIO, &no);
+			}
+#endif
 			return fd;
 		}
 		
-		if (errno != EINPROGRESS) {
+		if (!SOCKET_ERROR_IS_EINPROGRESS ()) {
 			errnosav = errno;
-			close (fd);
+			SOCKET_CLOSE (fd);
 			errno = errnosav;
 			return -1;
 		}
-		
+			
 		do {
 			FD_ZERO (&rdset);
 			FD_ZERO (&wrset);
@@ -329,36 +358,42 @@
 			tv.tv_usec = 0;
 			
 			status = select (fdmax, &rdset, &wrset, 0, &tv);
-		} while (status == -1 && errno == EINTR);
+		} while (status == -1 && SOCKET_ERROR_IS_EINTR ());
 		
 		if (status <= 0) {
-			close (fd);
+			SOCKET_CLOSE (fd);
 			errno = ETIMEDOUT;
 			return -1;
 		}
 		
 		if (cancel_fd != -1 && FD_ISSET (cancel_fd, &rdset)) {
-			close (fd);
+			SOCKET_CLOSE (fd);
 			errno = EINTR;
 			return -1;
 		} else {
 			len = sizeof (int);
 			
-			if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &len) == -1) {
+			if (getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &ret, &len) == -1) {
 				errnosav = errno;
-				close (fd);
+				SOCKET_CLOSE (fd);
 				errno = errnosav;
 				return -1;
 			}
 			
 			if (ret != 0) {
-				close (fd);
+				SOCKET_CLOSE (fd);
 				errno = ret;
 				return -1;
 			}
 		}
-		
+#ifndef G_OS_WIN32
 		fcntl (fd, F_SETFL, flags);
+#else
+		{
+			u_long no = 0;
+			ioctlsocket (fd, FIONBIO, &no);
+		}
+#endif
 	}
 	
 	return fd;
@@ -398,8 +433,10 @@
 get_sockopt_optname (const CamelSockOptData *data)
 {
 	switch (data->option) {
+#ifdef TCP_MAXSEG
 	case CAMEL_SOCKOPT_MAXSEGMENT:
 		return TCP_MAXSEG;
+#endif
 	case CAMEL_SOCKOPT_NODELAY:
 		return TCP_NODELAY;
 	case CAMEL_SOCKOPT_BROADCAST:
@@ -430,6 +467,7 @@
 		return -1;
 	
 	if (data->option == CAMEL_SOCKOPT_NONBLOCKING) {
+#ifndef G_OS_WIN32
 		int flags;
 		
 		flags = fcntl (((CamelTcpStreamRaw *)stream)->sockfd, F_GETFL);
@@ -437,7 +475,9 @@
 			return -1;
 		
 		data->value.non_blocking = flags & O_NONBLOCK ? TRUE : FALSE;
-		
+#else
+		data->value.non_blocking = ((CamelTcpStreamRaw *)stream)->is_nonblocking;
+#endif
 		return 0;
 	}
 	
@@ -457,6 +497,7 @@
 		return -1;
 	
 	if (data->option == CAMEL_SOCKOPT_NONBLOCKING) {
+#ifndef G_OS_WIN32
 		int flags, set;
 		
 		flags = fcntl (((CamelTcpStreamRaw *)stream)->sockfd, F_GETFL);
@@ -468,7 +509,12 @@
 		
 		if (fcntl (((CamelTcpStreamRaw *)stream)->sockfd, F_SETFL, flags) == -1)
 			return -1;
-		
+#else
+		u_long fionbio = data->value.non_blocking ? 1 : 0;
+		if (ioctlsocket (((CamelTcpStreamRaw *)stream)->sockfd, FIONBIO, &fionbio) == SOCKET_ERROR)
+			return -1;
+		((CamelTcpStreamRaw *)stream)->is_nonblocking = data->value.non_blocking ? 1 : 0;
+#endif
 		return 0;
 	}
 	
Index: camel/camel-vee-store.c
===================================================================
--- camel/camel-vee-store.c	(revision 444)
+++ camel/camel-vee-store.c	(working copy)
@@ -22,15 +22,16 @@
 #include <config.h>
 #endif
 
+#include <string.h>
+
+#include <glib/gstdio.h>
+
 #include "camel-exception.h"
+#include "camel-i18n.h"
+#include "camel-private.h"
+#include "camel-vee-folder.h"
 #include "camel-vee-store.h"
-#include "camel-vee-folder.h"
 
-#include "camel-private.h"
-#include "camel-i18n.h"
-
-#include <string.h>
-
 #define d(x)
 
 static CamelFolder *vee_get_folder (CamelStore *store, const char *folder_name, guint32 flags, CamelException *ex);
@@ -374,7 +375,7 @@
 
 		camel_object_get(folder, NULL, CAMEL_OBJECT_STATE_FILE, &statefile, NULL);
 		if (statefile) {
-			unlink(statefile);
+			g_unlink(statefile);
 			camel_object_free(folder, CAMEL_OBJECT_STATE_FILE, statefile);
 			camel_object_set(folder, NULL, CAMEL_OBJECT_STATE_FILE, NULL, NULL);
 		}
Index: camel/Makefile.am
===================================================================
--- camel/Makefile.am	(revision 444)
+++ camel/Makefile.am	(working copy)
@@ -38,6 +38,7 @@
 	-DCAMEL_PROVIDERDIR=\""$(camel_providerdir)"\" 	\
 	-DG_LOG_DOMAIN=\"camel\"			\
 	-DCAMEL_EXPLICIT_TRANSLATION_DOMAIN=\"$(GETTEXT_PACKAGE)\"	\
+	-DE_DATA_SERVER_PREFIX=\"$(prefix)\"		\
 	-DEVOLUTION_LOCALEDIR=\""$(localedir)"\"	\
 	$(CAMEL_CFLAGS)
 
@@ -138,7 +139,7 @@
 
 libcamel_provider_1_2_la_LIBADD =			\
 	$(top_builddir)/libedataserver/libedataserver-${API_VERSION}.la 	\
-	libcamel-$(API_VERSION).la				\
+	libcamel-1.2.la				\
 	$(CAMEL_LIBS)				\
 	$(SOCKET_LIBS)				\
 	$(REGEX_LIBS)
@@ -200,6 +201,7 @@
 	camel-stream-fs.c			\
 	camel-stream-mem.c			\
 	camel-stream-null.c			\
+	camel-stream-vfs.c			\
 	camel-stream.c				\
 	camel-string-utils.c			\
 	camel-text-index.c			\
@@ -269,6 +271,7 @@
 	camel-stream-mem.h			\
 	camel-stream-null.h			\
 	camel-stream-process.h			\
+	camel-stream-vfs.h			\
 	camel-stream.h				\
 	camel-string-utils.h			\
 	camel-text-index.h			\
@@ -301,7 +304,7 @@
 	camel-index-control.c
 
 camel_index_control_1_2_LDADD =			\
-	libcamel-$(API_VERSION).la				\
+	libcamel-1.2.la				\
 	$(libcamel_1_2_la_LIBADD)
 
 camel-mime-tables.c: gentables.pl
Index: camel/camel-tcp-stream-raw.h
===================================================================
--- camel/camel-tcp-stream-raw.h	(revision 444)
+++ camel/camel-tcp-stream-raw.h	(working copy)
@@ -42,6 +42,9 @@
 	CamelTcpStream parent_object;
 	
 	int sockfd;
+#ifdef G_OS_WIN32
+	int is_nonblocking;
+#endif
 };
 
 typedef struct {
Index: camel/camel-mime-filter-gzip.c
===================================================================
--- camel/camel-mime-filter-gzip.c	(revision 444)
+++ camel/camel-mime-filter-gzip.c	(working copy)
@@ -205,12 +205,12 @@
 			fprintf (stderr, "gzip: %d: %s\n", retval, priv->stream->msg);
 		
 		if (flush == Z_FULL_FLUSH) {
-			size_t outlen;
+			size_t n;
 			
-			outlen = filter->outsize - priv->stream->avail_out;
-			camel_mime_filter_set_size (filter, outlen + (priv->stream->avail_in * 2) + 12, TRUE);
-			priv->stream->avail_out = filter->outsize - outlen;
-			priv->stream->next_out = filter->outbuf + outlen;
+			n = filter->outsize - priv->stream->avail_out;
+			camel_mime_filter_set_size (filter, n + (priv->stream->avail_in * 2) + 12, TRUE);
+			priv->stream->avail_out = filter->outsize - n;
+			priv->stream->next_out = filter->outbuf + n;
 			
 			if (priv->stream->avail_in == 0) {
 				guint32 val;
@@ -358,17 +358,17 @@
 			fprintf (stderr, "gunzip: %d: %s\n", retval, priv->stream->msg);
 		
 		if (flush == Z_FULL_FLUSH) {
-			size_t outlen;
+			size_t n;
 			
 			if (priv->stream->avail_in == 0) {
 				/* FIXME: extract & compare calculated crc32 and isize values? */
 				break;
 			}
 			
-			outlen = filter->outsize - priv->stream->avail_out;
-			camel_mime_filter_set_size (filter, outlen + (priv->stream->avail_in * 2) + 12, TRUE);
-			priv->stream->avail_out = filter->outsize - outlen;
-			priv->stream->next_out = filter->outbuf + outlen;
+			n = filter->outsize - priv->stream->avail_out;
+			camel_mime_filter_set_size (filter, n + (priv->stream->avail_in * 2) + 12, TRUE);
+			priv->stream->avail_out = filter->outsize - n;
+			priv->stream->next_out = filter->outbuf + n;
 		} else {
 			priv->stream->avail_in += 8;
 			
Index: camel/camel-session.c
===================================================================
--- camel/camel-session.c	(revision 444)
+++ camel/camel-session.c	(working copy)
@@ -34,17 +34,19 @@
 #include <unistd.h>
 #include <errno.h>
 
+#include <glib/gstdio.h>
+
+#include "libedataserver/e-data-server-util.h"
+#include "camel-exception.h"
+#include "camel-file-utils.h"
+#include "camel-i18n.h"
+#include "camel-private.h"
 #include "camel-session.h"
 #include "camel-store.h"
+#include "camel-string-utils.h"
 #include "camel-transport.h"
-#include "camel-exception.h"
-#include "camel-file-utils.h"
-#include "camel-string-utils.h"
 #include "camel-url.h"
-#include "camel-i18n.h"
 
-#include "camel-private.h"
-
 #define d(x)
 
 #define CS_CLASS(so) ((CamelSessionClass *)((CamelObject *)so)->klass)
@@ -67,6 +69,7 @@
 camel_session_init (CamelSession *session)
 {
 	session->online = TRUE;
+	session->network_state = TRUE;
 	session->priv = g_malloc0(sizeof(*session->priv));
 	
 	session->priv->lock = g_mutex_new();
@@ -277,10 +280,14 @@
 	path = g_strdup_printf ("%s/%s", session->storage_path, p);
 	g_free (p);
 
+#ifdef G_OS_WIN32 
+	if (g_access (path, F_OK) == 0)
+#else
 	if (access (path, F_OK) == 0)
+#endif
 		return path;
 
-	if (camel_mkdir (path, S_IRWXU) == -1) {
+	if (e_util_mkdir_hier (path, S_IRWXU) == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Could not create directory %s:\n%s"),
 				      path, g_strerror (errno));
@@ -554,7 +561,7 @@
 		wait = g_hash_table_lookup(session->priv->thread_active, GINT_TO_POINTER(id)) != NULL;
 		CAMEL_SESSION_UNLOCK(session, thread_lock);
 		if (wait) {
-			usleep(20000);
+			g_usleep(20000);
 		}
 	} while (wait);
 }
@@ -674,3 +681,19 @@
 
 	session->check_junk = check_junk;
 }
+
+gboolean
+camel_session_get_network_state (CamelSession *session)
+{
+	g_return_val_if_fail (CAMEL_IS_SESSION(session), FALSE);
+	
+	return session->network_state;
+}
+
+void
+camel_session_set_network_state (CamelSession *session, gboolean network_state)
+{
+	g_return_if_fail (CAMEL_IS_SESSION(session));
+	
+	session->network_state = network_state;
+}
Index: camel/camel-session.h
===================================================================
--- camel/camel-session.h	(revision 444)
+++ camel/camel-session.h	(working copy)
@@ -56,6 +56,7 @@
 	CAMEL_SESSION_PASSWORD_REPROMPT = 1 << 0,
 	CAMEL_SESSION_PASSWORD_SECRET = 1 << 2,
 	CAMEL_SESSION_PASSWORD_STATIC = 1 << 3,
+	CAMEL_SESSION_PASSPHRASE = 1 << 4,
 };
 
 struct _CamelSession
@@ -66,8 +67,9 @@
 	char *storage_path;
 	CamelJunkPlugin *junk_plugin;
 
-	gboolean online:1;
-	gboolean check_junk:1;
+	guint online:1;
+	guint check_junk:1;
+	guint network_state:1;
 };
 
 typedef struct _CamelSessionThreadOps CamelSessionThreadOps;
@@ -193,7 +195,8 @@
 void camel_session_thread_msg_free(CamelSession *session, CamelSessionThreadMsg *msg);
 int camel_session_thread_queue(CamelSession *session, CamelSessionThreadMsg *msg, int flags);
 void camel_session_thread_wait(CamelSession *session, int id);
-
+gboolean camel_session_get_network_state (CamelSession *session);
+void camel_session_set_network_state (CamelSession *session, gboolean network_state);
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
Index: camel/camel-multipart-signed.c
===================================================================
--- camel/camel-multipart-signed.c	(revision 444)
+++ camel/camel-multipart-signed.c	(working copy)
@@ -29,27 +29,25 @@
 #endif
 
 #include <stdio.h>
-
 #include <string.h>
 #include <unistd.h>
 #include <time.h>
-
 #include <errno.h>
 
-#include "camel-mime-part.h"
+#include "libedataserver/md5-utils.h"
+
+#include "camel-exception.h"
+#include "camel-i18n.h"
+#include "camel-mime-filter-canon.h"
+#include "camel-mime-filter-crlf.h"
 #include "camel-mime-message.h"
 #include "camel-mime-parser.h"
-#include "camel-stream-mem.h"
-#include "camel-multipart-signed.h"
 #include "camel-mime-part.h"
-#include "camel-exception.h"
-#include "libedataserver/md5-utils.h"
-
-#include "camel-stream-filter.h"
+#include "camel-mime-part.h"
+#include "camel-multipart-signed.h"
 #include "camel-seekable-substream.h"
-#include "camel-mime-filter-crlf.h"
-#include "camel-mime-filter-canon.h"
-#include "camel-i18n.h"
+#include "camel-stream-filter.h"
+#include "camel-stream-mem.h"
 
 #define d(x) /*(printf("%s(%d): ", __FILE__, __LINE__),(x))
 	       #include <stdio.h>;*/
@@ -209,7 +207,7 @@
 		case CAMEL_MIME_PARSER_STATE_MESSAGE_END:
 			break;
 		default:
-			g_error ("Bad parser state: Expecing MESSAGE_END or EOF or EOM, got: %d", camel_mime_parser_state (cmp));
+			g_error ("Bad parser state: Expecting MESSAGE_END or EOF or EOM, got: %u", camel_mime_parser_state (cmp));
 			camel_mime_parser_unstep(cmp);
 			return -1;
 		}
@@ -220,7 +218,7 @@
 			skip_content(cmp);
 		break;
 	default:
-		g_warning("Invalid state encountered???: %d", camel_mime_parser_state(cmp));
+		g_warning("Invalid state encountered???: %u", camel_mime_parser_state (cmp));
 	}
 
 	return 0;
@@ -235,7 +233,6 @@
 	const char *boundary;
 	char *buf;
 	size_t len;
-	off_t head = -1, tail = -1;
 	int state;
 
 	boundary = camel_multipart_get_boundary(mp);
@@ -266,7 +263,6 @@
 
 	while ((state = camel_mime_parser_step(cmp, &buf, &len)) != CAMEL_MIME_PARSER_STATE_MULTIPART_END) {
 		if (mps->start1 == -1) {
-			head = camel_mime_parser_tell_start_boundary(cmp);
 			mps->start1 = camel_mime_parser_tell_start_headers(cmp);
 		} else if (mps->start2 == -1) {
 			mps->start2 = camel_mime_parser_tell_start_headers(cmp);
@@ -286,8 +282,7 @@
 
 	if (state == CAMEL_MIME_PARSER_STATE_MULTIPART_END) {
 		mps->end2 = camel_mime_parser_tell_start_boundary(cmp);
-		tail = camel_mime_parser_tell(cmp);
-
+		
 		camel_multipart_set_preface(mp, camel_mime_parser_preface(cmp));
 		camel_multipart_set_postface(mp, camel_mime_parser_postface(cmp));
 	}
Index: camel/camel-text-index.c
===================================================================
--- camel/camel-text-index.c	(revision 444)
+++ camel/camel-text-index.c	(working copy)
@@ -33,18 +33,19 @@
 #include <fcntl.h>
 #include <ctype.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
 #include "libedataserver/e-msgport.h"
 #include "libedataserver/e-memory.h"
 
-#include "camel/camel-object.h"
-
-#include "camel-text-index.h"
 #include "camel-block-file.h"
+#include "camel-object.h"
 #include "camel-partition-table.h"
+#include "camel-private.h"
+#include "camel-text-index.h"
 
-#include <glib/gunicode.h>
 
-
 #define w(x)
 #define io(x) 
 #define d(x) /*(printf("%s(%d):%s: ",  __FILE__, __LINE__, __PRETTY_FUNCTION__),(x))*/
@@ -513,9 +514,9 @@
 
 	/* clean up temp files always */
 	sprintf(savepath, "%s~.index", oldpath);
-	unlink(savepath);
+	g_unlink(savepath);
 	sprintf(newpath, "%s.data", savepath);
-	unlink(newpath);
+	g_unlink(newpath);
 
 	return ret;
 }
@@ -932,17 +933,17 @@
 	sprintf(oldname, "%s.index", old);
 	sprintf(newname, "%s.index", new);
 
-	if (rename(oldname, newname) == -1 && errno != ENOENT)
+	if (g_rename(oldname, newname) == -1 && errno != ENOENT)
 		return -1;
 
 	sprintf(oldname, "%s.index.data", old);
 	sprintf(newname, "%s.index.data", new);
 
-	if (rename(oldname, newname) == -1 && errno != ENOENT) {
+	if (g_rename(oldname, newname) == -1 && errno != ENOENT) {
 		err = errno;
 		sprintf(oldname, "%s.index", old);
 		sprintf(newname, "%s.index", new);
-		rename(newname, oldname);
+		g_rename(newname, oldname);
 		errno = err;
 		return -1;
 	}
@@ -963,9 +964,9 @@
 	sprintf(block, "%s.index", old);
 	sprintf(key, "%s.index.data", old);
 
-	if (unlink(block) == -1 && errno != ENOENT)
+	if (g_unlink(block) == -1 && errno != ENOENT)
 		ret = -1;
-	if (unlink(key) == -1 && errno != ENOENT)
+	if (g_unlink(key) == -1 && errno != ENOENT)
 		ret = -1;
 
 	return ret;
@@ -980,12 +981,12 @@
 	int frag;
 
 	printf("Path: '%s'\n", idx->parent.path);
-	printf("Version: %d\n", idx->parent.version);
+	printf("Version: %u\n", idx->parent.version);
 	printf("Flags: %08x\n", idx->parent.flags);
-	printf("Total words: %d\n", rb->words);
-	printf("Total names: %d\n", rb->names);
-	printf("Total deleted: %d\n", rb->deleted);
-	printf("Total key blocks: %d\n", rb->keys);
+	printf("Total words: %u\n", rb->words);
+	printf("Total names: %u\n", rb->names);
+	printf("Total deleted: %u\n", rb->deleted);
+	printf("Total key blocks: %u\n", rb->keys);
 
 	if (rb->words > 0) {
 		frag = ((rb->keys - rb->words) * 100)/ rb->words;
@@ -1090,7 +1091,7 @@
 	int fd;
 	camel_block_t id, total;
 
-	fd = open(path, O_RDONLY);
+	fd = g_open(path, O_RDONLY|O_BINARY, 0);
 	if (fd == -1)
 		return;
 
@@ -1334,7 +1335,7 @@
 		while (data) {
 			printf(" data %x ", data);
 			if (camel_key_file_read(p->links, &data, &count, &records) == -1) {
-				printf("Warning, read failed for word '%s', at data '%d'\n", word, data);
+				printf("Warning, read failed for word '%s', at data '%u'\n", word, data);
 				data = 0;
 			} else {
 				printf("(%d)\n", (int)count);
Index: camel/camel.c
===================================================================
--- camel/camel.c	(revision 444)
+++ camel/camel.c	(working copy)
@@ -37,10 +37,10 @@
 
 #include "camel.h"
 #include "camel-certdb.h"
+#include "camel-debug.h"
 #include "camel-i18n.h"
-#include "camel-mime-utils.h"
 #include "camel-provider.h"
-#include "camel-debug.h"
+#include "camel-private.h"
 
 static int initialised = FALSE;
 
@@ -52,7 +52,10 @@
 	if (!initialised)
 		return;
 	
-#ifdef HAVE_NSS
+#if defined (HAVE_NSS) && !defined (G_OS_WIN32)
+	/* For some reason we get into trouble on Win32 if we call these.
+	 * But they shouldn't be necessary as the process is exiting anywy?
+	 */
 	NSS_Shutdown ();
 	
 	PR_Cleanup ();
@@ -86,16 +89,24 @@
 
 #ifdef HAVE_NSS
 	if (nss_init) {
+		char *nss_configdir;
+
 		PR_Init (PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 10);
 		
-		if (NSS_InitReadWrite (configdir) == SECFailure) {
+#ifndef G_OS_WIN32
+		nss_configdir = g_strdup (configdir);
+#else
+		nss_configdir = g_win32_locale_filename_from_utf8 (configdir);
+#endif
+
+		if (NSS_InitReadWrite (nss_configdir) == SECFailure) {
 			/* fall back on using volatile dbs? */
-			if (NSS_NoDB_Init (configdir) == SECFailure) {
+			if (NSS_NoDB_Init (nss_configdir) == SECFailure) {
 				g_warning ("Failed to initialize NSS");
 				return -1;
 			}
 		}
-		
+
 		NSS_SetDomesticPolicy ();
 		
 		SSL_OptionSetDefault (SSL_ENABLE_SSL2, PR_TRUE);
@@ -118,22 +129,7 @@
 	
 	camel_object_unref (certdb);
 	
-#ifndef G_OS_WIN32
 	g_atexit (camel_shutdown);
-#else
-	/* In GLib (<= 2.8.0 at least, might get fixed later),
-	 * g_atexit() is a function in the GLib DLL that calls the
-	 * atexit() in the C runtime DLL. atexit() is implemented so
-	 * that registered function will be called when the DLL
-	 * containing the calling function is being detached from a
-	 * process (not when exit() is called).
-	 *
-	 * We want to run camel_shutdown when the the process exits,
-	 * or at least when the camel DLL is being detached, not when
-	 * the GLib DLL is being detached.
-	 */
-	atexit (camel_shutdown);
-#endif
 	
 	initialised = TRUE;
 	
Index: camel/camel-junk-plugin.c
===================================================================
--- camel/camel-junk-plugin.c	(revision 444)
+++ camel/camel-junk-plugin.c	(working copy)
@@ -22,10 +22,11 @@
 
 #include <stdio.h>
 #include <glib.h>
-#include <camel/camel-debug.h>
-#include <camel/camel-junk-plugin.h>
-#include <camel/camel-mime-message.h>
 
+#include "camel-debug.h"
+#include "camel-junk-plugin.h"
+#include "camel-mime-message.h"
+
 #define d(x) (camel_debug("junk")?(x):0)
 
 const char *
Index: camel/camel-certdb.c
===================================================================
--- camel/camel-certdb.c	(revision 444)
+++ camel/camel-certdb.c	(working copy)
@@ -35,14 +35,14 @@
 #include <fcntl.h>
 #include <errno.h>
 
+#include <glib/gstdio.h>
+
 #include "camel-certdb.h"
+#include "camel-file-utils.h"
 #include "camel-private.h"
 
-#include <camel/camel-file-utils.h>
+#include "libedataserver/e-memory.h"
 
-#include <libedataserver/e-memory.h>
-
-
 #define CAMEL_CERTDB_GET_CLASS(db)  ((CamelCertDBClass *) CAMEL_OBJECT_GET_CLASS (db))
 
 #define CAMEL_CERTDB_VERSION  0x100
@@ -261,7 +261,7 @@
 	g_return_val_if_fail (CAMEL_IS_CERTDB (certdb), -1);
 	g_return_val_if_fail (certdb->filename, -1);
 
-	in = fopen (certdb->filename, "r");
+	in = g_fopen (certdb->filename, "rb");
 	if (in == NULL)
 		return -1;
 	
@@ -340,15 +340,15 @@
 	filename = alloca (strlen (certdb->filename) + 4);
 	sprintf (filename, "%s~", certdb->filename);
 	
-	fd = open (filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
+	fd = g_open (filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
 	if (fd == -1)
 		return -1;
 	
-	out = fdopen (fd, "w");
+	out = fdopen (fd, "wb");
 	if (out == NULL) {
 		i = errno;
 		close (fd);
-		unlink (filename);
+		g_unlink (filename);
 		errno = i;
 		return -1;
 	}
@@ -371,21 +371,21 @@
 	if (fflush (out) != 0 || fsync (fileno (out)) == -1) {
 		i = errno;
 		fclose (out);
-		unlink (filename);
+		g_unlink (filename);
 		errno = i;
 		return -1;
 	}
 	
 	if (fclose (out) != 0) {
 		i = errno;
-		unlink (filename);
+		g_unlink (filename);
 		errno = i;
 		return -1;
 	}
 	
-	if (rename (filename, certdb->filename) == -1) {
+	if (g_rename (filename, certdb->filename) == -1) {
 		i = errno;
-		unlink (filename);
+		g_unlink (filename);
 		errno = i;
 		return -1;
 	}
@@ -402,7 +402,7 @@
 	
 	i = errno;
 	fclose (out);
-	unlink (filename);
+	g_unlink (filename);
 	errno = i;
 	
 	return -1;
Index: camel/camel-charset-map.c
===================================================================
--- camel/camel-charset-map.c	(revision 444)
+++ camel/camel-charset-map.c	(working copy)
@@ -152,7 +152,7 @@
 		}
 	}
 
-	printf("const struct {\n");
+	printf("static const struct {\n");
 	for (k=0;k<bytes;k++) {
 		printf("\tconst unsigned char *bits%d;\n", k);
 	}
@@ -168,7 +168,7 @@
 			if (j < 256) {
 				printf("m%02x%x, ", i, k);
 			} else {
-				printf("0, ");
+				printf("NULL, ");
 			}
 		}
 		printf("}, ");
@@ -177,7 +177,7 @@
 	}
 	printf("\n};\n\n");
 
-	printf("const struct {\n\tconst char *name;\n\tunsigned int bit;\n} camel_charinfo[] = {\n");
+	printf("static const struct {\n\tconst char *name;\n\tunsigned int bit;\n} camel_charinfo[] = {\n");
 	for (j=0;tables[j].name;j++) {
 		printf("\t{ \"%s\", 0x%04x },\n", tables[j].name, tables[j].bit);
 	}
@@ -222,19 +222,20 @@
 void
 camel_charset_step (CamelCharset *cc, const char *in, int len)
 {
+	const unsigned char *inptr = (const unsigned char *) in;
+	const unsigned char *inend = inptr + len;
 	register unsigned int mask;
 	register int level;
-	const unsigned char *inptr = in, *inend = in+len;
 	register guint32 c;
-
+	
 	mask = cc->mask;
 	level = cc->level;
-
+	
 	/* check what charset a given string will fit in */
-	while ( (c = camel_utf8_getc_limit(&inptr, inend)) != 0xffff) {
+	while ((c = camel_utf8_getc_limit(&inptr, inend)) != 0xffff) {
 		if (c < 0xffff) {
 			mask &= charset_mask(c);
-		
+			
 			if (c>=128 && c<256)
 				level = MAX(level, 1);
 			else if (c>=256)
@@ -245,7 +246,7 @@
 			break;
 		}
 	}
-
+	
 	cc->mask = mask;
 	cc->level = level;
 }
@@ -262,7 +263,7 @@
 		if (camel_charinfo[i].bit & mask) {
 			lang = e_iconv_charset_language (camel_charinfo[i].name);
 			
-			if (!lang || (locale_lang && !strncmp (locale_lang, lang, 2)))
+			if (!locale_lang || (lang && !strncmp (locale_lang, lang, 2)))
 				return camel_charinfo[i].name;
 		}
 	}
Index: camel/camel-lock-helper.c
===================================================================
--- camel/camel-lock-helper.c	(revision 444)
+++ camel/camel-lock-helper.c	(working copy)
@@ -188,7 +188,7 @@
 	info->id = lock_id;
 	info->depth = 1;
 	info->next = lock_info_list;
-	info->stamp = time(0);
+	info->stamp = time (NULL);
 	lock_info_list = info;
 
 	if (lockid)
@@ -306,7 +306,7 @@
 
 		/* check the minimum timeout we need to refresh the next oldest lock */
 		if (lock_info_list) {
-			time_t now = time(0);
+			time_t now = time (NULL);
 			time_t left;
 			time_t delay = CAMEL_DOT_LOCK_REFRESH;
 
@@ -332,7 +332,7 @@
 
 		/* did we get a timeout?  scan for any locks that need updating */
 		if (!FD_ISSET(STDIN_FILENO, &rset)) {
-			time_t now = time(0);
+			time_t now = time (NULL);
 			time_t left;
 
 			d(fprintf(stderr, "Got a timeout, checking locks\n"));
Index: camel/camel-list-utils.c
===================================================================
--- camel/camel-list-utils.c	(revision 444)
+++ camel/camel-list-utils.c	(working copy)
@@ -38,7 +38,7 @@
 void camel_dlist_init(CamelDList *v)
 {
         v->head = (CamelDListNode *)&v->tail;
-        v->tail = 0;
+        v->tail = NULL;
         v->tailpred = (CamelDListNode *)&v->head;
 }
 
Index: camel/camel-mime-filter-html.c
===================================================================
--- camel/camel-mime-filter-html.c	(revision 444)
+++ camel/camel-mime-filter-html.c	(working copy)
@@ -1,3 +1,4 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
 /*
  *  Copyright (C) 2001 Ximian Inc.
  *
@@ -111,19 +112,19 @@
 }
 
 static void
-run(CamelMimeFilter *mf, char *in, size_t len, size_t prespace, char **out, size_t *outlenptr, size_t *outprespace, int last)
+run(CamelMimeFilter *mf, char *in, size_t inlen, size_t prespace, char **out, size_t *outlenptr, size_t *outprespace, int last)
 {
+	CamelMimeFilterHTML *f = (CamelMimeFilterHTML *) mf;
 	camel_html_parser_t state;
 	char *outp;
-	CamelMimeFilterHTML *f = (CamelMimeFilterHTML *)mf;
-
-	d(printf("converting html:\n%.*s\n", (int)len, in));
 	
+	d(printf("converting html:\n%.*s\n", (int)inlen, in));
+	
 	/* We should generally shrink the data, but this'll do */
-	camel_mime_filter_set_size(mf, len*2+256, FALSE);
+	camel_mime_filter_set_size (mf, inlen * 2 + 256, FALSE);
 	outp = mf->outbuf;
-
-	camel_html_parser_set_data(f->priv->ctxt, in, len, last);
+	
+	camel_html_parser_set_data (f->priv->ctxt, in, inlen, last);
 	do {
 		const char *data;
 		int len;
Index: camel/camel-utf8.c
===================================================================
--- camel/camel-utf8.c	(revision 444)
+++ camel/camel-utf8.c	(working copy)
@@ -29,10 +29,9 @@
 #include <string.h>
 
 #include <glib.h>
+
 #include "camel-utf8.h"
 
-#include <netinet/in.h>
-
 /**
  * camel_utf8_putc:
  * @ptr: 
@@ -147,7 +146,7 @@
 			do {
 				if (p >= end)
 					return 0xffff;
-
+				
 				c = *p++;
 				if ((c & 0xc0) != 0x80) {
 					r = c;
@@ -157,7 +156,7 @@
 				r<<=1;
 				m<<=5;
 			} while (r & 0x40);
-		
+			
 			*ptr = p;
 			
 			v &= ~m;
@@ -362,7 +361,7 @@
 	/* what if c is > 0xffff ? */
 
 	while ( (c = camel_utf8_getc((const unsigned char **)&ptr)) ) {
-		guint16 s = htons(c);
+		guint16 s = g_htons(c);
 
 		g_byte_array_append(work, (char *)&s, 2);
 	}
@@ -392,7 +391,7 @@
 	char *out;
 
 	while ( (c = *ucs++) )
-		g_string_append_u(work, ntohs(c));
+		g_string_append_u(work, g_ntohs(c));
 
 	out = g_strdup(work->str);
 	g_string_free(work, TRUE);
Index: camel/camel-store-summary.c
===================================================================
--- camel/camel-store-summary.c	(revision 444)
+++ camel/camel-store-summary.c	(working copy)
@@ -32,14 +32,14 @@
 #include <fcntl.h>
 #include <errno.h>
 
-#include "camel-store-summary.h"
+#include <glib/gstdio.h>
 
-#include "camel-file-utils.h"
-
 #include "libedataserver/md5-utils.h"
 #include "libedataserver/e-memory.h"
 
+#include "camel-file-utils.h"
 #include "camel-private.h"
+#include "camel-store-summary.h"
 #include "camel-url.h"
 
 #define d(x)
@@ -366,7 +366,7 @@
 
 	g_assert(s->summary_path);
 
-	in = fopen(s->summary_path, "r");
+	in = g_fopen(s->summary_path, "rb");
 	if (in == NULL)
 		return -1;
 
@@ -432,12 +432,12 @@
 		return 0;
 	}
 
-	fd = open(s->summary_path, O_RDWR|O_CREAT|O_TRUNC, 0600);
+	fd = g_open(s->summary_path, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0600);
 	if (fd == -1) {
 		io(printf("**  open error: %s\n", strerror (errno)));
 		return -1;
 	}
-	out = fdopen(fd, "w");
+	out = fdopen(fd, "wb");
 	if ( out == NULL ) {
 		i = errno;
 		printf("**  fdopen error: %s\n", strerror (errno));
@@ -503,7 +503,7 @@
 
 	g_assert(s->summary_path);
 
-	in = fopen(s->summary_path, "r");
+	in = g_fopen(s->summary_path, "rb");
 	if (in == NULL)
 		return -1;
 
Index: camel/camel-sasl-popb4smtp.c
===================================================================
--- camel/camel-sasl-popb4smtp.c	(revision 444)
+++ camel/camel-sasl-popb4smtp.c	(working copy)
@@ -28,10 +28,10 @@
 #include <string.h>
 #include <time.h>
 
+#include "camel-i18n.h"
 #include "camel-sasl-popb4smtp.h"
 #include "camel-service.h"
 #include "camel-session.h"
-#include "camel-i18n.h"
 
 CamelServiceAuthType camel_sasl_popb4smtp_authtype = {
 	N_("POP before SMTP"),
@@ -108,7 +108,7 @@
 		return NULL;
 	}
 
-	if (strncasecmp(popuri, "pop:", 4) != 0) {
+	if (g_ascii_strncasecmp(popuri, "pop:", 4) != 0) {
 		camel_exception_setv(ex, 1, _("POP Before SMTP auth using a non-pop source"));
 		return NULL;
 	}
Index: camel/camel-sasl-anonymous.c
===================================================================
--- camel/camel-sasl-anonymous.c	(revision 444)
+++ camel/camel-sasl-anonymous.c	(working copy)
@@ -26,10 +26,10 @@
 #endif
 
 #include <string.h>
+
+#include "camel-i18n.h"
+#include "camel-internet-address.h"
 #include "camel-sasl-anonymous.h"
-#include "camel-internet-address.h"
-#include <string.h>
-#include "camel-i18n.h"
 
 CamelServiceAuthType camel_sasl_anonymous_authtype = {
 	N_("Anonymous"),
Index: camel/camel-mime-filter-basic.c
===================================================================
--- camel/camel-mime-filter-basic.c	(revision 444)
+++ camel/camel-mime-filter-basic.c	(working copy)
@@ -19,10 +19,10 @@
  * Boston, MA 02111-1307, USA.
  */
 
+#include <string.h>
+
 #include "camel-mime-filter-basic.h"
-
 #include "camel-mime-utils.h"
-#include <string.h>
 
 static void reset(CamelMimeFilter *mf);
 static void complete(CamelMimeFilter *mf, char *in, size_t len, 
@@ -138,7 +138,7 @@
 		}
 		break;
 	default:
-		g_warning("unknown type %d in CamelMimeFilterBasic", f->type);
+		g_warning ("unknown type %u in CamelMimeFilterBasic", f->type);
 		goto donothing;
 	}
 
@@ -236,7 +236,7 @@
 		}
 		break;
 	default:
-		g_warning("unknown type %d in CamelMimeFilterBasic", f->type);
+		g_warning ("unknown type %u in CamelMimeFilterBasic", f->type);
 		goto donothing;
 	}
 
@@ -291,7 +291,7 @@
 		new->type = type;
 		break;
 	default:
-		g_warning("Invalid type of CamelMimeFilterBasic requested: %d", type);
+		g_warning ("Invalid type of CamelMimeFilterBasic requested: %u", type);
 		new = NULL;
 		break;
 	}
Index: camel/camel-mime-filter-enriched.c
===================================================================
--- camel/camel-mime-filter-enriched.c	(revision 444)
+++ camel/camel-mime-filter-enriched.c	(working copy)
@@ -28,9 +28,8 @@
 #include <stdio.h>
 #include <string.h>
 
-#include <camel/camel-string-utils.h>
-
 #include "camel-mime-filter-enriched.h"
+#include "camel-string-utils.h"
 
 /* text/enriched is rfc1896 */
 
@@ -40,11 +39,11 @@
 static char *param_parse_font (const char *inptr, int inlen);
 static char *param_parse_lang (const char *inptr, int inlen);
 
-static const struct {
-	const char *enriched;
-	const char *html;
-	const gboolean needs_param;
-	const EnrichedParamParser parse_param; /* parses *and* validates the input */
+static struct {
+	char *enriched;
+	char *html;
+	gboolean needs_param;
+	EnrichedParamParser parse_param; /* parses *and* validates the input */
 } enriched_tags[] = {
 	{ "bold",        "<b>",                 FALSE, NULL               },
 	{ "/bold",       "</b>",                FALSE, NULL               },
@@ -197,7 +196,7 @@
 	int i;
 	
 	for (i = 0; i < NUM_VALID_COLOURS; i++) {
-		if (!strncasecmp (inptr, valid_colours[i], inlen))
+		if (!g_ascii_strncasecmp (inptr, valid_colours[i], inlen))
 			return g_strdup (valid_colours[i]);
 	}
 	
@@ -406,14 +405,14 @@
 				goto need_input;
 			}
 			
-			if (!strncasecmp (tag, "nofill>", 7)) {
+			if (!g_ascii_strncasecmp (tag, "nofill>", 7)) {
 				if ((outptr + 5) < outend) {
 					enriched->nofill++;
 				} else {
 					inptr = tag - 1;
 					goto backup;
 				}
-			} else if (!strncasecmp (tag, "/nofill>", 8)) {
+			} else if (!g_ascii_strncasecmp (tag, "/nofill>", 8)) {
 				if ((outptr + 6) < outend) {
 					enriched->nofill--;
 				} else {
@@ -445,7 +444,7 @@
 							goto need_input;
 						}
 						
-						if (strncasecmp (inptr, "<param>", 7) != 0) {
+						if (g_ascii_strncasecmp (inptr, "<param>", 7) != 0) {
 							/* ignore the enriched command tag... */
 							inptr -= 1;
 							goto loop;
@@ -462,7 +461,7 @@
 							goto need_input;
 						}
 						
-						if (strncasecmp (inptr, "</param>", 8) != 0) {
+						if (g_ascii_strncasecmp (inptr, "</param>", 8) != 0) {
 							/* ignore the enriched command tag... */
 							inptr += 7;
 							goto loop;
Index: camel/camel-url-scanner.c
===================================================================
--- camel/camel-url-scanner.c	(revision 444)
+++ camel/camel-url-scanner.c	(working copy)
@@ -30,8 +30,9 @@
 #include <ctype.h>
 
 #include "libedataserver/e-trie.h"
+
+#include "camel-url-scanner.h"
 #include "camel-utf8.h"
-#include "camel-url-scanner.h"
 
 
 struct _CamelUrlScanner {
@@ -196,7 +197,8 @@
 	
 	g_assert (*inptr == '@');
 	
-	inptr--;
+	if (inptr > in)
+		inptr--;
 	
 	while (inptr > in) {
 		if (is_atom (*inptr))
@@ -211,10 +213,10 @@
 			inptr--;
 	}
 	
-	if (!is_atom (*inptr) || is_open_brace (*inptr))
+	while (!is_atom (*inptr) || is_open_brace (*inptr))
 		inptr++;
 	
-	if (inptr == pos)
+	if (inptr >= pos)
 		return FALSE;
 	
 	match->um_so = (inptr - in);
@@ -355,8 +357,8 @@
 			while (inptr < inend && is_atom (*inptr))
 				inptr++;
 			
-			if ((inptr + 1) < inend && *inptr == '.' && is_atom (inptr[1]))
-				inptr++;
+			if ((inptr + 1) < inend && *inptr == '.' && (is_atom (inptr[1]) || inptr[1] == '/')) 
+					inptr++;
 		}
 		
 		if (*inptr != '@')
@@ -376,8 +378,8 @@
 			while (inptr < inend && is_domain (*inptr))
 				inptr++;
 			
-			if ((inptr + 1) < inend && *inptr == '.' && is_domain (inptr[1]))
-				inptr++;
+			if ((inptr + 1) < inend && *inptr == '.' && (is_domain (inptr[1]) || inptr[1] == '/')) 
+					inptr++;
 		}
 	} else {
 		return FALSE;
Index: camel/camel-exception.c
===================================================================
--- camel/camel-exception.c	(revision 444)
+++ camel/camel-exception.c	(working copy)
@@ -156,12 +156,10 @@
  * simply returns.
  **/
 void
-camel_exception_set (CamelException *ex,
-		     ExceptionId id,
-		     const char *desc)
+camel_exception_set (CamelException *ex, ExceptionId id, const char *desc)
 {
 	if (camel_debug("exception"))
-		printf("CamelException.set(%p, %d, '%s')\n", ex, id, desc);
+		printf("CamelException.set(%p, %u, '%s')\n", ex, id, desc);
 
 	if (!ex)
 		return;
@@ -199,10 +197,7 @@
  * simply returns.
  **/
 void
-camel_exception_setv (CamelException *ex,
-		      ExceptionId id,
-		      const char *format, 
-		      ...)
+camel_exception_setv (CamelException *ex, ExceptionId id, const char *format, ...)
 {
 	va_list args;
 	char *desc;
@@ -212,7 +207,7 @@
 	va_end (args);
 
 	if (camel_debug("exception"))
-		printf("CamelException.setv(%p, %d, '%s')\n", ex, id, desc);
+		printf("CamelException.setv(%p, %u, '%s')\n", ex, id, desc);
 	
 	if (!ex) {
 		g_free(desc);
Index: camel/camel-stream-fs.c
===================================================================
--- camel/camel-stream-fs.c	(revision 444)
+++ camel/camel-stream-fs.c	(working copy)
@@ -29,12 +29,14 @@
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
-#include <fcntl.h>
 #include <errno.h>
 #include <string.h>
 
+#include <glib/gstdio.h>
+
 #include "camel-file-utils.h"
 #include "camel-operation.h"
+#include "camel-private.h"
 #include "camel-stream-fs.h"
 
 static CamelSeekableStreamClass *parent_class = NULL;
@@ -172,7 +174,7 @@
 {
 	int fd;
 
-	fd = open (name, flags, mode);
+	fd = g_open (name, flags|O_BINARY, mode);
 	if (fd == -1) {
 		return NULL;
 	}
Index: camel/camel-sasl-digest-md5.c
===================================================================
--- camel/camel-sasl-digest-md5.c	(revision 444)
+++ camel/camel-sasl-digest-md5.c	(working copy)
@@ -29,15 +29,14 @@
 #include <ctype.h>
 #include <unistd.h>
 
-#include <libedataserver/md5-utils.h>
+#include "libedataserver/e-iconv.h"
+#include "libedataserver/md5-utils.h"
 
-#include <libedataserver/e-iconv.h>
-
 #include "camel-charset-map.h"
-#include "camel-mime-utils.h"
-#include "camel-sasl-digest-md5.h"
 #include "camel-i18n.h"
+#include "camel-mime-utils.h"
 #include "camel-net-utils.h"
+#include "camel-sasl-digest-md5.h"
 
 #define d(x)
 
@@ -765,7 +764,7 @@
 	
 	if (resp->maxbuf > 0) {
 		g_byte_array_append (buffer, ",maxbuf=", 8);
-		buf = g_strdup_printf ("%d", resp->maxbuf);
+		buf = g_strdup_printf ("%u", resp->maxbuf);
 		g_byte_array_append (buffer, buf, strlen (buf));
 		g_free (buf);
 	}
Index: camel/camel-string-utils.c
===================================================================
--- camel/camel-string-utils.c	(revision 444)
+++ camel/camel-string-utils.c	(working copy)
@@ -88,7 +88,7 @@
 		return (char *) haystack;
 	
 	for (ptr = haystack; *(ptr + len - 1) != '\0'; ptr++)
-		if (!strncasecmp (ptr, needle, len))
+		if (!g_ascii_strncasecmp (ptr, needle, len))
 			return (char *) ptr;
 	
 	return NULL;
@@ -146,6 +146,54 @@
 static GHashTable *pstring_table = NULL;
 
 /**
+ * camel_pstring_add:
+ * @str: string to add to the string pool
+ * @own: whether the string pool will own the memory pointed to by @str, if @str is not yet in the pool
+ *
+ * Add the string to the pool.
+ *
+ * The NULL and empty strings are special cased to constant values.
+ *
+ * Return value: A pointer to an equivalent string of @s.  Use
+ * camel_pstring_free() when it is no longer needed.
+ **/
+const char *
+camel_pstring_add (char *str, gboolean own)
+{
+	void *pcount;
+	char *pstr;
+	int count;
+	
+	if (str == NULL)
+		return NULL;
+	
+	if (str[0] == '\0') {
+		if (own)
+			g_free (str);
+		return "";
+	}
+	
+	pthread_mutex_lock (&pstring_lock);
+	if (pstring_table == NULL)
+		pstring_table = g_hash_table_new (g_str_hash, g_str_equal);
+	
+	if (g_hash_table_lookup_extended (pstring_table, str, (void **) &pstr, &pcount)) {
+		count = GPOINTER_TO_INT (pcount) + 1;
+		g_hash_table_insert (pstring_table, pstr, GINT_TO_POINTER (count));
+		if (own)
+			g_free (str);
+	} else {
+		pstr = own ? str : g_strdup (str);
+		g_hash_table_insert (pstring_table, pstr, GINT_TO_POINTER (1));
+	}
+	
+	pthread_mutex_unlock (&pstring_lock);
+	
+	return pstr;
+}
+
+
+/**
  * camel_pstring_strdup:
  * @s: String to copy.
  * 
@@ -159,33 +207,13 @@
  * Return value: A pointer to an equivalent string of @s.  Use
  * camel_pstring_free() when it is no longer needed.
  **/
-const char *camel_pstring_strdup(const char *s)
+const char *
+camel_pstring_strdup (const char *s)
 {
-	char *p;
-	void *pcount;
-	int count;
+	return camel_pstring_add ((char *) s, FALSE);
+}
 
-	if (s == NULL)
-		return NULL;
-	if (s[0] == 0)
-		return "";
 
-	pthread_mutex_lock(&pstring_lock);
-	if (pstring_table == NULL)
-		pstring_table = g_hash_table_new(g_str_hash, g_str_equal);
-
-	if (g_hash_table_lookup_extended(pstring_table, s, (void **)&p, &pcount)) {
-		count = GPOINTER_TO_INT(pcount)+1;
-		g_hash_table_insert(pstring_table, p, GINT_TO_POINTER(count));
-	} else {
-		p = g_strdup(s);
-		g_hash_table_insert(pstring_table, p, GINT_TO_POINTER(1));
-	}
-	pthread_mutex_unlock(&pstring_lock);
-
-	return p;
-}
-
 /**
  * camel_pstring_free:
  * @s: String to free.
@@ -194,7 +222,8 @@
  *
  * NULL and the empty string are special cased.
  **/
-void camel_pstring_free(const char *s)
+void
+camel_pstring_free(const char *s)
 {
 	char *p;
 	void *pcount;
Index: camel/camel-string-utils.h
===================================================================
--- camel/camel-string-utils.h	(revision 444)
+++ camel/camel-string-utils.h	(working copy)
@@ -42,6 +42,7 @@
 char camel_tolower(char c);
 char camel_toupper(char c);
 
+const char *camel_pstring_add (char *str, gboolean own);
 const char *camel_pstring_strdup(const char *s);
 void camel_pstring_free(const char *s);
 
Index: camel/camel-mime-message.c
===================================================================
--- camel/camel-mime-message.c	(revision 444)
+++ camel/camel-mime-message.c	(working copy)
@@ -32,20 +32,28 @@
 #include <string.h>
 #include <errno.h>
 
-#include <libedataserver/e-iconv.h>
-#include <libedataserver/e-time-utils.h>
+#include "libedataserver/e-iconv.h"
+#include "libedataserver/e-time-utils.h"
 
+#include "camel-mime-filter-bestenc.h"
+#include "camel-mime-filter-charset.h"
 #include "camel-mime-message.h"
 #include "camel-multipart.h"
+#include "camel-stream-filter.h"
 #include "camel-stream-mem.h"
+#include "camel-stream-null.h"
 #include "camel-string-utils.h"
 #include "camel-url.h"
 
-#include "camel-stream-filter.h"
-#include "camel-stream-null.h"
-#include "camel-mime-filter-charset.h"
-#include "camel-mime-filter-bestenc.h"
+#ifdef G_OS_WIN32
+/* Undef the similar macro from pthread.h, it doesn't check if
+ * gmtime() returns NULL.
+ */
+#undef gmtime_r
 
+/* The gmtime() in Microsoft's C library is MT-safe */
+#define gmtime_r(tp,tmp) (gmtime(tp)?(*(tmp)=*gmtime(tp),(tmp)):0)
+#endif
 #define d(x)
 
 extern int camel_verbose_debug;
@@ -592,7 +600,7 @@
 	case CAMEL_MIME_PARSER_STATE_MESSAGE_END:
 		break;
 	default:
-		g_error ("Bad parser state: Expecing MESSAGE_END or EOF or EOM, got: %d", camel_mime_parser_state (mp));
+		g_error ("Bad parser state: Expecing MESSAGE_END or EOF or EOM, got: %u", camel_mime_parser_state (mp));
 		camel_mime_parser_unstep (mp);
 		return -1;
 	}
@@ -754,9 +762,9 @@
 	if (CAMEL_IS_MULTIPART (containee)) {
 		parts = camel_multipart_get_number (CAMEL_MULTIPART (containee));
 		for (i = 0; go && i < parts; i++) {
-			CamelMimePart *part = camel_multipart_get_part (CAMEL_MULTIPART (containee), i);
+			CamelMimePart *mpart = camel_multipart_get_part (CAMEL_MULTIPART (containee), i);
 			
-			go = message_foreach_part_rec (msg, part, callback, data);
+			go = message_foreach_part_rec (msg, mpart, callback, data);
 		}
 	} else if (CAMEL_IS_MIME_MESSAGE (containee)) {
 		go = message_foreach_part_rec (msg, (CamelMimePart *)containee, callback, data);
@@ -1168,9 +1176,9 @@
 	if (CAMEL_IS_MULTIPART(containee)) {
 		parts = camel_multipart_get_number((CamelMultipart *)containee);
 		for (i = 0; go && i < parts; i++) {
-			CamelMimePart *part = camel_multipart_get_part((CamelMultipart *)containee, i);
-
-			cmm_dump_rec(msg, part, body, depth+2);
+			CamelMimePart *mpart = camel_multipart_get_part((CamelMultipart *)containee, i);
+			
+			cmm_dump_rec(msg, mpart, body, depth+2);
 		}
 	} else if (CAMEL_IS_MIME_MESSAGE(containee)) {
 		cmm_dump_rec(msg, (CamelMimePart *)containee, body, depth+2);
Index: camel/camel-folder-search.c
===================================================================
--- camel/camel-folder-search.c	(revision 444)
+++ camel/camel-folder-search.c	(working copy)
@@ -182,7 +182,7 @@
 #define CAMEL_STRUCT_OFFSET(type, field)        ((gint) ((gchar*) &((type *) 0)->field))
 #endif
 
-struct {
+static struct {
 	char *name;
 	int offset;
 	int flags;		/* 0x02 = immediate, 0x01 = always enter */
@@ -463,6 +463,7 @@
 		for (i=0;i<search->summary->len;i++)
 			if (g_hash_table_lookup(uids_hash, camel_message_info_uid(search->summary->pdata[i])))
 				g_ptr_array_add(search->summary_set, search->summary->pdata[i]);
+		g_hash_table_destroy(uids_hash);
 	} else {
 		summary_set = search->summary;
 	}
@@ -772,6 +773,8 @@
 		type = 2;
 	else if (!strcmp(r->value.string, "replies_parents"))
 		type = 3;
+	else if (!strcmp(r->value.string, "single"))
+		type = 4;
 	e_sexp_result_free(f, r);
 
 	/* behave as (begin does */
@@ -801,31 +804,34 @@
 
 	results = g_hash_table_new(g_str_hash, g_str_equal);
 	for (i=0;i<r->value.ptrarray->len;i++) {
-		d(printf("adding match: %s\n", (char *)g_ptr_array_index(r->value.ptrarray, i)));
-		g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER (1));
-	}
-
-	for (i=0;i<r->value.ptrarray->len;i++) {
 		struct _CamelFolderThreadNode *node, *scan;
 
+		if (type != 4)
+			g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER(1));
+
 		node = g_hash_table_lookup(p->threads_hash, (char *)g_ptr_array_index(r->value.ptrarray, i));
 		if (node == NULL) /* this shouldn't happen but why cry over spilt milk */
 			continue;
 
 		/* select messages in thread according to search criteria */
-		if (type == 3) {
-			scan = node;
-			while (scan && scan->parent) {
-				scan = scan->parent;
-				g_hash_table_insert(results, (char *)camel_message_info_uid(scan->message), GINT_TO_POINTER(1));
+		if (type == 4) {
+			if (node->child == NULL && node->parent == NULL)
+				g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
+		} else {
+			if (type == 3) {
+				scan = node;
+				while (scan && scan->parent) {
+					scan = scan->parent;
+					g_hash_table_insert(results, (char *)camel_message_info_uid(scan->message), GINT_TO_POINTER(1));
+				}
+			} else if (type == 1) {
+				while (node && node->parent)
+					node = node->parent;
 			}
-		} else if (type == 1) {
-			while (node && node->parent)
-				node = node->parent;
+			g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
+			if (node->child)
+				add_thread_results(node->child, results);
 		}
-		g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
-		if (node->child)
-			add_thread_results(node->child, results);
 	}
 	e_sexp_result_free(f, r);
 
@@ -858,19 +864,19 @@
 
 		/* only a subset of headers are supported .. */
 		headername = argv[0]->value.string;
-		if (!strcasecmp(headername, "subject")) {
+		if (!g_ascii_strcasecmp(headername, "subject")) {
 			header = camel_message_info_subject(search->current);
-		} else if (!strcasecmp(headername, "date")) {
+		} else if (!g_ascii_strcasecmp(headername, "date")) {
 			/* FIXME: not a very useful form of the date */
 			sprintf(strbuf, "%d", (int)camel_message_info_date_sent(search->current));
 			header = strbuf;
-		} else if (!strcasecmp(headername, "from")) {
+		} else if (!g_ascii_strcasecmp(headername, "from")) {
 			header = camel_message_info_from(search->current);
 			type = CAMEL_SEARCH_TYPE_ADDRESS;
-		} else if (!strcasecmp(headername, "to")) {
+		} else if (!g_ascii_strcasecmp(headername, "to")) {
 			header = camel_message_info_to(search->current);
 			type = CAMEL_SEARCH_TYPE_ADDRESS;
-		} else if (!strcasecmp(headername, "cc")) {
+		} else if (!g_ascii_strcasecmp(headername, "cc")) {
 			header = camel_message_info_cc(search->current);
 			type = CAMEL_SEARCH_TYPE_ADDRESS;
 		} else if (!g_ascii_strcasecmp(headername, "x-camel-mlist")) {
Index: camel/camel-offline-journal.c
===================================================================
--- camel/camel-offline-journal.c	(revision 444)
+++ camel/camel-offline-journal.c	(working copy)
@@ -34,15 +34,16 @@
 #include <ctype.h>
 #include <errno.h>
 
-#include <camel/camel-i18n.h>
-#include <camel/camel-folder.h>
-#include <camel/camel-file-utils.h>
-#include <camel/camel-folder-summary.h>
-#include <camel/camel-data-cache.h>
+#include <glib/gstdio.h>
 
+#include "camel-data-cache.h"
+#include "camel-file-utils.h"
+#include "camel-folder-summary.h"
+#include "camel-folder.h"
+#include "camel-i18n.h"
 #include "camel-offline-journal.h"
+#include "camel-private.h"
 
-
 #define d(x) x
 
 static void camel_offline_journal_class_init (CamelOfflineJournalClass *klass);
@@ -115,7 +116,7 @@
 	journal->filename = g_strdup (filename);
 	journal->folder = folder;
 	
-	if ((fp = fopen (filename, "r"))) {
+	if ((fp = g_fopen (filename, "rb"))) {
 		while ((entry = CAMEL_OFFLINE_JOURNAL_GET_CLASS (journal)->entry_load (journal, fp)))
 			e_dlist_addtail (&journal->queue, entry);
 		
@@ -157,7 +158,7 @@
 	FILE *fp;
 	int fd;
 	
-	if ((fd = open (journal->filename, O_CREAT | O_TRUNC | O_WRONLY, 0666)) == -1) {
+	if ((fd = g_open (journal->filename, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0666)) == -1) {
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 				      _("Cannot write offline journal for folder `%s': %s"),
 				      journal->folder->full_name, g_strerror (errno));
Index: camel/camel-gpg-context.c
===================================================================
--- camel/camel-gpg-context.c	(revision 444)
+++ camel/camel-gpg-context.c	(working copy)
@@ -35,18 +35,24 @@
 #include <string.h>
 #include <sys/time.h>
 #include <sys/types.h>
-#include <sys/ioctl.h>
 #include <sys/stat.h>
-#include <sys/wait.h>
 #include <sys/time.h>
-#include <sys/poll.h>
-#include <termios.h>
 #include <signal.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <errno.h>
 #include <ctype.h>
 
+#include <glib.h>
+#include <glib/gstdio.h>
+
+#ifndef G_OS_WIN32
+#include <sys/ioctl.h>
+#include <sys/wait.h>
+#include <sys/poll.h>
+#include <termios.h>
+#endif
+
 #include "libedataserver/e-iconv.h"
 
 #include "camel-gpg-context.h"
@@ -293,7 +299,7 @@
 	gpg->diagbuf = CAMEL_STREAM_MEM (stream)->buffer;
 	gpg->diagflushed = FALSE;
 	
-	if ((charset = e_iconv_locale_charset ()) && strcasecmp (charset, "UTF-8") != 0) {
+	if ((charset = e_iconv_locale_charset ()) && g_ascii_strcasecmp (charset, "UTF-8") != 0) {
 		CamelMimeFilterCharset *filter;
 		CamelStreamFilter *fstream;
 		
@@ -398,7 +404,7 @@
 		g_byte_array_append (gpg->diagbuf, "", 1);
 	}
 	
-	return gpg->diagbuf->data;
+	return (const char *) gpg->diagbuf->data;
 }
 
 static void
@@ -464,6 +470,8 @@
 	g_free (gpg);
 }
 
+#ifndef G_OS_WIN32
+
 static const char *
 gpg_hash_str (CamelCipherHash hash)
 {
@@ -581,9 +589,12 @@
 	return argv;
 }
 
+#endif
+
 static int
 gpg_ctx_op_start (struct _GpgCtx *gpg)
 {
+#ifndef G_OS_WIN32
 	char *status_fd = NULL, *passwd_fd = NULL;
 	int i, maxfd, errnosave, fds[10];
 	GPtrArray *argv;
@@ -676,10 +687,18 @@
 	}
 	
 	errno = errnosave;
+#else
+	/* FIXME: Port me */
+	g_warning ("%s: Not implemented", __FUNCTION__);
+
+	errno = EINVAL;
+#endif
 	
 	return -1;
 }
 
+#ifndef G_OS_WIN32
+
 static const char *
 next_token (const char *in, char **token)
 {
@@ -775,40 +794,71 @@
 		
 		g_free (gpg->need_id);
 		gpg->need_id = userid;
-	} else if (!strncmp (status, "GET_HIDDEN passphrase.enter", 27)) {
+	} else if (!strncmp (status, "NEED_PASSPHRASE_PIN ", 20)) {
+		char *userid;
+		
+		status += 20;
+		
+		status = next_token (status, &userid);
+		if (!userid) {
+			camel_exception_set (ex, CAMEL_EXCEPTION_SYSTEM,
+					     _("Failed to parse gpg passphrase request."));
+			return -1;
+		}
+		
+		g_free (gpg->need_id);
+		gpg->need_id = userid;
+	} else if (!strncmp (status, "GET_HIDDEN ", 11)) {
+		const char *name = NULL;
 		char *prompt, *passwd;
-		const char *name;
+		guint32 flags;
 		
-		name = g_hash_table_lookup (gpg->userid_hint, gpg->need_id);
-		if (!name)
+		status += 11;
+		
+		if (gpg->need_id && !(name = g_hash_table_lookup (gpg->userid_hint, gpg->need_id)))
 			name = gpg->need_id;
+		else if (!name)
+			name = "";
 		
-		prompt = g_strdup_printf (_("You need a passphrase to unlock the key for\n"
-					    "user: \"%s\""), name);
+		if (!strncmp (status, "passphrase.pin.ask", 18)) {
+			prompt = g_strdup_printf (_("You need a PIN to unlock the key for your\n"
+						    "SmartCard: \"%s\""), name);
+		} else if (!strncmp (status, "passphrase.enter", 16)) {
+			prompt = g_strdup_printf (_("You need a passphrase to unlock the key for\n"
+						    "user: \"%s\""), name);
+		} else {
+			next_token (status, &prompt);
+			camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
+					      _("Unexpected request from GnuPG for `%s'"), prompt);
+			g_free (prompt);
+			return -1;
+		}
 		
-		if ((passwd = camel_session_get_password (gpg->session, NULL, NULL, prompt,  gpg->need_id, CAMEL_SESSION_PASSWORD_SECRET, ex)) && !gpg->utf8) {
-			char *opasswd = passwd;
+		flags = CAMEL_SESSION_PASSWORD_SECRET | CAMEL_SESSION_PASSPHRASE;
+		if ((passwd = camel_session_get_password (gpg->session, NULL, NULL, prompt, gpg->need_id, flags, ex))) {
+			if (!gpg->utf8) {
+				char *opasswd = passwd;
+				
+				if ((passwd = g_locale_to_utf8 (passwd, -1, &nread, &nwritten, NULL))) {
+					memset (opasswd, 0, strlen (opasswd));
+					g_free (opasswd);
+				} else {
+					passwd = opasswd;
+				}
+			}
 			
-			if ((passwd = g_locale_to_utf8 (passwd, -1, &nread, &nwritten, NULL))) {
-				memset (opasswd, 0, strlen (opasswd));
-				g_free (opasswd);
-			} else {
-				passwd = opasswd;
-			}
-		}
-		g_free (prompt);
-		
-		if (passwd == NULL) {
+			gpg->passwd = g_strdup_printf ("%s\n", passwd);
+			memset (passwd, 0, strlen (passwd));
+			g_free (passwd);
+			
+			gpg->send_passwd = TRUE;
+		} else {
 			if (!camel_exception_is_set (ex))
-				camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled."));
+				camel_exception_set (ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled."));
 			return -1;
 		}
 		
-		gpg->passwd = g_strdup_printf ("%s\n", passwd);
-		memset (passwd, 0, strlen (passwd));
-		g_free (passwd);
-		
-		gpg->send_passwd = TRUE;
+		g_free (prompt);
 	} else if (!strncmp (status, "GOOD_PASSPHRASE", 15)) {
 		gpg->bad_passwds = 0;
 	} else if (!strncmp (status, "BAD_PASSPHRASE", 14)) {
@@ -913,6 +963,8 @@
 	return 0;
 }
 
+#endif
+
 #define status_backup(gpg, start, len) G_STMT_START {                     \
 	if (gpg->statusleft <= len) {                                     \
 		unsigned int slen, soff;                                  \
@@ -933,6 +985,8 @@
 	gpg->statusleft -= len;                                           \
 } G_STMT_END
 
+#ifndef G_OS_WIN32
+
 static void
 gpg_ctx_op_cancel (struct _GpgCtx *gpg)
 {
@@ -953,9 +1007,12 @@
 	}
 }
 
+#endif
+
 static int
 gpg_ctx_op_step (struct _GpgCtx *gpg, CamelException *ex)
 {
+#ifndef G_OS_WIN32
 	struct pollfd polls[6];
 	int status, i, cancel_fd;
 
@@ -997,7 +1054,7 @@
 		goto exception;
 
 	if ((polls[5].revents & POLLIN) && camel_operation_cancel_check(NULL)) {
-		camel_exception_set(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Cancelled."));
+		camel_exception_set(ex, CAMEL_EXCEPTION_USER_CANCEL, _("Canceled."));
 		gpg_ctx_op_cancel(gpg);
 		return -1;
 	}
@@ -1137,7 +1194,7 @@
 	/* always called on an i/o error */
 	camel_exception_setv(ex, CAMEL_EXCEPTION_SYSTEM, _("Failed to execute gpg: %s"), g_strerror(errno));
 	gpg_ctx_op_cancel(gpg);
-
+#endif
 	return -1;
 }
 
@@ -1171,6 +1228,7 @@
 static int
 gpg_ctx_op_wait (struct _GpgCtx *gpg)
 {
+#ifndef G_OS_WIN32
 	sigset_t mask, omask;
 	pid_t retval;
 	int status;
@@ -1205,6 +1263,9 @@
 		return WEXITSTATUS (status);
 	else
 		return -1;
+#else
+	return -1;
+#endif
 }
 
 
@@ -1326,15 +1387,14 @@
 	char *template;
 	int fd, ret;
 	
-	template = g_strdup ("/tmp/evolution-pgp.XXXXXX");
-	fd = mkstemp (template);
-	if (fd == -1) {
+	template = g_build_filename (g_get_tmp_dir (), "evolution-pgp.XXXXXX", NULL);
+	if ((fd = g_mkstemp (template)) == -1) {
 		g_free (template);
 		return NULL;
 	}
-
+	
 	/* TODO: This should probably just write the decoded message content out, not the part + headers */
-
+	
 	ostream = camel_stream_fs_new_with_fd (fd);
 	ret = camel_data_wrapper_write_to_stream((CamelDataWrapper *)sigpart, ostream);
 	if (ret != -1) {
@@ -1342,11 +1402,11 @@
 		if (ret != -1)
 			ret = camel_stream_close (ostream);
 	}
-
+	
 	camel_object_unref(ostream);
-
+	
 	if (ret == -1) {
-		unlink (template);
+		g_unlink (template);
 		g_free (template);
 		return NULL;
 	}
@@ -1404,15 +1464,13 @@
 		camel_data_wrapper_decode_to_stream (content, istream);
 		camel_stream_reset(istream);
 		sigpart = NULL;
-			
 	} else {
 		/* Invalid Mimetype */
 		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
 			      _("Cannot verify message signature: Incorrect message format"));
 		return NULL;
 	}
-    
-
+	
 	/* Now start the real work of verifying the message */
 #ifdef GPG_LOG
 	if (camel_debug_start("gpg:sign")) {
@@ -1488,7 +1546,7 @@
 	gpg_ctx_free (gpg);
 	
 	if (sigfile) {
-		unlink (sigfile);
+		g_unlink (sigfile);
 		g_free (sigfile);
 	}
 	camel_object_unref(istream);
@@ -1504,7 +1562,7 @@
 		camel_object_unref(istream);
 
 	if (sigfile) {
-		unlink (sigfile);
+		g_unlink (sigfile);
 		g_free (sigfile);
 	}
 	
Index: camel/camel-service.c
===================================================================
--- camel/camel-service.c	(revision 444)
+++ camel/camel-service.c	(working copy)
@@ -36,12 +36,12 @@
 
 #include "libedataserver/e-msgport.h"
 
-#include "camel-service.h"
-#include "camel-session.h"
 #include "camel-exception.h"
+#include "camel-i18n.h"
 #include "camel-operation.h"
 #include "camel-private.h"
-#include "camel-i18n.h"
+#include "camel-service.h"
+#include "camel-session.h"
 
 #define d(x)
 #define w(x)
@@ -443,6 +443,7 @@
 	
 	CAMEL_SERVICE_UNLOCK (service, connect_lock);
 	
+		service->status = CAMEL_SERVICE_DISCONNECTED;
 	return res;
 }
 
Index: camel/camel-sasl-kerberos4.c
===================================================================
--- camel/camel-sasl-kerberos4.c	(revision 444)
+++ camel/camel-sasl-kerberos4.c	(working copy)
@@ -34,11 +34,12 @@
 
 #include <string.h>
 #include <netdb.h>
+
 #include "camel-i18n.h"
 #include "camel-net-utils.h"
-#include "camel-string-utils.h"
 #include "camel-sasl-kerberos4.h"
 #include "camel-service.h"
+#include "camel-string-utils.h"
 
 CamelServiceAuthType camel_sasl_kerberos4_authtype = {
 	N_("Kerberos 4"),
Index: camel/camel-win32.c
===================================================================
--- camel/camel-win32.c	(revision 444)
+++ camel/camel-win32.c	(working copy)
@@ -29,10 +29,54 @@
 #include <io.h>
 
 #include <glib.h>
+#include <glib/gstdio.h>
 
+#include <libedataserver/e-data-server-util.h>
+
 #include "camel.h"
-#include "camel-private.h"
 
+G_LOCK_DEFINE_STATIC (mutex);
+
+/* localedir uses system codepage as it is passed to the non-UTF8ified
+ * gettext library
+ */
+static const char *localedir = NULL;
+
+/* The others are in UTF-8 */
+static const char *libexecdir;
+static const char *providerdir;
+
+static void
+setup (void)
+{
+        G_LOCK (mutex);
+        if (localedir != NULL) {
+                G_UNLOCK (mutex);
+                return;
+        }
+
+        localedir = e_util_replace_prefix (E_DATA_SERVER_PREFIX, e_util_get_cp_prefix (), EVOLUTION_LOCALEDIR);
+
+	libexecdir = e_util_replace_prefix (E_DATA_SERVER_PREFIX, e_util_get_prefix (), CAMEL_LIBEXECDIR);
+	providerdir = e_util_replace_prefix (E_DATA_SERVER_PREFIX, e_util_get_prefix (), CAMEL_PROVIDERDIR);
+
+	G_UNLOCK (mutex);
+}
+
+#include "camel-private.h"	/* For prototypes */
+
+#define GETTER(varbl)				\
+const char *					\
+_camel_get_##varbl (void)			\
+{						\
+        setup ();				\
+        return varbl;				\
+}
+
+GETTER(localedir)
+GETTER(libexecdir)
+GETTER(providerdir)
+
 int
 fsync (int fd)
 {
@@ -60,133 +104,3 @@
 	return -1;
 }
 
-char *
-realpath(const char *name,
-	 char       *resolved)
-{
-  /* Lifted from glibc and modified as necessary */
-
-  char *dest, *extra_buf = NULL;
-  const char *past_root;
-  const char *start, *end, *resolved_limit;
-
-  if (name == NULL || resolved == NULL)
-    {
-      /* As per Single Unix Specification V2 we must return an error if
-	 either parameter is a null pointer.  */
-      errno = EINVAL;
-      return NULL;
-    }
-
-  if (name[0] == '\0')
-    {
-      /* As per Single Unix Specification V2 we must return an error if
-	 the name argument points to an empty string.  */
-      errno = ENOENT;
-      return NULL;
-    }
-
-  resolved_limit = resolved + PATH_MAX;
-
-  if (!g_path_is_absolute (name))
-    {
-      char *cwd = g_get_current_dir ();
-
-      if (strlen (cwd) > PATH_MAX)
-	{
-	  g_free (cwd);
-	  resolved[0] = '\0';
-	  errno = ENAMETOOLONG;
-	  goto error;
-	}
-      strcpy (resolved, cwd);
-      g_free (cwd);
-      past_root = g_path_skip_root (resolved);
-      dest = strchr (resolved, '\0');
-      start = name;
-    }
-  else
-    {
-      const char *n = name;
-      start = g_path_skip_root (name);
-
-      dest = resolved;
-      while (dest != resolved_limit && n != start)
-	{
-	  if (G_IS_DIR_SEPARATOR (*n))
-	    {
-	      *dest++ = G_DIR_SEPARATOR;
-	      n++;
-	    }
-	  else
-	    *dest++ = *n++;
-	}
-      if (dest == resolved_limit)
-	{
-	  resolved[0] = '\0';
-	  errno = ENAMETOOLONG;
-	  goto error;
-	}
-      past_root = dest;
-    }
-
-  for (end = name; *start; start = end)
-    {
-      struct stat st;
-      int n;
-
-      /* Skip sequence of multiple path-separators.  */
-      while (G_IS_DIR_SEPARATOR (*start))
-	++start;
-
-      /* Find end of path component.  */
-      for (end = start; *end && !G_IS_DIR_SEPARATOR (*end); ++end)
-	/* Nothing.  */;
-
-      if (end - start == 0)
-	break;
-      else if (end - start == 1 && start[0] == '.')
-	/* nothing */;
-      else if (end - start == 2 && start[0] == '.' && start[1] == '.')
-	{
-	  /* Back up to previous component, ignore if at root already.  */
-	  if (dest > past_root)
-	    {
-	      --dest;
-	      while (!G_IS_DIR_SEPARATOR ((dest)[-1]))
-		--dest;
-	    }
-	}
-      else
-	{
-	  size_t new_size;
-
-	  if (!G_IS_DIR_SEPARATOR (dest[-1]))
-	    *dest++ = G_DIR_SEPARATOR;
-
-	  if (dest + (end - start) >= resolved_limit)
-	    {
-	      errno = ENAMETOOLONG;
-	      if (dest > past_root)
-		dest--;
-	      *dest = '\0';
-	      goto error;
-	    }
-
-	  memcpy (dest, start, end - start);
-	  dest += end - start;
-	  *dest = '\0';
-
-	  if (stat (resolved, &st) < 0)
-	    goto error;
-	}
-    }
-  if (dest > past_root && G_IS_DIR_SEPARATOR (dest[-1]))
-    --dest;
-  *dest = '\0';
-
-  return resolved;
-
-error:
-  return NULL;
-}
Index: camel/camel-sasl-cram-md5.c
===================================================================
--- camel/camel-sasl-cram-md5.c	(revision 444)
+++ camel/camel-sasl-cram-md5.c	(working copy)
@@ -26,11 +26,13 @@
 
 #include <stdio.h>
 #include <string.h>
+
+#include "libedataserver/md5-utils.h"
+
+#include "camel-i18n.h"
+#include "camel-mime-utils.h"
 #include "camel-sasl-cram-md5.h"
-#include "camel-mime-utils.h"
 #include "camel-service.h"
-#include <libedataserver/md5-utils.h>
-#include "camel-i18n.h"
 
 CamelServiceAuthType camel_sasl_cram_md5_authtype = {
 	N_("CRAM-MD5"),
Index: camel/camel-mime-filter-yenc.c
===================================================================
--- camel/camel-mime-filter-yenc.c	(revision 444)
+++ camel/camel-mime-filter-yenc.c	(working copy)
@@ -416,7 +416,7 @@
 camel_ydecode_step (const unsigned char *in, size_t inlen, unsigned char *out,
 		    int *state, guint32 *pcrc, guint32 *crc)
 {
-	const register unsigned char *inptr;
+	register const unsigned char *inptr;
 	register unsigned char *outptr;
 	const unsigned char *inend;
 	unsigned char ch;
@@ -496,7 +496,7 @@
 camel_yencode_step (const unsigned char *in, size_t inlen, unsigned char *out,
 		    int *state, guint32 *pcrc, guint32 *crc)
 {
-	const register unsigned char *inptr;
+	register const unsigned char *inptr;
 	register unsigned char *outptr;
 	const unsigned char *inend;
 	register int already;
Index: camel/camel-block-file.c
===================================================================
--- camel/camel-block-file.c	(revision 444)
+++ camel/camel-block-file.c	(working copy)
@@ -32,10 +32,13 @@
 #include <fcntl.h>
 #include <errno.h>
 
+#include <glib/gstdio.h>
+
 #include "libedataserver/e-msgport.h"
 
 #include "camel-block-file.h"
 #include "camel-file-utils.h"
+#include "camel-private.h"
 
 #define d(x) /*(printf("%s(%d):%s: ",  __FILE__, __LINE__, __PRETTY_FUNCTION__),(x))*/
 
@@ -80,14 +83,14 @@
 static int
 block_file_validate_root(CamelBlockFile *bs)
 {
+	CamelBlockRoot *br;
 	struct stat st;
-	CamelBlockRoot *br;
-	int s;
-
+	int retval;
+	
 	br = bs->root;
-
-	s = fstat(bs->fd, &st);
-
+	
+	retval = fstat (bs->fd, &st);
+	
 	d(printf("Validate root: '%s'\n", bs->path));
 	d(printf("version: %.8s (%.8s)\n", bs->root->version, bs->version));
 	d(printf("block size: %d (%d)%s\n", br->block_size, bs->block_size,
@@ -103,12 +106,12 @@
 	    || br->block_size != bs->block_size
 	    || (br->free % bs->block_size) != 0
 	    || (br->last % bs->block_size) != 0
-	    || fstat(bs->fd, &st) == -1
+	    || retval == -1
 	    || st.st_size != br->last
 	    || br->free > st.st_size
 	    || (br->flags & CAMEL_BLOCK_FILE_SYNC) == 0) {
 #if 0
-		if (s != -1 && st.st_size > 0) {
+		if (retval != -1 && st.st_size > 0) {
 			g_warning("Invalid root: '%s'", bs->path);
 			g_warning("version: %.8s (%.8s)", bs->root->version, bs->version);
 			g_warning("block size: %d (%d)%s", br->block_size, bs->block_size,
@@ -215,7 +218,7 @@
 	bn = bl->next;
 	while (bn) {
 		if (bl->refcount != 0)
-			g_warning("Block '%d' still referenced", bl->id);
+			g_warning("Block '%u' still referenced", bl->id);
 		g_free(bl);
 		bl = bn;
 		bn = bn->next;
@@ -282,7 +285,7 @@
 	} else
 		d(printf("Turning block file online: %s\n", bs->path));
 
-	if ((bs->fd = open(bs->path, bs->flags, 0600)) == -1) {
+	if ((bs->fd = g_open(bs->path, bs->flags|O_BINARY, 0600)) == -1) {
 		err = errno;
 		CAMEL_BLOCK_FILE_UNLOCK(bs, io_lock);
 		errno = err;
@@ -410,12 +413,12 @@
 
 	CAMEL_BLOCK_FILE_LOCK(bs, io_lock);
 
-	ret = rename(bs->path, path);
+	ret = g_rename(bs->path, path);
 	if (ret == -1) {
 		/* Maybe the rename actually worked */
 		err = errno;
-		if (stat(path, &st) == 0
-		    && stat(bs->path, &st) == -1
+		if (g_stat(path, &st) == 0
+		    && g_stat(bs->path, &st) == -1
 		    && errno == ENOENT)
 			ret = 0;
 		errno = err;
@@ -448,7 +451,7 @@
 	}
 
 	p->deleted = TRUE;
-	ret = unlink(bs->path);
+	ret = g_unlink(bs->path);
 
 	CAMEL_BLOCK_FILE_UNLOCK(bs, io_lock);
 
@@ -905,11 +908,11 @@
 		d(printf("Turning key file online: '%s'\n", bs->path));
 
 	if ((bs->flags & O_ACCMODE) == O_RDONLY)
-		flag = "r";
+		flag = "rb";
 	else
-		flag = "a+";
+		flag = "a+b";
 
-	if ((fd = open(bs->path, bs->flags, 0600)) == -1
+	if ((fd = g_open(bs->path, bs->flags|O_BINARY, 0600)) == -1
 	    || (bs->fp = fdopen(fd, flag)) == NULL) {
 		err = errno;
 		close(fd);
@@ -1023,12 +1026,12 @@
 
 	CAMEL_KEY_FILE_LOCK(kf, lock);
 
-	ret = rename(kf->path, path);
+	ret = g_rename(kf->path, path);
 	if (ret == -1) {
 		/* Maybe the rename actually worked */
 		err = errno;
-		if (stat(path, &st) == 0
-		    && stat(kf->path, &st) == -1
+		if (g_stat(path, &st) == 0
+		    && g_stat(kf->path, &st) == -1
 		    && errno == ENOENT)
 			ret = 0;
 		errno = err;
@@ -1061,7 +1064,7 @@
 	}
 
 	p->deleted = TRUE;
-	ret = unlink(kf->path);
+	ret = g_unlink(kf->path);
 
 	CAMEL_KEY_FILE_UNLOCK(kf, lock);
 
Index: camel/camel-http-stream.c
===================================================================
--- camel/camel-http-stream.c	(revision 444)
+++ camel/camel-http-stream.c	(working copy)
@@ -179,7 +179,7 @@
 
 	d(printf("connecting to http stream @ '%s'\n", url->host));
 
-	if (!strcasecmp (url->protocol, "https")) {
+	if (!g_ascii_strcasecmp (url->protocol, "https")) {
 #ifdef HAVE_SSL
 		stream = camel_tcp_stream_ssl_new (http->session, url->host, SSL_FLAGS);
 #endif
@@ -267,7 +267,7 @@
 	d(printf("HTTP Status: %s\n", buffer));
 
 	/* parse the HTTP status code */
-	if (!strncasecmp (buffer, "HTTP/", 5)) {
+	if (!g_ascii_strncasecmp (buffer, "HTTP/", 5)) {
 		token = http_next_token (buffer);
 		http->statuscode = camel_header_decode_int (&token);
 		return http->statuscode;
@@ -326,7 +326,7 @@
 		
 		break;
 	default:
-		g_warning ("Invalid state encountered???: %d", camel_mime_parser_state (http->parser));
+		g_warning ("Invalid state encountered???: %u", camel_mime_parser_state (http->parser));
 	}
 	
 	err = camel_mime_parser_errno (http->parser);
@@ -532,7 +532,7 @@
 		http_disconnect(http);
 
 	return 0;
-};
+}
 
 CamelContentType *
 camel_http_stream_get_content_type (CamelHttpStream *http_stream)
Index: camel/camel-sasl-login.c
===================================================================
--- camel/camel-sasl-login.c	(revision 444)
+++ camel/camel-sasl-login.c	(working copy)
@@ -25,9 +25,10 @@
 #endif
 
 #include <string.h>
+
+#include "camel-i18n.h"
 #include "camel-sasl-login.h"
 #include "camel-service.h"
-#include "camel-i18n.h"
 
 CamelServiceAuthType camel_sasl_login_authtype = {
 	N_("Login"),
Index: camel/camel-vee-summary.c
===================================================================
--- camel/camel-vee-summary.c	(revision 444)
+++ camel/camel-vee-summary.c	(working copy)
@@ -29,8 +29,8 @@
 #include <string.h>
 #include <stdlib.h>
 
+#include "camel-folder.h"
 #include "camel-vee-summary.h"
-#include "camel-folder.h"
 
 #define d(x)
 
Index: camel/camel-mime-filter.c
===================================================================
--- camel/camel-mime-filter.c	(revision 444)
+++ camel/camel-mime-filter.c	(working copy)
@@ -19,6 +19,7 @@
  */
 
 #include <string.h>
+
 #include "camel-mime-filter.h"
 
 /*#define MALLOC_CHECK */ /* for some malloc checking, requires mcheck enabled */
Index: camel/camel-multipart-encrypted.c
===================================================================
--- camel/camel-multipart-encrypted.c	(revision 444)
+++ camel/camel-multipart-encrypted.c	(working copy)
@@ -28,14 +28,14 @@
 #include <stdio.h>
 #include <string.h>
 
+#include "camel-i18n.h"
+#include "camel-mime-filter-crlf.h"
+#include "camel-mime-part.h"
+#include "camel-mime-utils.h"
 #include "camel-multipart-encrypted.h"
-#include "camel-mime-filter-crlf.h"
 #include "camel-stream-filter.h"
+#include "camel-stream-fs.h"
 #include "camel-stream-mem.h"
-#include "camel-stream-fs.h"
-#include "camel-mime-utils.h"
-#include "camel-mime-part.h"
-#include "camel-i18n.h"
 
 static void camel_multipart_encrypted_class_init (CamelMultipartEncryptedClass *klass);
 static void camel_multipart_encrypted_init (gpointer object, gpointer klass);
Index: camel/camel-private.h
===================================================================
--- camel/camel-private.h	(revision 444)
+++ camel/camel-private.h	(working copy)
@@ -160,8 +160,32 @@
 #define CAMEL_CERTDB_LOCK(db, l) (g_mutex_lock (((CamelCertDB *) db)->priv->l))
 #define CAMEL_CERTDB_UNLOCK(db, l) (g_mutex_unlock (((CamelCertDB *) db)->priv->l))
 
+#if !GLIB_CHECK_VERSION(2,8,0)
+#define g_access access
+#define g_chmod chmod
+#define g_creat creat
+#define g_chdir chdir
+#endif
+
+#ifdef G_OS_WIN32
+int fsync (int fd);
+
+const char *_camel_get_localedir (void) G_GNUC_CONST;
+const char *_camel_get_libexecdir (void) G_GNUC_CONST;
+const char *_camel_get_providerdir (void) G_GNUC_CONST;
+
+#undef EVOLUTION_LOCALEDIR
+#define EVOLUTION_LOCALEDIR _camel_get_localedir ()
+
+#undef CAMEL_LIBEXECDIR
+#define CAMEL_LIBEXECDIR _camel_get_libexecdir ()
+
+#undef CAMEL_PROVIDERDIR
+#define CAMEL_PROVIDERDIR _camel_get_providerdir ()
+
+#endif /* G_OS_WIN32 */
+
 #ifdef __cplusplus
-}
 #endif /* __cplusplus */
 
 #endif /* CAMEL_PRIVATE_H */
Index: camel/camel-mime-parser.c
===================================================================
--- camel/camel-mime-parser.c	(revision 444)
+++ camel/camel-mime-parser.c	(working copy)
@@ -28,7 +28,6 @@
 
 #include <sys/types.h>
 #include <sys/stat.h>
-#include <fcntl.h>
 #include <unistd.h>
 
 #include <string.h>
@@ -36,18 +35,17 @@
 #include <stdio.h>
 #include <errno.h>
 
-#include <regex.h>
-#include <ctype.h>
-
 #include <glib.h>
+
+#include "libedataserver/e-memory.h"
+
+#include "camel-mime-filter.h"
 #include "camel-mime-parser.h"
 #include "camel-mime-utils.h"
-#include "camel-mime-filter.h"
-#include "camel-stream.h"
+#include "camel-private.h"
 #include "camel-seekable-stream.h"
+#include "camel-stream.h"
 
-#include "libedataserver/e-memory.h"
-
 #define r(x) 
 #define h(x) 
 #define c(x) 
@@ -372,7 +370,7 @@
 	if (array->len == 0 || array->data[array->len-1] != '\0')
 		g_byte_array_append(array, "", 1);
 
-	return array->data;
+	return (const char *) array->data;
 }
 
 /**
@@ -1153,11 +1151,11 @@
 	if (headerlen > 0) {									\
 		if (headerlen >= (s->outend - s->outptr)) {					\
 			register char *outnew;							\
-			register int len = ((s->outend - s->outbuf)+headerlen)*2+1;		\
-			outnew = g_realloc(s->outbuf, len);					\
+			register int olen = ((s->outend - s->outbuf) + headerlen) * 2 + 1;	\
+			outnew = g_realloc(s->outbuf, olen);					\
 			s->outptr = s->outptr - s->outbuf + outnew;				\
 			s->outbuf = outnew;							\
-			s->outend = outnew + len;						\
+			s->outend = outnew + olen;						\
 		}										\
 		if (start[headerlen-1] == '\r')							\
 			headerlen--;								\
@@ -1628,9 +1626,9 @@
 /*					camel_header_raw_replace(&h->headers, "Content-Type", "text/plain", offset);*/
 					/*g_warning("Multipart with no boundary, treating as text/plain");*/
 				}
-			} else if (!strcasecmp(ct->type, "message")) {
-				if (!strcasecmp(ct->subtype, "rfc822")
-				    || !strcasecmp(ct->subtype, "news")
+			} else if (!g_ascii_strcasecmp(ct->type, "message")) {
+				if (!g_ascii_strcasecmp(ct->subtype, "rfc822")
+				    || !g_ascii_strcasecmp(ct->subtype, "news")
 				    /*|| !g_ascii_strcasecmp(ct->subtype, "partial")*/) {
 					type = CAMEL_MIME_PARSER_STATE_MESSAGE;
 				}
@@ -1764,7 +1762,7 @@
 		return;
 
 	default:
-		g_warning("Invalid state in camel-mime-parser: %d", s->state);
+		g_warning ("Invalid state in camel-mime-parser: %u", s->state);
 		break;
 	}
 
@@ -1833,7 +1831,7 @@
 		name = argv[i];
 		printf("opening: %s", name);
 		
-		fd = open(name, O_RDONLY);
+		fd = g_open(name, O_RDONLY|O_BINARY, 0);
 		if (fd==-1) {
 			perror("Cannot open mailbox");
 			exit(1);
@@ -1866,7 +1864,7 @@
 
 				encoding = camel_header_raw_find(&s->parts->headers, "Content-transfer-encoding", 0);
 				printf("encoding = '%s'\n", encoding);
-				if (encoding && !strncasecmp(encoding, " base64", 7)) {
+				if (encoding && !g_ascii_strncasecmp(encoding, " base64", 7)) {
 					printf("adding base64 filter\n");
 					attachname = g_strdup_printf("attach.%d.%d", i, attach++);
 #if 0
@@ -1877,7 +1875,7 @@
 					folder_push_filter_mime(s, 0);
 #endif
 				}
-				if (encoding && !strncasecmp(encoding, " quoted-printable", 17)) {
+				if (encoding && !g_ascii_strncasecmp(encoding, " quoted-printable", 17)) {
 					printf("adding quoted-printable filter\n");
 					attachname = g_strdup_printf("attach.%d.%d", i, attach++);
 #if 0
@@ -1895,14 +1893,14 @@
 				break;
 			case CAMEL_MIME_PARSER_STATE_BODY_END:
 				printf("end body %d '%.*s'\n",  len, len, data);
-				if (encoding && !strncasecmp(encoding, " base64", 7)) {
+				if (encoding && !g_ascii_strncasecmp(encoding, " base64", 7)) {
 					printf("removing filters\n");
 #if 0
 					folder_filter_pull(s);
 					folder_filter_pull(s);
 #endif
 				}
-				if (encoding && !strncasecmp(encoding, " quoted-printable", 17)) {
+				if (encoding && !g_ascii_strncasecmp(encoding, " quoted-printable", 17)) {
 					printf("removing filters\n");
 #if 0
 					folder_filter_pull(s);
Index: camel/camel-charset-map-private.h
===================================================================
--- camel/camel-charset-map-private.h	(revision 444)
+++ camel/camel-charset-map-private.h	(working copy)
@@ -560,45 +560,45 @@
 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
 };
 
-const struct {
+static const struct {
 	const unsigned char *bits0;
 	const unsigned char *bits1;
 } camel_charmap[256] = {
-	{ m000, m001, }, { m010, m011, }, { m020, 0, }, { m030, 0, }, { m040, m041, }, { m050, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ m200, m201, }, { m210, m211, }, { m220, 0, }, { m230, 0, }, { 0, 0, }, { m250, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
-	{ 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, { 0, 0, }, 
+	{ m000, m001, }, { m010, m011, }, { m020, NULL, }, { m030, NULL, }, { m040, m041, }, { m050, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ m200, m201, }, { m210, m211, }, { m220, NULL, }, { m230, NULL, }, { NULL, NULL, }, { m250, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
+	{ NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, { NULL, NULL, }, 
 };
 
-const struct {
+static const struct {
 	const char *name;
 	unsigned int bit;
 } camel_charinfo[] = {
Index: camel/camel-uid-cache.c
===================================================================
--- camel/camel-uid-cache.c	(revision 444)
+++ camel/camel-uid-cache.c	(working copy)
@@ -32,8 +32,12 @@
 #include <sys/stat.h>
 #include <unistd.h>
 
+#include <glib/gstdio.h>
+
+#include "libedataserver/e-data-server-util.h"
+#include "camel-file-utils.h"
+#include "camel-private.h"
 #include "camel-uid-cache.h"
-#include "camel-file-utils.h"
 
 struct _uid_state {
 	int level;
@@ -60,14 +64,14 @@
 	int fd, i;
 	
 	dirname = g_path_get_dirname (filename);
-	if (camel_mkdir (dirname, 0777) == -1) {
+	if (e_util_mkdir_hier (dirname, 0777) == -1) {
 		g_free (dirname);
 		return NULL;
 	}
 	
 	g_free (dirname);
 	
-	if ((fd = open (filename, O_RDONLY | O_CREAT, 0666)) == -1)
+	if ((fd = g_open (filename, O_RDONLY | O_CREAT | O_BINARY, 0666)) == -1)
 		return NULL;
 	
 	if (fstat (fd, &st) == -1) {
@@ -153,7 +157,7 @@
 	int fd;
 	
 	filename = g_strdup_printf ("%s~", cache->filename);
-	if ((fd = open (filename, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1) {
+	if ((fd = g_open (filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666)) == -1) {
 		g_free (filename);
 		return FALSE;
 	}
@@ -172,7 +176,7 @@
 	close (fd);
 	fd = -1;
 	
-	if (rename (filename, cache->filename) == -1)
+	if (g_rename (filename, cache->filename) == -1)
 		goto exception;
 	
 	g_free (filename);
@@ -200,7 +204,7 @@
 		 * the new cache as well.
 		 **/
 		
-		if (stat (cache->filename, &st) == 0 &&
+		if (g_stat (cache->filename, &st) == 0 &&
 		    (cache->size > st.st_size || cache->size + cache->expired > st.st_size)) {
 			if (ftruncate (fd, (off_t) cache->size) != -1) {
 				cache->size = 0;
@@ -213,7 +217,7 @@
 	}
 #endif
 	
-	unlink (filename);
+	g_unlink (filename);
 	g_free (filename);
 	
 	errno = errnosav;
Index: camel/camel-mime-filter-charset.c
===================================================================
--- camel/camel-mime-filter-charset.c	(revision 444)
+++ camel/camel-mime-filter-charset.c	(working copy)
@@ -27,7 +27,7 @@
 #include <string.h>
 #include <errno.h>
 
-#include <libedataserver/e-iconv.h>
+#include "libedataserver/e-iconv.h"
 
 #include "camel-mime-filter-charset.h"
 #include "camel-charset-map.h"
Index: camel/camel-sasl.c
===================================================================
--- camel/camel-sasl.c	(revision 444)
+++ camel/camel-sasl.c	(working copy)
@@ -26,18 +26,18 @@
 #endif
 
 #include <string.h>
-#include "camel-sasl.h"
+
 #include "camel-mime-utils.h"
-#include "camel-service.h"
-
 #include "camel-sasl-cram-md5.h"
 #include "camel-sasl-digest-md5.h"
 #include "camel-sasl-gssapi.h"
 #include "camel-sasl-kerberos4.h"
 #include "camel-sasl-login.h"
+#include "camel-sasl-ntlm.h"
 #include "camel-sasl-plain.h"
 #include "camel-sasl-popb4smtp.h"
-#include "camel-sasl-ntlm.h"
+#include "camel-sasl.h"
+#include "camel-service.h"
 
 
 #define w(x)
Index: camel/camel-stream-buffer.c
===================================================================
--- camel/camel-stream-buffer.c	(revision 444)
+++ camel/camel-stream-buffer.c	(working copy)
@@ -30,6 +30,7 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <errno.h>
+
 #include "camel-stream-buffer.h"
 
 static CamelStreamClass *parent_class = NULL;
Index: camel/camel-sasl-plain.c
===================================================================
--- camel/camel-sasl-plain.c	(revision 444)
+++ camel/camel-sasl-plain.c	(working copy)
@@ -25,9 +25,10 @@
 #endif
 
 #include <string.h>
+
+#include "camel-i18n.h"
 #include "camel-sasl-plain.h"
 #include "camel-service.h"
-#include "camel-i18n.h"
 
 CamelServiceAuthType camel_sasl_plain_authtype = {
 	N_("PLAIN"),
Index: camel/camel-folder-summary.c
===================================================================
--- camel/camel-folder-summary.c	(revision 444)
+++ camel/camel-folder-summary.c	(working copy)
@@ -33,34 +33,30 @@
 #include <errno.h>
 #include <ctype.h>
 
-#include <libedataserver/e-iconv.h>
+#include "libedataserver/e-iconv.h"
 
+#include "camel-folder.h"
 #include "camel-folder-summary.h"
+#include "camel-file-utils.h"
+#include "camel-mime-filter.h"
+#include "camel-mime-filter-index.h"
+#include "camel-mime-filter-charset.h"
+#include "camel-mime-filter-basic.h"
+#include "camel-mime-filter-html.h"
+#include "camel-mime-message.h"
+#include "camel-multipart.h"
+#include "camel-private.h"
+#include "camel-stream-mem.h"
+#include "camel-stream-null.h"
+#include "camel-stream-filter.h"
+#include "camel-string-utils.h"
+#include "camel-disco-folder.h"
 
-/* for change events, perhaps we should just do them ourselves */
-#include "camel-folder.h"
-
-#include <camel/camel-file-utils.h>
-#include <camel/camel-mime-filter.h>
-#include <camel/camel-mime-filter-index.h>
-#include <camel/camel-mime-filter-charset.h>
-#include <camel/camel-mime-filter-basic.h>
-#include <camel/camel-mime-filter-html.h>
-#include <camel/camel-mime-message.h>
-#include <camel/camel-multipart.h>
-#include <camel/camel-stream-mem.h>
-
-#include <camel/camel-stream-null.h>
-#include <camel/camel-stream-filter.h>
-
-#include <camel/camel-string-utils.h>
-
 #include "libedataserver/md5-utils.h"
 #include "libedataserver/e-memory.h"
 
-#include "camel-private.h"
+#include <glib/gstdio.h>
 
-
 static pthread_mutex_t info_lock = PTHREAD_MUTEX_INITIALIZER;
 
 /* this lock is ONLY for the standalone messageinfo stuff */
@@ -71,15 +67,15 @@
 /* this should probably be conditional on it existing */
 #define USE_BSEARCH
 
-#define d(x)
+#define d(x)	
 #define io(x)			/* io debug */
-#define w(x)
+#define w(x)	
 
 #if 0
 extern int strdup_count, malloc_count, free_count;
 #endif
 
-#define CAMEL_FOLDER_SUMMARY_VERSION (13)
+#define CAMEL_FOLDER_SUMMARY_VERSION (15)
 
 #define _PRIVATE(o) (((CamelFolderSummary *)(o))->priv)
 
@@ -91,13 +87,13 @@
 static struct _node *my_list_append(struct _node **list, struct _node *n);
 static int my_list_size(struct _node **list);
 
-static int summary_header_load(CamelFolderSummary *, FILE *);
-static int summary_header_save(CamelFolderSummary *, FILE *);
+static int summary_header_load(CamelFolderSummary *, FILE *in);
+static int summary_header_save(CamelFolderSummary *, FILE *out);
 
 static CamelMessageInfo * message_info_new_from_header(CamelFolderSummary *, struct _camel_header_raw *);
 static CamelMessageInfo * message_info_new_from_parser(CamelFolderSummary *, CamelMimeParser *);
 static CamelMessageInfo * message_info_new_from_message(CamelFolderSummary *s, CamelMimeMessage *msg);
-static CamelMessageInfo * message_info_load(CamelFolderSummary *, FILE *);
+static CamelMessageInfo * message_info_load(CamelFolderSummary *, FILE *in);
 static int		  message_info_save(CamelFolderSummary *, FILE *, CamelMessageInfo *);
 static void		  message_info_free(CamelFolderSummary *, CamelMessageInfo *);
 
@@ -143,6 +139,7 @@
 	s->time = 0;
 	s->nextuid = 1;
 
+
 	s->messages = g_ptr_array_new();
 	s->messages_uid = g_hash_table_new(g_str_hash, g_str_equal);
 	
@@ -165,6 +162,11 @@
 	struct _CamelFolderSummaryPrivate *p;
 	CamelFolderSummary *s = (CamelFolderSummary *)obj;
 
+
+	if (s->file)
+		g_mapped_file_free (s->file);
+	s->file = NULL;
+
 	p = _PRIVATE(obj);
 
 	camel_folder_summary_clear(s);
@@ -241,7 +243,7 @@
 	CamelFolderSummary *new = CAMEL_FOLDER_SUMMARY ( camel_object_new (camel_folder_summary_get_type ()));
 
 	new->folder = folder;
-
+	
 	return new;
 }
 
@@ -509,17 +511,24 @@
 	int i;
 	guint32 count;
 	CamelMessageContentInfo *ci, *part;
+	unsigned char *ptrchr = s->filepos;
 
 	ci = ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->content_info_load(s, in);
+
 	if (ci == NULL)
 		return NULL;
 
-	if (camel_file_util_decode_uint32(in, &count) == -1 || count > 500) {
+	ptrchr = s->filepos;
+	ptrchr = camel_file_util_mmap_decode_uint32 ((unsigned char*)ptrchr, &count, FALSE);
+	s->filepos = ptrchr;
+
+	if (count > 500) {
 		camel_folder_summary_content_info_free(s, ci);
 		return NULL;
 	}
 
 	for (i=0;i<count;i++) {
+
 		part = perform_content_info_load(s, in);
 		if (part) {
 			my_list_append((struct _node **)&ci->childs, (struct _node *)part);
@@ -545,31 +554,34 @@
 int
 camel_folder_summary_load(CamelFolderSummary *s)
 {
-	FILE *in;
 	int i;
 	CamelMessageInfo *mi;
 
-	if (s->summary_path == NULL)
+
+	if (s->summary_path == NULL || !g_file_test (s->summary_path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
 		return 0;
 
-	in = fopen(s->summary_path, "r");
-	if (in == NULL)
-		return -1;
+	CAMEL_SUMMARY_LOCK(s, io_lock);
 
-	CAMEL_SUMMARY_LOCK(s, io_lock);
-	if ( ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->summary_header_load(s, in) == -1)
+	if (!s->file)
+		s->file = g_mapped_file_new (s->summary_path, FALSE, NULL);
+
+	s->filepos = (unsigned char*) g_mapped_file_get_contents (s->file);
+
+	if ( ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->summary_header_load(s, NULL) == -1)
 		goto error;
 
 	/* now read in each message ... */
 	for (i=0;i<s->saved_count;i++) {
-		mi = ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->message_info_load(s, in);
+		mi = ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->message_info_load(s, NULL);
 
 		if (mi == NULL)
 			goto error;
 
 		/* FIXME: this should be done differently, how i don't know */
+
 		if (s->build_content) {
-			((CamelMessageInfoBase *)mi)->content = perform_content_info_load(s, in);
+			((CamelMessageInfoBase *)mi)->content = perform_content_info_load(s, NULL);
 			if (((CamelMessageInfoBase *)mi)->content == NULL) {
 				camel_message_info_free(mi);
 				goto error;
@@ -579,13 +591,12 @@
 		camel_folder_summary_add(s, mi);
 	}
 
+
 	CAMEL_SUMMARY_UNLOCK(s, io_lock);
-	
-	if (fclose (in) != 0)
-		return -1;
 
 	s->flags &= ~CAMEL_SUMMARY_DIRTY;
 
+
 	return 0;
 
 error:
@@ -593,7 +604,6 @@
 		g_warning ("Cannot load summary file: `%s': %s", s->summary_path, g_strerror (errno));
 	
 	CAMEL_SUMMARY_UNLOCK(s, io_lock);
-	fclose (in);
 	s->flags |= ~CAMEL_SUMMARY_DIRTY;
 
 	return -1;
@@ -648,13 +658,14 @@
 
 	path = alloca(strlen(s->summary_path)+4);
 	sprintf(path, "%s~", s->summary_path);
-	fd = open(path, O_RDWR|O_CREAT|O_TRUNC, 0600);
+	fd = g_open(path, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0600);
 	if (fd == -1)
 		return -1;
-	out = fdopen(fd, "w");
+
+	out = fdopen(fd, "wb");
 	if (out == NULL) {
 		i = errno;
-		unlink(path);
+		g_unlink(path);
 		close(fd);
 		errno = i;
 		return -1;
@@ -683,32 +694,38 @@
 	
 	if (fflush (out) != 0 || fsync (fileno (out)) == -1)
 		goto exception;
+
+	CAMEL_SUMMARY_UNLOCK(s, io_lock);
 	
 	fclose (out);
+
 	
-	CAMEL_SUMMARY_UNLOCK(s, io_lock);
-	
-	if (rename(path, s->summary_path) == -1) {
+#ifdef G_OS_WIN32
+	g_unlink(s->summary_path);
+#endif
+	if (g_rename(path, s->summary_path) == -1) {
 		i = errno;
-		unlink(path);
+		g_unlink(path);
 		errno = i;
 		return -1;
 	}
 	
 	s->flags &= ~CAMEL_SUMMARY_DIRTY;
+
 	return 0;
 	
  exception:
+
+	CAMEL_SUMMARY_UNLOCK(s, io_lock);
 	
 	i = errno;
 	
 	fclose (out);
-	
-	CAMEL_SUMMARY_UNLOCK(s, io_lock);
-	
-	unlink (path);
+		
+	g_unlink (path);
 	errno = i;
 	
+
 	return -1;
 }
 
@@ -726,22 +743,24 @@
 int
 camel_folder_summary_header_load(CamelFolderSummary *s)
 {
-	FILE *in;
 	int ret;
 
-	if (s->summary_path == NULL)
+	if (s->summary_path == NULL || !g_file_test (s->summary_path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))
 		return 0;
 
-	in = fopen(s->summary_path, "r");
-	if (in == NULL)
-		return -1;
+	CAMEL_SUMMARY_LOCK(s, io_lock);
 
-	CAMEL_SUMMARY_LOCK(s, io_lock);
-	ret = ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->summary_header_load(s, in);
-	CAMEL_SUMMARY_UNLOCK(s, io_lock);
+	if (!s->file)
+		s->file = g_mapped_file_new (s->summary_path, FALSE, NULL);
+
+	s->filepos = (unsigned char*) g_mapped_file_get_contents (s->file);
+
 	
-	fclose(in);
+	ret = ((CamelFolderSummaryClass *)(CAMEL_OBJECT_GET_CLASS(s)))->summary_header_load(s, NULL);
+	
 	s->flags &= ~CAMEL_SUMMARY_DIRTY;
+	CAMEL_SUMMARY_UNLOCK(s, io_lock);
+
 	return ret;
 }
 
@@ -750,11 +769,15 @@
 {
 	const char *uid;
 	CamelMessageInfo *mi;
+	CamelMessageInfoBase *bi = (CamelMessageInfoBase*)info;
 
 	uid = camel_message_info_uid(info);
 	if (uid == NULL || uid[0] == 0) {
-		g_free(info->uid);
+
+		if (bi->uid_needs_free || bi->needs_free)
+			g_free(info->uid);
 		uid = info->uid = camel_folder_summary_next_uid_string(s);
+		bi->uid_needs_free = TRUE;
 	}
 
 	CAMEL_SUMMARY_LOCK(s, summary_lock);
@@ -764,8 +787,13 @@
 		if (mi == info)
 			return 0;
 		d(printf ("Trying to insert message with clashing uid (%s).  new uid re-assigned", camel_message_info_uid(info)));
-		g_free(info->uid);
+
+
+		if (bi->uid_needs_free || bi->needs_free)
+			g_free(info->uid);
 		uid = info->uid = camel_folder_summary_next_uid_string(s);
+		bi->uid_needs_free = TRUE;
+
 		camel_message_info_set_flags(info, CAMEL_MESSAGE_FOLDER_FLAGGED, CAMEL_MESSAGE_FOLDER_FLAGGED);
 		CAMEL_SUMMARY_LOCK(s, summary_lock);
 	}
@@ -1304,12 +1332,28 @@
 		if (token != -1) {
 			return camel_file_util_encode_uint32(out, token+1);
 		} else {
-			if (camel_file_util_encode_uint32(out, len+32) == -1)
+			int lena;
+
+			lena = len = len + 1;
+
+			if (lena % G_MEM_ALIGN)
+				lena += G_MEM_ALIGN - (lena % G_MEM_ALIGN);
+
+			if (camel_file_util_encode_uint32(out, lena+32) == -1)
 				return -1;
-			if (fwrite(str, len, 1, out) != 1)
-				return -1;
+
+			if (fwrite (str, len, 1, out) == 1)
+			{
+				if (lena > len)
+				{
+					if (fwrite ("\0\0\0\0\0\0\0\0", lena-len, 1, out) == 1)
+						return 0;
+					else return -1;
+				}
+			}
 		}
 	}
+
 	return 0;
 }
 
@@ -1324,24 +1368,22 @@
  * Returns %0 on success or %-1 on fail
  **/
 int
-camel_folder_summary_decode_token(FILE *in, char **str)
+camel_folder_summary_decode_token(CamelFolderSummary *s, FILE *in, char **str)
 {
 	char *ret;
 	guint32 len;
+	unsigned char *ptrchr = s->filepos;
 
 	io(printf("Decode token ...\n"));
-	
-	if (camel_file_util_decode_uint32(in, &len) == -1) {
-		io(printf ("Could not decode token from file"));
-		*str = NULL;
-		return -1;
-	}
 
+	ptrchr = camel_file_util_mmap_decode_uint32 ((unsigned char*)ptrchr, &len, FALSE);
+
 	if (len<32) {
+
 		if (len <= 0) {
 			ret = NULL;
 		} else if (len<= tokens_len) {
-			ret = g_strdup(tokens[len-1]);
+			ret = tokens[len-1];
 		} else {
 			io(printf ("Invalid token encountered: %d", len));
 			*str = NULL;
@@ -1352,17 +1394,17 @@
 		*str = NULL;
 		return -1;
 	} else {
+
 		len -= 32;
-		ret = g_malloc(len+1);
-		if (len > 0 && fread(ret, len, 1, in) != 1) {
-			g_free(ret);
-			*str = NULL;
-			return -1;
-		}
-		ret[len]=0;
+
+		if (len != 0)
+			ret = (char*)ptrchr;
+		else ret = NULL;
+
+		ptrchr += len;
 	}
 
-	io(printf("Token = '%s'\n", ret));
+	s->filepos = ptrchr;
 
 	*str = ret;
 	return 0;
@@ -1394,40 +1436,38 @@
 static int
 summary_header_load(CamelFolderSummary *s, FILE *in)
 {
-	fseek(in, 0, SEEK_SET);
+	s->version = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
 
-	io(printf("Loading header\n"));
+	io(printf("Loading header %d", (s->version&0xff)));
 
-	if (camel_file_util_decode_fixed_int32(in, &s->version) == -1)
-		return -1;
-
-	/* Legacy version check, before version 12 we have no upgrade knowledge */
+	/* Legacy version check, before version 13 we have no upgrade knowledge */
 	if ((s->version > 0xff) && (s->version & 0xff) < 12) {
 		io(printf ("Summary header version mismatch"));
 		errno = EINVAL;
 		return -1;
 	}
 
-	if (!(s->version < 0x100 && s->version >= 13))
-		io(printf("Loading legacy summary\n"));
-	else
-		io(printf("loading new-format summary\n"));
+	/* Check for MMAPable file */
+	if (s->version != CAMEL_FOLDER_SUMMARY_VERSION)
+	{
+		/* Put a summary-file-upgrader here */
 
-	/* legacy version */
-	if (camel_file_util_decode_fixed_int32(in, &s->flags) == -1
-	    || camel_file_util_decode_fixed_int32(in, &s->nextuid) == -1
-	    || camel_file_util_decode_time_t(in, &s->time) == -1
-	    || camel_file_util_decode_fixed_int32(in, &s->saved_count) == -1) {
+		errno = EINVAL;
 		return -1;
 	}
 
-	/* version 13 */
-	if (s->version < 0x100 && s->version >= 13
-	    && (camel_file_util_decode_fixed_int32(in, &s->unread_count) == -1
-		|| camel_file_util_decode_fixed_int32(in, &s->deleted_count) == -1
-		|| camel_file_util_decode_fixed_int32(in, &s->junk_count) == -1)) {
-		return -1;
+	s->flags = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+	s->nextuid = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+	s->time = (time_t)g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+	s->saved_count = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+
+
+	if (s->version < 0x100 && s->version >= 13) {
+		s->unread_count = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+		s->deleted_count = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+		s->junk_count = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
 	}
+     
 
 	return 0;
 }
@@ -1561,6 +1601,7 @@
 	const char *text;
 	
 	text = camel_header_raw_find (&h, name, NULL);
+
 	if (text) {
 		while (isspace ((unsigned) *text))
 			text++;
@@ -1590,8 +1631,9 @@
 		s->content_info_chunks = e_memchunk_new(32, s->content_info_size);
 	ci = e_memchunk_alloc(s->content_info_chunks);
 	CAMEL_SUMMARY_UNLOCK(s, alloc_lock);
+	ci->needs_free = FALSE;
+	memset(ci, 0, s->content_info_size);
 
-	memset(ci, 0, s->content_info_size);
 	return ci;
 }
 
@@ -1610,6 +1652,8 @@
 
 	mi = (CamelMessageInfoBase *)camel_message_info_new(s);
 
+	mi->needs_free = TRUE;
+
 	if ((content = camel_header_raw_find(&h, "Content-Type", NULL))
 	     && (ct = camel_content_type_decode(content))
 	     && (charset = camel_content_type_param(ct, "charset"))
@@ -1627,22 +1671,31 @@
 	if (ct)
 		camel_content_type_unref(ct);
 
-	mi->subject = camel_pstring_strdup(subject);
-	mi->from = camel_pstring_strdup(from);
-	mi->to = camel_pstring_strdup(to);
-	mi->cc = camel_pstring_strdup(cc);
-	mi->mlist = camel_pstring_strdup(mlist);
+	if (subject)
+		mi->subject = camel_pstring_add (subject, TRUE);
+	else mi->subject = NULL;
 
-	g_free(subject);
-	g_free(from);
-	g_free(to);
-	g_free(cc);
-	g_free(mlist);
+	if (from)
+		mi->from = camel_pstring_add (from, TRUE);
+	else mi->from = NULL;
 
+	if (to)
+		mi->to = camel_pstring_add (to, TRUE);
+	else mi->to = NULL;
+
+	if (cc)
+		mi->cc = camel_pstring_add (cc, TRUE);
+	else mi->cc = NULL;
+
+	if (mlist)
+		mi->mlist = camel_pstring_add (mlist, TRUE);
+	else mi->mlist = NULL;
+
 	mi->user_flags = NULL;
 	mi->user_tags = NULL;
 	mi->date_sent = camel_header_decode_date(camel_header_raw_find(&h, "date", NULL), NULL);
 	received = camel_header_raw_find(&h, "received", NULL);
+
 	if (received)
 		received = strrchr(received, ';');
 	if (received)
@@ -1689,90 +1742,125 @@
 	return (CamelMessageInfo *)mi;
 }
 
+
 static CamelMessageInfo *
 message_info_load(CamelFolderSummary *s, FILE *in)
 {
 	CamelMessageInfoBase *mi;
-	guint count;
-	int i;
-	char *subject, *from, *to, *cc, *mlist, *uid;
+	guint count, len;
+	unsigned char *ptrchr = s->filepos;
+	unsigned int i;
 
 	mi = (CamelMessageInfoBase *)camel_message_info_new(s);
 
+	mi->needs_free = FALSE;
+
 	io(printf("Loading message info\n"));
 
-	camel_file_util_decode_string(in, &uid);
-	camel_file_util_decode_uint32(in, &mi->flags);
-	camel_file_util_decode_uint32(in, &mi->size);
-	camel_file_util_decode_time_t(in, &mi->date_sent);
-	camel_file_util_decode_time_t(in, &mi->date_received);
-	camel_file_util_decode_string(in, &subject);
-	camel_file_util_decode_string(in, &from);
-	camel_file_util_decode_string(in, &to);
-	camel_file_util_decode_string(in, &cc);
-	camel_file_util_decode_string(in, &mlist);
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (!ptrchr) return NULL;
 
-	mi->uid = uid;
-	mi->subject = camel_pstring_strdup(subject);
-	mi->from = camel_pstring_strdup(from);
-	mi->to = camel_pstring_strdup(to);
-	mi->cc = camel_pstring_strdup(cc);
-	mi->mlist = camel_pstring_strdup(mlist);
+	if (len) mi->uid = (char*)ptrchr;
+	ptrchr += len;
 
-	g_free(subject);
-	g_free(from);
-	g_free(to);
-	g_free(cc);
-	g_free(mlist);
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &mi->flags, FALSE);
+	if (!ptrchr) return NULL;
 
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &mi->size, FALSE);
+	if (!ptrchr) return NULL;
+
+	ptrchr = camel_file_util_mmap_decode_time_t (ptrchr, &mi->date_sent);
+	ptrchr = camel_file_util_mmap_decode_time_t (ptrchr, &mi->date_received);
+
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (!ptrchr) return NULL;
+
+	if (len) mi->subject = (const char*)ptrchr;
+	ptrchr += len;
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (!ptrchr) return NULL;
+
+	if (len) mi->from = (const char*)ptrchr;
+	ptrchr += len;
+
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (!ptrchr) return NULL;
+
+	if (len) mi->to = (const char*)ptrchr;
+	ptrchr += len;
+
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (!ptrchr) return NULL;
+
+	if (len) mi->cc = (const char*)ptrchr;
+	ptrchr += len;
+
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &len, TRUE);
+	if (!ptrchr) return NULL;
+
+	if (len) mi->mlist = (const char*)ptrchr;
+	ptrchr += len;	
+
 	mi->content = NULL;
 
-	camel_file_util_decode_fixed_int32(in, &mi->message_id.id.part.hi);
-	camel_file_util_decode_fixed_int32(in, &mi->message_id.id.part.lo);
+	s->filepos = ptrchr;
+	mi->message_id.id.part.hi = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
+	mi->message_id.id.part.lo = g_ntohl(get_unaligned_u32(s->filepos)); s->filepos += 4;
 
-	if (camel_file_util_decode_uint32(in, &count) == -1 || count > 500)
-		goto error;
+	ptrchr = (unsigned char*) s->filepos;
+	ptrchr = camel_file_util_mmap_decode_uint32 (ptrchr, &count, FALSE);
+	if (!ptrchr) return NULL;
 
-	if (count > 0) {
-		mi->references = g_malloc(sizeof(*mi->references) + ((count-1) * sizeof(mi->references->references[0])));
-		mi->references->size = count;
-		for (i=0;i<count;i++) {
-			camel_file_util_decode_fixed_int32(in, &mi->references->references[i].id.part.hi);
-			camel_file_util_decode_fixed_int32(in, &mi->references->references[i].id.part.lo);
-		}
+	mi->references = g_malloc(sizeof(*mi->references) + ((count-1) * sizeof(mi->references->references[0])));
+	mi->references-
