Index: Makefile.am
===================================================================
--- Makefile.am	(revision 3535a6e36df4c6beed134aef3f7f81c7f9ea6dd2)
+++ Makefile.am	(revision ce35060c0b8f538bfc2659317d8bf70e8a2adbf7)
@@ -45,5 +45,5 @@
      aim.c buddy.c buddylist.c style.c errqueue.c \
      zbuddylist.c popexec.c select.c wcwidth.c \
-     glib_compat.c mainpanel.c msgwin.c sepbar.c editcontext.c signal.c
+     glib_compat.c mainpanel.c msgwin.c sepbar.c editcontext.c
 
 NORMAL_SRCS = filterproc.c window.c windowcb.c
Index: aim.c
===================================================================
--- aim.c	(revision dc1edbded39e57c67e8049c2960f0c235cd5afb5)
+++ aim.c	(revision 3472845ecdabe9cd1549dd2b2355ca745059ea36)
@@ -446,6 +446,7 @@
 }
 
-int owl_aim_process_events(aim_session_t *aimsess)
-{
+int owl_aim_process_events(void)
+{
+  aim_session_t *aimsess;
   aim_conn_t *waitingconn = NULL;
   struct timeval tv;
@@ -453,4 +454,5 @@
   struct owlfaim_priv *priv;
 
+  aimsess=owl_global_get_aimsess(&g);
   priv = aimsess->aux_data;
 
@@ -1793,113 +1795,8 @@
 }
 
-typedef struct _owl_aim_event_source { /*noproto*/
-  GSource source;
-  aim_session_t *sess;
-  GPtrArray *fds;
-} owl_aim_event_source;
-
-static void truncate_pollfd_list(owl_aim_event_source *event_source, int len)
-{
-  GPollFD *fd;
-  int i;
-  if (len < event_source->fds->len)
-    owl_function_debugmsg("Truncating AIM PollFDs to %d, was %d", len, event_source->fds->len);
-  for (i = len; i < event_source->fds->len; i++) {
-    fd = event_source->fds->pdata[i];
-    g_source_remove_poll(&event_source->source, fd);
-    g_free(fd);
-  }
-  g_ptr_array_remove_range(event_source->fds, len, event_source->fds->len - len);
-}
-
-static gboolean owl_aim_event_source_prepare(GSource *source, int *timeout)
-{
-  owl_aim_event_source *event_source = (owl_aim_event_source*)source;
-  aim_conn_t *cur;
-  GPollFD *fd;
-  int i;
-
-  /* AIM HACK:
-   *
-   *  The problem - I'm not sure where to hook into the owl/faim
-   *  interface to keep track of when the AIM socket(s) open and
-   *  close. In particular, the bosconn thing throws me off. So,
-   *  rather than register particular dispatchers for AIM, I look up
-   *  the relevant FDs and add them to select's watch lists, then
-   *  check for them individually before moving on to the other
-   *  dispatchers. --asedeno
-   */
-  i = 0;
-  for (cur = event_source->sess->connlist; cur; cur = cur->next) {
-    if (cur->fd != -1) {
-      /* Add new GPollFDs as necessary. */
-      if (i == event_source->fds->len) {
-	fd = g_new0(GPollFD, 1);
-	g_ptr_array_add(event_source->fds, fd);
-	g_source_add_poll(source, fd);
-        owl_function_debugmsg("Allocated new AIM PollFD, len = %d", event_source->fds->len);
-      }
-      fd = event_source->fds->pdata[i];
-      fd->fd = cur->fd;
-      fd->events |= G_IO_IN | G_IO_HUP | G_IO_ERR;
-      if (cur->status & AIM_CONN_STATUS_INPROGRESS) {
-        /* Yes, we're checking writable sockets here. Without it, AIM
-           login is really slow. */
-	fd->events |= G_IO_OUT;
-      }
-      i++;
-    }
-  }
-  /* If the number of GPollFDs went down, clean up. */
-  truncate_pollfd_list(event_source, i);
-
-  *timeout = -1;
-  return FALSE;
-}
-
-static gboolean owl_aim_event_source_check(GSource *source)
-{
-  owl_aim_event_source *event_source = (owl_aim_event_source*)source;
-  int i;
-
-  for (i = 0; i < event_source->fds->len; i++) {
-    GPollFD *fd = event_source->fds->pdata[i];
-    if (fd->revents & fd->events)
-      return TRUE;
-  }
-  return FALSE;
-}
-
-static gboolean owl_aim_event_source_dispatch(GSource *source, GSourceFunc callback, gpointer user_data)
-{
-  owl_aim_event_source *event_source = (owl_aim_event_source*)source;
-  owl_aim_process_events(event_source->sess);
-  return TRUE;
-}
-
-static void owl_aim_event_source_finalize(GSource *source)
-{
-  owl_aim_event_source *event_source = (owl_aim_event_source*)source;
-  truncate_pollfd_list(event_source, 0);
-  g_ptr_array_free(event_source->fds, TRUE);
-}
-
-static GSourceFuncs aim_event_funcs = {
-  owl_aim_event_source_prepare,
-  owl_aim_event_source_check,
-  owl_aim_event_source_dispatch,
-  owl_aim_event_source_finalize,
-};
-
-GSource *owl_aim_event_source_new(aim_session_t *sess)
-{
-  GSource *source;
-  owl_aim_event_source *event_source;
-
-  source = g_source_new(&aim_event_funcs, sizeof(owl_aim_event_source));
-  event_source = (owl_aim_event_source *)source;
-  event_source->sess = sess;
-  /* TODO: When we depend on glib 2.22+, use g_ptr_array_new_with_free_func. */
-  event_source->fds = g_ptr_array_new();
-  return source;
-}
+void owl_process_aim(void)
+{
+  if (owl_global_is_doaimevents(&g)) {
+    owl_aim_process_events();
+  }
+}
Index: cmd.c
===================================================================
--- cmd.c	(revision 4c7c21f786a0416a755645b78db0b851f75f8748)
+++ cmd.c	(revision 6a7111370ea0e1de2c3eb86a85f34cd68848d4b1)
@@ -12,11 +12,12 @@
 
 int owl_cmddict_setup(owl_cmddict *cd) {
-  owl_cmddict_init(cd);
+  if (0 != owl_cmddict_init(cd)) return(-1);
   if (0 != owl_cmddict_add_from_list(cd, commands_to_init)) return(-1);
   return(0);
 }
 
-void owl_cmddict_init(owl_cmddict *cd) {
-  owl_dict_create(cd);
+int owl_cmddict_init(owl_cmddict *cd) {
+  if (owl_dict_create(cd)) return(-1);
+  return(0);
 }
 
@@ -134,9 +135,9 @@
 void owl_cmd_cleanup(owl_cmd *cmd)
 {
-  g_free(cmd->name);
-  g_free(cmd->summary);
-  g_free(cmd->usage);
-  g_free(cmd->description);
-  g_free(cmd->cmd_aliased_to);
+  if (cmd->name) g_free(cmd->name);
+  if (cmd->summary) g_free(cmd->summary);
+  if (cmd->usage) g_free(cmd->usage);
+  if (cmd->description) g_free(cmd->description);
+  if (cmd->cmd_aliased_to) g_free(cmd->cmd_aliased_to);
   if (cmd->cmd_perl) owl_perlconfig_cmd_cleanup(cmd);
 }
Index: commands.c
===================================================================
--- commands.c	(revision 697221fc51f0060043c93821f0358317f6bc6ab0)
+++ commands.c	(revision c809f5e8a3cc2745724f518c89b09279b5508b02)
@@ -281,6 +281,6 @@
   OWLCMD_ARGS("punt", owl_command_punt, OWL_CTX_ANY,
 	      "suppress an arbitrary filter",
-	      "punt <filter-name>\n"
-	      "punt <filter-text (multiple words)>",
+	      "punt <filter-text>",
+	      "punt <filter-text (multiple words)>\n"
 	      "The punt command will suppress messages to the specified\n"
 	      "filter\n\n"
@@ -289,10 +289,10 @@
   OWLCMD_ARGS("unpunt", owl_command_unpunt, OWL_CTX_ANY,
 	      "remove an entry from the punt list",
-	      "unpunt <number>\n"
-	      "unpunt <filter-name>\n"
-	      "unpunt <filter-text (multiple words)>",
+	      "unpunt <filter-text>\n"
+	      "unpunt <filter-text>\n"
+	      "unpunt <number>\n",
 	      "The unpunt command will remove an entry from the puntlist.\n"
-	      "The last two forms correspond to the two forms of the :punt\n"
-	      "command. The first allows you to remove a specific entry from\n"
+	      "The first two forms correspond to the first two forms of the :punt\n"
+	      "command. The latter allows you to remove a specific entry from the\n"
 	      "the list (see :show zpunts)\n\n"
 	      "SEE ALSO:  punt, zpunt, zunpunt, show zpunts\n"),
@@ -1288,5 +1288,5 @@
   }
   owl_function_nextmsg_full(filter, skip_deleted, last_if_none);
-  g_free(filter);
+  if (filter) g_free(filter);
   return(NULL);
 }
@@ -1318,5 +1318,5 @@
   }
   owl_function_prevmsg_full(filter, skip_deleted, first_if_none);
-  g_free(filter);
+  if (filter) g_free(filter);
   return(NULL);
 }
@@ -1691,5 +1691,7 @@
   commands = g_strsplit_set(newbuff, ";", 0);
   for (i = 0; commands[i] != NULL; i++) {
-    g_free(lastrv);
+    if (lastrv) {
+      g_free(lastrv);
+    }
     lastrv = owl_function_command(commands[i]);
   }
@@ -2464,4 +2466,5 @@
   owl_list * fl;
   owl_filter * f;
+  char * text;
   int i;
 
@@ -2479,12 +2482,12 @@
         return;
       } else {
-        owl_function_makemsg("No such filter number: %d.", i+1);
+        owl_function_error("No such filter number: %d", i+1);
       }
     }
-    const char *filter[] = {"filter", argv[1]};
-    owl_function_punt(2, filter, unpunt);
+    text = owl_string_build_quoted("filter %q", argv[1]);
+    owl_function_punt(text, unpunt);
+    g_free(text);
   } else {
-    /* Pass in argv[1]..argv[argc-1]. */
-    owl_function_punt(argc - 1, argv + 1, unpunt);
+    owl_function_punt(skiptokens(buff, 1), unpunt);
   }
 }
Index: configure.ac
===================================================================
--- configure.ac	(revision 125536565b016a2dc0130569f6192cfebbe39f49)
+++ configure.ac	(revision 64c829aed5e966415464e38f393083d736e281e8)
@@ -115,5 +115,5 @@
 
 dnl Add CFLAGS and LIBS for glib-2.0
-PKG_CHECK_MODULES(GLIB,[glib-2.0 >= 2.12 gobject-2.0 gthread-2.0])
+PKG_CHECK_MODULES(GLIB,[glib-2.0 >= 2.12 gobject-2.0])
 
 AC_MSG_NOTICE([Adding glib-2.0 CFLAGS ${GLIB_CFLAGS}])
Index: dict.c
===================================================================
--- dict.c	(revision 4c7c21f786a0416a755645b78db0b851f75f8748)
+++ dict.c	(revision f25df21f6284aedd48c098bc68cee9896da5ce98)
@@ -15,8 +15,10 @@
 #define GROWBY 3 / 2
 
-void owl_dict_create(owl_dict *d) {
+int owl_dict_create(owl_dict *d) {
   d->size=0;
   d->els=g_new(owl_dict_el, INITSIZE);
   d->avail=INITSIZE;
+  if (d->els==NULL) return(-1);
+  return(0);
 }
 
@@ -58,9 +60,12 @@
 /* Appends dictionary keys to a list.  Duplicates the keys,
  * so they will need to be freed by the caller. */
-void owl_dict_get_keys(const owl_dict *d, owl_list *l) {
+int owl_dict_get_keys(const owl_dict *d, owl_list *l) {
   int i;
+  char *dupk;
   for (i=0; i<d->size; i++) {
-    owl_list_append_element(l, g_strdup(d->els[i].k));
+    if ((dupk = g_strdup(d->els[i].k)) == NULL) return(-1);
+    owl_list_append_element(l, dupk);
   }
+  return(0);
 }
 
@@ -79,4 +84,5 @@
 {
   int pos, found;
+  char *dupk;
   found = _owl_dict_find_pos(d, k, &pos);
   if (found && delete_on_replace) {
@@ -93,4 +99,5 @@
       if (d->els==NULL) return(-1);
     }
+    if ((dupk = g_strdup(k)) == NULL) return(-1);
     if (pos!=d->size) {
       /* shift forward to leave us a slot */
@@ -99,5 +106,5 @@
     }
     d->size++;
-    d->els[pos].k = g_strdup(k);
+    d->els[pos].k = dupk;
     d->els[pos].v = v;    
     return(0);
Index: editwin.c
===================================================================
--- editwin.c	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ editwin.c	(revision 47e0a6a50d1c08ec05030b2507b3f1a84b618a9f)
@@ -317,5 +317,6 @@
   }
 
-  g_free(locktext);
+  if (locktext)
+    g_free(locktext);
 
   oe_set_index(e, lock);
Index: filterproc.c
===================================================================
--- filterproc.c	(revision e2cc8487b365b026214922326e880825057eb9e6)
+++ filterproc.c	(revision 8bd190d63b2f2c09ea416e7be7c51d974f56bfaf)
@@ -17,4 +17,5 @@
   int err = 0;
   struct pollfd fds[2];
+  struct sigaction sig = {.sa_handler = SIG_IGN}, old;
 
   fcntl(rfd, F_SETFL, O_NONBLOCK | fcntl(rfd, F_GETFL));
@@ -26,4 +27,6 @@
   fds[1].events = POLLOUT;
 
+  sigaction(SIGPIPE, &sig, &old);
+  
   while(1) {
     if(out && *out) {
@@ -64,4 +67,5 @@
 
   *in = g_string_free(str, err < 0);
+  sigaction(SIGPIPE, &old, NULL);
   return err;
 }
Index: functions.c
===================================================================
--- functions.c	(revision 259e60a8abc2d2d41bc7a484b02a334fdd13857f)
+++ functions.c	(revision 1081d0fb7e406801281c29e6ec2e0f9362f9b70c)
@@ -32,5 +32,5 @@
   char *rv;
   rv=owl_function_command(cmdbuff);
-  g_free(rv);
+  if (rv) g_free(rv);
 }
 
@@ -453,5 +453,5 @@
 
   if (rv || status) {
-    g_free(cryptmsg);
+    if(cryptmsg) g_free(cryptmsg);
     g_free(old_msg);
     owl_function_error("Error in zcrypt, possibly no key found.  Message not sent.");
@@ -991,5 +991,5 @@
   /* execute the commands in shutdown */
   ret = owl_perlconfig_execute("BarnOwl::Hooks::_shutdown();");
-  g_free(ret);
+  if (ret) g_free(ret);
 
   /* signal our child process, if any */
@@ -2347,5 +2347,7 @@
 done:
   g_free(class);
-  g_free(instance);
+  if (instance) {
+    g_free(instance);
+  }
   return(filtname);
 }
@@ -2770,30 +2772,24 @@
 void owl_function_zpunt(const char *class, const char *inst, const char *recip, int direction)
 {
-  GPtrArray *argv;
+  GString *buf;
   char *quoted;
 
-  argv = g_ptr_array_new();
+  buf = g_string_new("");
   if (!strcmp(class, "*")) {
-    g_ptr_array_add(argv, g_strdup("class"));
-    g_ptr_array_add(argv, g_strdup(".*"));
+    g_string_append(buf, "class .*");
   } else {
     quoted=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
-    g_ptr_array_add(argv, g_strdup("class"));
-    g_ptr_array_add(argv, g_strdup_printf("^(un)*%s(\\.d)*$", quoted));
+    owl_string_appendf_quoted(buf, "class ^(un)*%q(\\.d)*$", quoted);
     g_free(quoted);
   }
   if (!strcmp(inst, "*")) {
-    g_ptr_array_add(argv, g_strdup("and"));
-    g_ptr_array_add(argv, g_strdup("instance"));
-    g_ptr_array_add(argv, g_strdup(".*"));
+    g_string_append(buf, " and instance .*");
   } else {
     quoted=owl_text_quote(inst, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
-    g_ptr_array_add(argv, g_strdup("and"));
-    g_ptr_array_add(argv, g_strdup("instance"));
-    g_ptr_array_add(argv, g_strdup_printf("^(un)*%s(\\.d)*$", quoted));
+    owl_string_appendf_quoted(buf, " and instance ^(un)*%q(\\.d)*$", quoted);
     g_free(quoted);
   }
   if (!strcmp(recip, "*")) {
-    /* nothing */
+    /* g_string_append(buf, ""); */
   } else {
     if(!strcmp(recip, "%me%")) {
@@ -2801,16 +2797,13 @@
     }
     quoted=owl_text_quote(recip, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
-    g_ptr_array_add(argv, g_strdup("and"));
-    g_ptr_array_add(argv, g_strdup("recipient"));
-    g_ptr_array_add(argv, g_strdup_printf("^%s$", quoted));
+    owl_string_appendf_quoted(buf, " and recipient ^%q$", quoted);
     g_free(quoted);
   }
 
-  owl_function_punt(argv->len, (const char *const*) argv->pdata, direction);
-  g_ptr_array_foreach(argv, (GFunc)g_free, NULL);
-  g_ptr_array_free(argv, true);
-}
-
-void owl_function_punt(int argc, const char *const *argv, int direction)
+  owl_function_punt(buf->str, direction);
+  g_string_free(buf, true);
+}
+
+void owl_function_punt(const char *filter, int direction)
 {
   owl_filter *f;
@@ -2820,5 +2813,6 @@
 
   /* first, create the filter */
-  f = owl_filter_new("punt-filter", argc, argv);
+  owl_function_debugmsg("About to filter %s", filter);
+  f = owl_filter_new_fromstring("punt-filter", filter);
   if (f == NULL) {
     owl_function_error("Error creating filter for zpunt");
@@ -2847,11 +2841,9 @@
   }
 
-  if (direction == 0) {
-    owl_function_debugmsg("punting");
-    /* If we're punting, add the filter to the global punt list */
+  owl_function_debugmsg("punting");
+  /* If we're punting, add the filter to the global punt list */
+  if (direction==0) {
     owl_list_append_element(fl, f);
-  } else if (direction == 1) {
-    owl_function_makemsg("No matching punt filter");
- }
+  }
 }
 
@@ -2990,9 +2982,13 @@
       i--;
     }
-    if (owl_global_take_interrupt(&g)) {
+    owl_function_mask_sigint(NULL);
+    if(owl_global_is_interrupted(&g)) {
+      owl_global_unset_interrupted(&g);
+      owl_function_unmask_sigint(NULL);
       owl_function_makemsg("Search interrupted!");
       owl_mainwin_redisplay(owl_global_get_mainwin(&g));
       return;
     }
+    owl_function_unmask_sigint(NULL);
   }
   owl_mainwin_redisplay(owl_global_get_mainwin(&g));
@@ -3077,9 +3073,14 @@
           ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
 
-	  if (owl_global_take_interrupt(&g)) {
+          owl_function_mask_sigint(NULL);
+          if(owl_global_is_interrupted(&g)) {
             interrupted = 1;
+            owl_global_unset_interrupted(&g);
+            owl_function_unmask_sigint(NULL);
             owl_function_makemsg("Interrupted!");
             break;
           }
+
+          owl_function_unmask_sigint(NULL);
 
           if (ret!=ZERR_NONE) {
@@ -3242,7 +3243,6 @@
   filename=owl_global_get_startupfile(&g);
 
-  /* delete earlier copies, if the file exists */
-  if (g_file_test(filename, G_FILE_TEST_EXISTS))
-    owl_util_file_deleteline(filename, buff, 1);
+  /* delete earlier copies */
+  owl_util_file_deleteline(filename, buff, 1);
 
   file=fopen(filename, "a");
@@ -3487,4 +3487,20 @@
 }
 
+void owl_function_mask_sigint(sigset_t *oldmask) {
+  sigset_t intr;
+
+  sigemptyset(&intr);
+  sigaddset(&intr, SIGINT);
+  sigprocmask(SIG_BLOCK, &intr, oldmask);
+}
+
+void owl_function_unmask_sigint(sigset_t *oldmask) {
+  sigset_t intr;
+
+  sigemptyset(&intr);
+  sigaddset(&intr, SIGINT);
+  sigprocmask(SIG_UNBLOCK, &intr, oldmask);
+}
+
 void _owl_function_mark_message(const owl_message *m)
 {
Index: global.c
===================================================================
--- global.c	(revision dc1edbded39e57c67e8049c2960f0c235cd5afb5)
+++ global.c	(revision 7b4f3bea704ed82f2c36ba19fcf354d7442a5bb7)
@@ -16,7 +16,4 @@
 
   g_type_init();
-  g_thread_init(NULL);
-
-  owl_select_init();
 
   g->lines=LINES;
@@ -98,4 +95,5 @@
 
   owl_errqueue_init(&(g->errqueue));
+  g->got_err_signal=0;
 
   owl_zbuddylist_create(&(g->zbuddies));
@@ -106,9 +104,8 @@
   owl_message_init_fmtext_cache();
   owl_list_create(&(g->io_dispatch_list));
+  owl_list_create(&(g->psa_list));
   g->timerlist = NULL;
+  g->interrupted = FALSE;
   g->kill_buffer = NULL;
-
-  g->interrupt_count = 0;
-  g->interrupt_lock = g_mutex_new();
 }
 
@@ -347,5 +344,5 @@
 
 void owl_global_set_resize_pending(owl_global *g) {
-  g->resizepending = true;
+  g->resizepending=1;
 }
 
@@ -447,5 +444,5 @@
   /* resize the screen.  If lines or cols is 0 use the terminal size */
   if (!g->resizepending) return;
-  g->resizepending = false;
+  g->resizepending = 0;
 
   owl_global_get_terminal_size(&g->lines, &g->cols);
@@ -508,5 +505,5 @@
 
 void owl_global_set_startupargs(owl_global *g, int argc, char **argv) {
-  g_free(g->startupargs);
+  if (g->startupargs) g_free(g->startupargs);
   g->startupargs = g_strjoinv(" ", argv);
 }
@@ -679,24 +676,18 @@
 }
 
-bool owl_global_is_doaimevents(const owl_global *g)
-{
-  return g->aim_event_source != NULL;
+int owl_global_is_doaimevents(const owl_global *g)
+{
+  if (g->aim_doprocessing) return(1);
+  return(0);
 }
 
 void owl_global_set_doaimevents(owl_global *g)
 {
-  if (g->aim_event_source)
-    return;
-  g->aim_event_source = owl_aim_event_source_new(owl_global_get_aimsess(g));
-  g_source_attach(g->aim_event_source, NULL);
+  g->aim_doprocessing=1;
 }
 
 void owl_global_set_no_doaimevents(owl_global *g)
 {
-  if (!g->aim_event_source)
-    return;
-  g_source_destroy(g->aim_event_source);
-  g_source_unref(g->aim_event_source);
-  g->aim_event_source = NULL;
+  g->aim_doprocessing=0;
 }
 
@@ -756,6 +747,6 @@
 }
 
-void owl_global_get_style_names(const owl_global *g, owl_list *l) {
-  owl_dict_get_keys(&(g->styledict), l);
+int owl_global_get_style_names(const owl_global *g, owl_list *l) {
+  return owl_dict_get_keys(&(g->styledict), l);
 }
 
@@ -816,4 +807,28 @@
 }
 
+void owl_global_set_errsignal(owl_global *g, int signum, siginfo_t *siginfo)
+{
+  g->got_err_signal = signum;
+  if (siginfo) {
+    g->err_signal_info = *siginfo;
+  } else {
+    siginfo_t si;
+    memset(&si, 0, sizeof(si));
+    g->err_signal_info = si;
+  }
+}
+
+int owl_global_get_errsignal_and_clear(owl_global *g, siginfo_t *siginfo)
+{
+  int signum;
+  if (siginfo && g->got_err_signal) {
+    *siginfo = g->err_signal_info;
+  } 
+  signum = g->got_err_signal;
+  g->got_err_signal = 0;
+  return signum;
+}
+
+
 owl_zbuddylist *owl_global_get_zephyr_buddylist(owl_global *g)
 {
@@ -846,7 +861,24 @@
 }
 
+owl_list *owl_global_get_psa_list(owl_global *g)
+{
+  return &(g->psa_list);
+}
+
 GList **owl_global_get_timerlist(owl_global *g)
 {
   return &(g->timerlist);
+}
+
+int owl_global_is_interrupted(const owl_global *g) {
+  return g->interrupted;
+}
+
+void owl_global_set_interrupted(owl_global *g) {
+  g->interrupted = 1;
+}
+
+void owl_global_unset_interrupted(owl_global *g) {
+  g->interrupted = 0;
 }
 
@@ -916,21 +948,2 @@
   g->kill_buffer = g_strndup(kill, len);
 }
-
-void owl_global_add_interrupt(owl_global *g) {
-  /* TODO: This can almost certainly be done with atomic
-   * operations. Whatever. */
-  g_mutex_lock(g->interrupt_lock);
-  g->interrupt_count++;
-  g_mutex_unlock(g->interrupt_lock);
-}
-
-bool owl_global_take_interrupt(owl_global *g) {
-  bool ans = false;
-  g_mutex_lock(g->interrupt_lock);
-  if (g->interrupt_count > 0) {
-    ans = true;
-    g->interrupt_count--;
-  }
-  g_mutex_unlock(g->interrupt_lock);
-  return ans;
-}
Index: keybinding.c
===================================================================
--- keybinding.c	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ keybinding.c	(revision d07af84683f667d7c34814c1b0a12823b08f6df0)
@@ -69,7 +69,7 @@
 void owl_keybinding_delete(owl_keybinding *kb)
 {
-  g_free(kb->keys);
-  g_free(kb->desc);
-  g_free(kb->command);
+  if (kb->keys) g_free(kb->keys);
+  if (kb->desc) g_free(kb->desc);
+  if (kb->command) g_free(kb->command);
   g_free(kb);
 }
Index: keymap.c
===================================================================
--- keymap.c	(revision 4c7c21f786a0416a755645b78db0b851f75f8748)
+++ keymap.c	(revision 47e0a6a50d1c08ec05030b2507b3f1a84b618a9f)
@@ -9,7 +9,7 @@
 {
   if (!name || !desc) return(-1);
-  km->name = g_strdup(name);
-  km->desc = g_strdup(desc);
-  owl_list_create(&km->bindings);
+  if ((km->name = g_strdup(name)) == NULL) return(-1);
+  if ((km->desc = g_strdup(desc)) == NULL) return(-1);
+  if (0 != owl_list_create(&km->bindings)) return(-1);
   km->parent = NULL;
   km->default_fn = default_fn;
@@ -179,9 +179,10 @@
 /* NOTE: keyhandler has private access to the internals of keymap */
 
-void owl_keyhandler_init(owl_keyhandler *kh)
-{
-  owl_dict_create(&kh->keymaps);
+int owl_keyhandler_init(owl_keyhandler *kh)
+{
+  if (0 != owl_dict_create(&kh->keymaps)) return(-1); 
   kh->active = NULL;
   owl_keyhandler_reset(kh);
+  return(0);
 }
 
Index: list.c
===================================================================
--- list.c	(revision fda61d3fe64381f30e32bc0091ab5ab59d95524f)
+++ list.c	(revision ddbbcffae8064f4d266a9735a16225e4feef1a3c)
@@ -5,9 +5,11 @@
 #define GROWBY 3 / 2
 
-void owl_list_create(owl_list *l)
+int owl_list_create(owl_list *l)
 {
   l->size=0;
   l->list=g_new(void *, INITSIZE);
   l->avail=INITSIZE;
+  if (l->list==NULL) return(-1);
+  return(0);
 }
 
Index: owl.c
===================================================================
--- owl.c	(revision 6476c0e00a11e070e7480afa291a8a0976aa7828)
+++ owl.c	(revision 9efa5bd38b986cf116a08ae43aa3f8629dcc6e60)
@@ -160,5 +160,5 @@
  * was ignored due to user settings or otherwise.
  */
-static int owl_process_message(owl_message *m) {
+int owl_process_message(owl_message *m) {
   const owl_filter *f;
   /* if this message it on the puntlist, nuke it and continue */
@@ -245,17 +245,10 @@
 }
 
-static gboolean owl_process_messages_prepare(GSource *source, int *timeout) {
-  *timeout = -1;
-  return owl_global_messagequeue_pending(&g);
-}
-
-static gboolean owl_process_messages_check(GSource *source) {
-  return owl_global_messagequeue_pending(&g);
-}
-
 /*
  * Process any new messages we have waiting in the message queue.
+ * Returns 1 if any messages were added to the message list, and 0 otherwise.
  */
-static gboolean owl_process_messages_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
+int owl_process_messages(owl_ps_action *d, void *p)
+{
   int newmsgs=0;
   int followlast = owl_global_should_followlast(&g);
@@ -281,23 +274,5 @@
     owl_mainwin_redisplay(owl_global_get_mainwin(&g));
   }
-  return TRUE;
-}
-
-static GSourceFuncs owl_process_messages_funcs = {
-  owl_process_messages_prepare,
-  owl_process_messages_check,
-  owl_process_messages_dispatch,
-  NULL
-};
-
-void owl_process_input_char(owl_input j)
-{
-  int ret;
-
-  owl_global_set_lastinputtime(&g, time(NULL));
-  ret = owl_keyhandler_process(owl_global_get_keyhandler(&g), j);
-  if (ret!=0 && ret!=1) {
-    owl_function_makemsg("Unable to handle keypress");
-  }
+  return newmsgs;
 }
 
@@ -359,68 +334,53 @@
 }
 
-static void sig_handler_main_thread(void *data) {
-  int sig = GPOINTER_TO_INT(data);
-
-  owl_function_debugmsg("Got signal %d", sig);
-  if (sig == SIGWINCH) {
+void sig_handler(int sig, siginfo_t *si, void *data)
+{
+  if (sig==SIGWINCH) {
+    /* we can't inturrupt a malloc here, so it just sets a flag
+     * schedulding a resize for later
+     */
     owl_function_resize();
-  } else if (sig == SIGTERM || sig == SIGHUP) {
+  } else if (sig==SIGPIPE || sig==SIGCHLD) {
+    /* Set a flag and some info that we got the sigpipe
+     * so we can record that we got it and why... */
+    owl_global_set_errsignal(&g, sig, si);
+  } else if (sig==SIGTERM || sig==SIGHUP) {
     owl_function_quit();
-  } else if (sig == SIGINT && owl_global_take_interrupt(&g)) {
-    owl_input in;
-    in.ch = in.uch = owl_global_get_startup_tio(&g)->c_cc[VINTR];
-    owl_process_input_char(in);
-  }
-}
-
-static void sig_handler(const siginfo_t *siginfo, void *data) {
-  /* If it was an interrupt, set a flag so we can handle it earlier if
-   * needbe. sig_handler_main_thread will check the flag to make sure
-   * no one else took it. */
-  if (siginfo->si_signo == SIGINT) {
-    owl_global_add_interrupt(&g);
-  }
-  /* Send a message to the main thread. */
-  owl_select_post_task(sig_handler_main_thread,
-                       GINT_TO_POINTER(siginfo->si_signo), NULL);
-}
-
-#define CHECK_RESULT(s, syscall) \
-  G_STMT_START {		 \
-    if ((syscall) != 0) {	 \
-      perror((s));		 \
-      exit(1);			 \
-    }				 \
-  } G_STMT_END
+  }
+}
+
+void sigint_handler(int sig, siginfo_t *si, void *data)
+{
+  owl_global_set_interrupted(&g);
+}
+
+static int owl_errsignal_pre_select_action(owl_ps_action *a, void *data)
+{
+  siginfo_t si;
+  int signum;
+  if ((signum = owl_global_get_errsignal_and_clear(&g, &si)) > 0) {
+    owl_function_error("Got unexpected signal: %d %s  (code: %d band: %ld  errno: %d)",
+        signum, signum==SIGPIPE?"SIGPIPE":"SIG????",
+        si.si_code, si.si_band, si.si_errno);
+  }
+  return 0;
+}
 
 void owl_register_signal_handlers(void) {
-  struct sigaction sig_ignore = { .sa_handler = SIG_IGN };
-  struct sigaction sig_default = { .sa_handler = SIG_DFL };
-  sigset_t sigset;
-  int ret, i;
-  const int signals[] = { SIGABRT, SIGBUS, SIGCHLD, SIGFPE, SIGHUP, SIGILL,
-                          SIGINT, SIGQUIT, SIGSEGV, SIGTERM, SIGWINCH };
-
-  /* Sanitize our signals; the mask and dispositions from our parent
-   * aren't really useful. Signal list taken from equivalent code in
-   * Chromium. */
-  CHECK_RESULT("sigemptyset", sigemptyset(&sigset));
-  if ((ret = pthread_sigmask(SIG_SETMASK, &sigset, NULL)) != 0) {
-    errno = ret;
-    perror("pthread_sigmask");
-  }
-  for (i = 0; i < G_N_ELEMENTS(signals); i++) {
-    CHECK_RESULT("sigaction", sigaction(signals[i], &sig_default, NULL));
-  }
-
-  /* Turn off SIGPIPE; we check the return value of write. */
-  CHECK_RESULT("sigaction", sigaction(SIGPIPE, &sig_ignore, NULL));
-
-  /* Register some signals with the signal thread. */
-  CHECK_RESULT("sigaddset", sigaddset(&sigset, SIGWINCH));
-  CHECK_RESULT("sigaddset", sigaddset(&sigset, SIGTERM));
-  CHECK_RESULT("sigaddset", sigaddset(&sigset, SIGHUP));
-  CHECK_RESULT("sigaddset", sigaddset(&sigset, SIGINT));
-  owl_signal_init(&sigset, sig_handler, NULL);
+  struct sigaction sigact;
+
+  /* signal handler */
+  /*sigact.sa_handler=sig_handler;*/
+  sigact.sa_sigaction=sig_handler;
+  sigemptyset(&sigact.sa_mask);
+  sigact.sa_flags=SA_SIGINFO;
+  sigaction(SIGWINCH, &sigact, NULL);
+  sigaction(SIGALRM, &sigact, NULL);
+  sigaction(SIGPIPE, &sigact, NULL);
+  sigaction(SIGTERM, &sigact, NULL);
+  sigaction(SIGHUP, &sigact, NULL);
+
+  sigact.sa_sigaction=sigint_handler;
+  sigaction(SIGINT, &sigact, NULL);
 }
 
@@ -464,8 +424,9 @@
   }
   bread = read(rfd, buf, navail);
-  if (bread == -1)
-    return;
-
-  err = g_strdup_printf("[stderr]\n%.*s", bread, buf);
+  if (buf[navail-1] != '\0') {
+    buf[navail] = '\0';
+  }
+
+  err = g_strdup_printf("[stderr]\n%s", buf);
 
   owl_function_log_err(err);
@@ -474,4 +435,28 @@
 
 #endif /* OWL_STDERR_REDIR */
+
+static int owl_refresh_pre_select_action(owl_ps_action *a, void *data)
+{
+  owl_colorpair_mgr *cpmgr;
+
+  /* if a resize has been scheduled, deal with it */
+  owl_global_check_resize(&g);
+  /* update the terminal if we need to */
+  owl_window_redraw_scheduled();
+  /* On colorpair shortage, reset and redraw /everything/. NOTE: if we
+   * still overflow, this be useless work. With 8-colors, we get 64
+   * pairs. With 256-colors, we get 32768 pairs with ext-colors
+   * support and 256 otherwise. */
+  cpmgr = owl_global_get_colorpair_mgr(&g);
+  if (cpmgr->overflow) {
+    owl_function_debugmsg("colorpairs: used all %d pairs; reset pairs and redraw.",
+                          owl_util_get_colorpairs());
+    owl_fmtext_reset_colorpairs(cpmgr);
+    owl_function_full_redisplay();
+    owl_window_redraw_scheduled();
+  }
+  return 0;
+}
+
 
 int main(int argc, char **argv, char **env)
@@ -483,5 +468,4 @@
   const char *dir;
   owl_options opts;
-  GSource *source;
 
   if (!GLIB_CHECK_VERSION (2, 12, 0))
@@ -498,4 +482,5 @@
   g.load_initial_subs = opts.load_initial_subs;
 
+  owl_register_signal_handlers();
   owl_start_curses();
 
@@ -509,6 +494,4 @@
   owl_global_set_haveaim(&g);
 
-  owl_register_signal_handlers();
-
   /* register STDIN dispatch; throw away return, we won't need it */
   owl_select_add_io_dispatch(STDIN_FILENO, OWL_IO_READ, &owl_process_input, NULL, NULL);
@@ -569,5 +552,5 @@
   owl_function_debugmsg("startup: executing perl startup, if applicable");
   perlout = owl_perlconfig_execute("BarnOwl::Hooks::_startup();");
-  g_free(perlout);
+  if (perlout) g_free(perlout);
 
   /* welcome message */
@@ -602,11 +585,7 @@
   owl_global_push_context(&g, OWL_CTX_INTERACTIVE|OWL_CTX_RECV, NULL, "recv", NULL);
 
-  source = owl_window_redraw_source_new();
-  g_source_attach(source, NULL);
-  g_source_unref(source);
-
-  source = g_source_new(&owl_process_messages_funcs, sizeof(GSource));
-  g_source_attach(source, NULL);
-  g_source_unref(source);
+  owl_select_add_pre_select_action(owl_refresh_pre_select_action, NULL, NULL);
+  owl_select_add_pre_select_action(owl_process_messages, NULL, NULL);
+  owl_select_add_pre_select_action(owl_errsignal_pre_select_action, NULL, NULL);
 
   owl_function_debugmsg("startup: entering main loop");
@@ -615,5 +594,4 @@
   /* Shut down everything. */
   owl_zephyr_shutdown();
-  owl_signal_shutdown();
   owl_shutdown_curses();
   return 0;
Index: owl.h
===================================================================
--- owl.h	(revision 33b6431b480426ea3c8334c4c6de3f19ad477071)
+++ owl.h	(revision ede073c25bc2c2eaf445db7084ebc31056f72ee8)
@@ -548,11 +548,16 @@
   int fd;                                     /* FD to watch for dispatch. */
   int mode;
-  bool valid;
   int needs_gc;
   void (*callback)(const struct _owl_io_dispatch *, void *); /* C function to dispatch to. */
   void (*destroy)(const struct _owl_io_dispatch *);  /* Destructor */
   void *data;
-  GPollFD pollfd;
 } owl_io_dispatch;
+
+typedef struct _owl_ps_action {
+  int needs_gc;
+  int (*callback)(struct _owl_ps_action *, void *);
+  void (*destroy)(struct _owl_ps_action *);
+  void *data;
+} owl_ps_action;
 
 typedef struct _owl_popexec {
@@ -563,4 +568,6 @@
   const owl_io_dispatch *dispatch;
 } owl_popexec;
+
+typedef struct _OwlGlobalNotifier OwlGlobalNotifier;
 
 typedef struct _owl_global {
@@ -588,5 +595,5 @@
   gulong typwin_erase_id;
   int rightshift;
-  bool resizepending;
+  volatile sig_atomic_t resizepending;
   char *homedir;
   char *confdir;
@@ -611,5 +618,5 @@
   aim_conn_t bosconn;
   int aim_loggedin;         /* true if currently logged into AIM */
-  GSource *aim_event_source; /* where we get our AIM events from */
+  int aim_doprocessing;     /* true if we should process AIM events (like pending login) */
   char *aim_screenname;     /* currently logged in AIM screen name */
   char *aim_screenname_for_filters;     /* currently logged in AIM screen name */
@@ -621,4 +628,6 @@
   int haveaim;
   int ignoreaimlogin;
+  volatile sig_atomic_t got_err_signal; /* 1 if we got an unexpected signal */
+  volatile siginfo_t err_signal_info;
   owl_zbuddylist zbuddies;
   GList *zaldlist;
@@ -626,11 +635,11 @@
   struct termios startup_tio;
   owl_list io_dispatch_list;
+  owl_list psa_list;
   GList *timerlist;
   owl_timer *aim_nop_timer;
   int load_initial_subs;
+  volatile sig_atomic_t interrupted;
   FILE *debug_file;
   char *kill_buffer;
-  int interrupt_count;
-  GMutex *interrupt_lock;
 } owl_global;
 
Index: perlconfig.c
===================================================================
--- perlconfig.c	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ perlconfig.c	(revision f2d71cfa06117d6e28806432db20b584c4596a19)
@@ -467,5 +467,5 @@
                                            :"BarnOwl::_receive_msg_legacy_wrap", m);
   }
-  g_free(ptr);
+  if (ptr) g_free(ptr);
 }
 
@@ -478,5 +478,5 @@
                                            :"BarnOwl::Hooks::_new_msg", m);
   }
-  g_free(ptr);
+  if (ptr) g_free(ptr);
 }
 
Index: perlglue.xs
===================================================================
--- perlglue.xs	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ perlglue.xs	(revision 6a7111370ea0e1de2c3eb86a85f34cd68848d4b1)
@@ -57,5 +57,5 @@
 		RETVAL
 	CLEANUP:
-		g_free(rv);
+		if (rv) g_free(rv);
 
 SV *
@@ -114,5 +114,5 @@
 		RETVAL
 	CLEANUP:
-		g_free(rv);
+		if (rv) g_free(rv);
 
 const utf8 *
@@ -141,5 +141,5 @@
 		RETVAL
     CLEANUP:
-		g_free(rv);
+		if (rv) g_free(rv);
 
 void
@@ -324,5 +324,6 @@
 		RETVAL
 	CLEANUP:
-		g_free(rv);
+		if (rv)
+			g_free(rv);
 
 void
Index: select.c
===================================================================
--- select.c	(revision 33b6431b480426ea3c8334c4c6de3f19ad477071)
+++ select.c	(revision fb961524492fcc80a144e70d4b31e3f46146dbb8)
@@ -1,13 +1,15 @@
 #include "owl.h"
-
-static GMainLoop *loop = NULL;
-static GMainContext *context;
+#include <sys/stat.h>
+
 static int dispatch_active = 0;
-
-static GSource *owl_timer_source;
-static GSource *owl_io_dispatch_source;
-
-static int _owl_select_timer_cmp(const owl_timer *t1, const owl_timer *t2) {
+static int psa_active = 0;
+static int loop_active = 0;
+
+int _owl_select_timer_cmp(const owl_timer *t1, const owl_timer *t2) {
   return t1->time - t2->time;
+}
+
+int _owl_select_timer_eq(const owl_timer *t1, const owl_timer *t2) {
+  return t1 == t2;
 }
 
@@ -42,64 +44,19 @@
 }
 
-static gboolean owl_timer_prepare(GSource *source, int *timeout) {
+void owl_select_process_timers(struct timespec *timeout)
+{
+  time_t now = time(NULL);
   GList **timers = owl_global_get_timerlist(&g);
-  GTimeVal now;
-
-  /* TODO: In the far /far/ future, g_source_get_time is what the cool
-   * kids use to get system monotonic time. */
-  g_source_get_current_time(source, &now);
-
-  /* FIXME: bother with millisecond accuracy now that we can? */
-  if (*timers) {
-    owl_timer *t = (*timers)->data;
-    *timeout = t->time - now.tv_sec;
-    if (*timeout <= 0) {
-      *timeout = 0;
-      return TRUE;
-    }
-    if (*timeout > 60 * 1000)
-      *timeout = 60 * 1000;
-  } else {
-    *timeout = 60 * 1000;
-  }
-  return FALSE;
-}
-
-static gboolean owl_timer_check(GSource *source) {
-  GList **timers = owl_global_get_timerlist(&g);
-  GTimeVal now;
-
-  /* TODO: In the far /far/ future, g_source_get_time is what the cool
-   * kids use to get system monotonic time. */
-  g_source_get_current_time(source, &now);
-
-  /* FIXME: bother with millisecond accuracy now that we can? */
-  if (*timers) {
-    owl_timer *t = (*timers)->data;
-    return t->time >= now.tv_sec;
-  }
-  return FALSE;
-}
-
-
-static gboolean owl_timer_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
-  GList **timers = owl_global_get_timerlist(&g);
-  GTimeVal now;
-
-  /* TODO: In the far /far/ future, g_source_get_time is what the cool
-   * kids use to get system monotonic time. */
-  g_source_get_current_time(source, &now);
-
-  /* FIXME: bother with millisecond accuracy now that we can? */
+
   while(*timers) {
     owl_timer *t = (*timers)->data;
     int remove = 0;
 
-    if(t->time > now.tv_sec)
+    if(t->time > now)
       break;
 
     /* Reschedule if appropriate */
     if(t->interval > 0) {
-      t->time = now.tv_sec + t->interval;
+      t->time = now + t->interval;
       *timers = g_list_remove(*timers, t);
       *timers = g_list_insert_sorted(*timers, t,
@@ -115,16 +72,18 @@
     }
   }
-  return TRUE;
-}
-
-static GSourceFuncs owl_timer_funcs = {
-  owl_timer_prepare,
-  owl_timer_check,
-  owl_timer_dispatch,
-  NULL
-};
-
-/* Returns the valid owl_io_dispatch for a given file descriptor. */
-static owl_io_dispatch *owl_select_find_valid_io_dispatch_by_fd(const int fd)
+
+  if(*timers) {
+    owl_timer *t = (*timers)->data;
+    timeout->tv_sec = t->time - now;
+    if (timeout->tv_sec > 60)
+      timeout->tv_sec = 60;
+  } else {
+    timeout->tv_sec = 60;
+  }
+
+  timeout->tv_nsec = 0;
+}
+
+static const owl_io_dispatch *owl_select_find_io_dispatch_by_fd(const int fd)
 {
   int i, len;
@@ -135,5 +94,5 @@
   for(i = 0; i < len; i++) {
     d = owl_list_get_element(dl, i);
-    if (d->fd == fd && d->valid) return d;
+    if (d->fd == fd) return d;
   }
   return NULL;
@@ -154,12 +113,4 @@
   }
   return -1;
-}
-
-static void owl_select_invalidate_io_dispatch(owl_io_dispatch *d)
-{
-  if (d == NULL || !d->valid)
-    return;
-  d->valid = false;
-  g_source_remove_poll(owl_io_dispatch_source, &d->pollfd);
 }
 
@@ -175,5 +126,4 @@
         d->needs_gc = 1;
       else {
-	owl_select_invalidate_io_dispatch(d);
         owl_list_remove_element(dl, elt);
         if (d->destroy)
@@ -185,5 +135,5 @@
 }
 
-static void owl_select_io_dispatch_gc(void)
+void owl_select_io_dispatch_gc(void)
 {
   int i;
@@ -203,5 +153,5 @@
 }
 
-/* Each FD may have at most one valid dispatcher.
+/* Each FD may have at most one dispatcher.
  * If a new dispatch is added for an FD, the old one is removed.
  * mode determines what types of events are watched for, and may be any combination of:
@@ -212,8 +162,6 @@
   owl_io_dispatch *d = g_new(owl_io_dispatch, 1);
   owl_list *dl = owl_global_get_io_dispatch_list(&g);
-  owl_io_dispatch *other;
 
   d->fd = fd;
-  d->valid = true;
   d->needs_gc = 0;
   d->mode = mode;
@@ -222,19 +170,5 @@
   d->data = data;
 
-  /* TODO: Allow changing fd and mode in the middle? Probably don't care... */
-  d->pollfd.fd = fd;
-  d->pollfd.events = 0;
-  if (d->mode & OWL_IO_READ)
-    d->pollfd.events |= G_IO_IN | G_IO_HUP | G_IO_ERR;
-  if (d->mode & OWL_IO_WRITE)
-    d->pollfd.events |= G_IO_OUT | G_IO_ERR;
-  if (d->mode & OWL_IO_EXCEPT)
-    d->pollfd.events |= G_IO_PRI | G_IO_ERR;
-  g_source_add_poll(owl_io_dispatch_source, &d->pollfd);
-
-
-  other = owl_select_find_valid_io_dispatch_by_fd(fd);
-  if (other)
-    owl_select_invalidate_io_dispatch(other);
+  owl_select_remove_io_dispatch(owl_select_find_io_dispatch_by_fd(fd));
   owl_list_append_element(dl, d);
 
@@ -242,39 +176,37 @@
 }
 
-static gboolean owl_io_dispatch_prepare(GSource *source, int *timeout) {
-  *timeout = -1;
-  return FALSE;
-}
-
-static gboolean owl_io_dispatch_check(GSource *source) {
-  int i, len;
-  const owl_list *dl;
-
-  dl = owl_global_get_io_dispatch_list(&g);
-  len = owl_list_get_size(dl);
-  for(i = 0; i < len; i++) {
-    owl_io_dispatch *d = owl_list_get_element(dl, i);
-    if (!d->valid) continue;
-    if (d->pollfd.revents & G_IO_NVAL) {
-      owl_function_debugmsg("Pruning defunct dispatch on fd %d.", d->fd);
-      owl_select_invalidate_io_dispatch(d);
-    }
-    if (d->pollfd.revents & d->pollfd.events)
-      return TRUE;
-  }
-  return FALSE;
-}
-
-static gboolean owl_io_dispatch_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
-  int i, len;
-  const owl_list *dl;
-
-  dispatch_active = 1;
-  dl = owl_global_get_io_dispatch_list(&g);
+int owl_select_prepare_io_dispatch_fd_sets(fd_set *rfds, fd_set *wfds, fd_set *efds) {
+  int i, len, max_fd;
+  owl_io_dispatch *d;
+  owl_list *dl = owl_global_get_io_dispatch_list(&g);
+
+  max_fd = 0;
   len = owl_list_get_size(dl);
   for (i = 0; i < len; i++) {
-    owl_io_dispatch *d = owl_list_get_element(dl, i);
-    if (!d->valid) continue;
-    if ((d->pollfd.revents & d->pollfd.events) && d->callback != NULL) {
+    d = owl_list_get_element(dl, i);
+    if (d->mode & (OWL_IO_READ | OWL_IO_WRITE | OWL_IO_EXCEPT)) {
+      if (max_fd < d->fd) max_fd = d->fd;
+      if (d->mode & OWL_IO_READ) FD_SET(d->fd, rfds);
+      if (d->mode & OWL_IO_WRITE) FD_SET(d->fd, wfds);
+      if (d->mode & OWL_IO_EXCEPT) FD_SET(d->fd, efds);
+    }
+  }
+  return max_fd + 1;
+}
+
+void owl_select_io_dispatch(const fd_set *rfds, const fd_set *wfds, const fd_set *efds, const int max_fd)
+{
+  int i, len;
+  owl_io_dispatch *d;
+  owl_list *dl = owl_global_get_io_dispatch_list(&g);
+
+  dispatch_active = 1;
+  len = owl_list_get_size(dl);
+  for (i = 0; i < len; i++) {
+    d = owl_list_get_element(dl, i);
+    if (d->fd < max_fd && d->callback != NULL &&
+        ((d->mode & OWL_IO_READ && FD_ISSET(d->fd, rfds)) ||
+         (d->mode & OWL_IO_WRITE && FD_ISSET(d->fd, wfds)) ||
+         (d->mode & OWL_IO_EXCEPT && FD_ISSET(d->fd, efds)))) {
       d->callback(d, d->data);
     }
@@ -282,48 +214,21 @@
   dispatch_active = 0;
   owl_select_io_dispatch_gc();
-
-  return TRUE;
-}
-
-static GSourceFuncs owl_io_dispatch_funcs = {
-  owl_io_dispatch_prepare,
-  owl_io_dispatch_check,
-  owl_io_dispatch_dispatch,
-  NULL
-};
+}
 
 int owl_select_add_perl_io_dispatch(int fd, int mode, SV *cb)
 {
-  const owl_io_dispatch *d = owl_select_find_valid_io_dispatch_by_fd(fd);
+  const owl_io_dispatch *d = owl_select_find_io_dispatch_by_fd(fd);
   if (d != NULL && d->callback != owl_perlconfig_io_dispatch) {
     /* Don't mess with non-perl dispatch functions from here. */
     return 1;
   }
-  /* Also remove any invalidated perl dispatch functions that may have
-   * stuck around. */
-  owl_select_remove_perl_io_dispatch(fd);
   owl_select_add_io_dispatch(fd, mode, owl_perlconfig_io_dispatch, owl_perlconfig_io_dispatch_destroy, cb);
   return 0;
 }
 
-static owl_io_dispatch *owl_select_find_perl_io_dispatch(int fd)
-{
-  int i, len;
-  const owl_list *dl;
-  owl_io_dispatch *d;
-  dl = owl_global_get_io_dispatch_list(&g);
-  len = owl_list_get_size(dl);
-  for(i = 0; i < len; i++) {
-    d = owl_list_get_element(dl, i);
-    if (d->fd == fd && d->callback == owl_perlconfig_io_dispatch)
-      return d;
-  }
-  return NULL;
-}
-
 int owl_select_remove_perl_io_dispatch(int fd)
 {
-  owl_io_dispatch *d = owl_select_find_perl_io_dispatch(fd);
-  if (d != NULL) {
+  const owl_io_dispatch *d = owl_select_find_io_dispatch_by_fd(fd);
+  if (d != NULL && d->callback == owl_perlconfig_io_dispatch) {
     /* Only remove perl io dispatchers from here. */
     owl_select_remove_io_dispatch(d);
@@ -333,60 +238,239 @@
 }
 
-void owl_select_init(void)
-{
-  owl_timer_source = g_source_new(&owl_timer_funcs, sizeof(GSource));
-  g_source_attach(owl_timer_source, NULL);
-
-  owl_io_dispatch_source = g_source_new(&owl_io_dispatch_funcs, sizeof(GSource));
-  g_source_attach(owl_io_dispatch_source, NULL);
+int owl_select_aim_hack(fd_set *rfds, fd_set *wfds)
+{
+  aim_conn_t *cur;
+  aim_session_t *sess;
+  int max_fd;
+
+  max_fd = 0;
+  sess = owl_global_get_aimsess(&g);
+  for (cur = sess->connlist; cur; cur = cur->next) {
+    if (cur->fd != -1) {
+      FD_SET(cur->fd, rfds);
+      if (cur->status & AIM_CONN_STATUS_INPROGRESS) {
+        /* Yes, we're checking writable sockets here. Without it, AIM
+           login is really slow. */
+        FD_SET(cur->fd, wfds);
+      }
+      
+      if (cur->fd > max_fd)
+        max_fd = cur->fd;
+    }
+  }
+  return max_fd;
+}
+
+void owl_process_input_char(owl_input j)
+{
+  int ret;
+
+  owl_global_set_lastinputtime(&g, time(NULL));
+  ret = owl_keyhandler_process(owl_global_get_keyhandler(&g), j);
+  if (ret!=0 && ret!=1) {
+    owl_function_makemsg("Unable to handle keypress");
+  }
+}
+
+void owl_select_mask_signals(sigset_t *oldmask) {
+  sigset_t set;
+
+  sigemptyset(&set);
+  sigaddset(&set, SIGWINCH);
+  sigaddset(&set, SIGALRM);
+  sigaddset(&set, SIGPIPE);
+  sigaddset(&set, SIGTERM);
+  sigaddset(&set, SIGHUP);
+  sigaddset(&set, SIGINT);
+  sigprocmask(SIG_BLOCK, &set, oldmask);
+}
+
+void owl_select_handle_intr(sigset_t *restore)
+{
+  owl_input in;
+
+  owl_global_unset_interrupted(&g);
+
+  sigprocmask(SIG_SETMASK, restore, NULL);
+
+  in.ch = in.uch = owl_global_get_startup_tio(&g)->c_cc[VINTR];
+  owl_process_input_char(in);
+}
+
+owl_ps_action *owl_select_add_pre_select_action(int (*cb)(owl_ps_action *, void *), void (*destroy)(owl_ps_action *), void *data)
+{
+  owl_ps_action *a = g_new(owl_ps_action, 1);
+  owl_list *psa_list = owl_global_get_psa_list(&g);
+  a->needs_gc = 0;
+  a->callback = cb;
+  a->destroy = destroy;
+  a->data = data;
+  owl_list_append_element(psa_list, a);
+  return a;
+}
+
+void owl_select_psa_gc(void)
+{
+  int i;
+  owl_list *psa_list;
+  owl_ps_action *a;
+
+  psa_list = owl_global_get_psa_list(&g);
+  for (i = owl_list_get_size(psa_list) - 1; i >= 0; i--) {
+    a = owl_list_get_element(psa_list, i);
+    if (a->needs_gc) {
+      owl_list_remove_element(psa_list, i);
+      if (a->destroy) {
+        a->destroy(a);
+      }
+      g_free(a);
+    }
+  }
+}
+
+void owl_select_remove_pre_select_action(owl_ps_action *a)
+{
+  a->needs_gc = 1;
+  if (!psa_active)
+    owl_select_psa_gc();
+}
+
+int owl_select_do_pre_select_actions(void)
+{
+  int i, len, ret;
+  owl_list *psa_list;
+
+  psa_active = 1;
+  ret = 0;
+  psa_list = owl_global_get_psa_list(&g);
+  len = owl_list_get_size(psa_list);
+  for (i = 0; i < len; i++) {
+    owl_ps_action *a = owl_list_get_element(psa_list, i);
+    if (a->callback != NULL && a->callback(a, a->data)) {
+      ret = 1;
+    }
+  }
+  psa_active = 0;
+  owl_select_psa_gc();
+  return ret;
+}
+
+static void owl_select_prune_bad_fds(void) {
+  owl_list *dl = owl_global_get_io_dispatch_list(&g);
+  int len, i;
+  struct stat st;
+  owl_io_dispatch *d;
+
+  len = owl_list_get_size(dl);
+  for (i = 0; i < len; i++) {
+    d = owl_list_get_element(dl, i);
+    if (fstat(d->fd, &st) < 0 && errno == EBADF) {
+      owl_function_debugmsg("Pruning defunct dispatch on fd %d.", d->fd);
+      d->needs_gc = 1;
+    }
+  }
+  owl_select_io_dispatch_gc();
+}
+
+void owl_select(void)
+{
+  int i, max_fd, max_fd2, aim_done, ret;
+  fd_set r;
+  fd_set w;
+  fd_set e;
+  fd_set aim_rfds, aim_wfds;
+  struct timespec timeout;
+  sigset_t mask;
+
+  owl_select_process_timers(&timeout);
+
+  owl_select_mask_signals(&mask);
+
+  if(owl_global_is_interrupted(&g)) {
+    owl_select_handle_intr(&mask);
+    return;
+  }
+  FD_ZERO(&r);
+  FD_ZERO(&w);
+  FD_ZERO(&e);
+
+  max_fd = owl_select_prepare_io_dispatch_fd_sets(&r, &w, &e);
+
+  /* AIM HACK: 
+   *
+   *  The problem - I'm not sure where to hook into the owl/faim
+   *  interface to keep track of when the AIM socket(s) open and
+   *  close. In particular, the bosconn thing throws me off. So,
+   *  rather than register particular dispatchers for AIM, I look up
+   *  the relevant FDs and add them to select's watch lists, then
+   *  check for them individually before moving on to the other
+   *  dispatchers. --asedeno
+   */
+  aim_done = 1;
+  FD_ZERO(&aim_rfds);
+  FD_ZERO(&aim_wfds);
+  if (owl_global_is_doaimevents(&g)) {
+    aim_done = 0;
+    max_fd2 = owl_select_aim_hack(&aim_rfds, &aim_wfds);
+    if (max_fd < max_fd2) max_fd = max_fd2;
+    for(i = 0; i <= max_fd2; i++) {
+      if (FD_ISSET(i, &aim_rfds)) {
+        FD_SET(i, &r);
+        FD_SET(i, &e);
+      }
+      if (FD_ISSET(i, &aim_wfds)) {
+        FD_SET(i, &w);
+        FD_SET(i, &e);
+      }
+    }
+  }
+  /* END AIM HACK */
+
+  if (owl_select_do_pre_select_actions()) {
+    timeout.tv_sec = 0;
+    timeout.tv_nsec = 0;
+  }
+
+  ret = pselect(max_fd+1, &r, &w, &e, &timeout, &mask);
+
+  if(ret < 0) {
+    if (errno == EINTR) {
+      if(owl_global_is_interrupted(&g)) {
+        owl_select_handle_intr(NULL);
+      }
+    } else if (errno == EBADF) {
+      /* Perl must have closed an fd on us without removing it first. */
+      owl_select_prune_bad_fds();
+    }
+    sigprocmask(SIG_SETMASK, &mask, NULL);
+    return;
+  }
+
+  sigprocmask(SIG_SETMASK, &mask, NULL);
+
+  if(ret > 0) {
+    /* AIM HACK: process all AIM events at once. */
+    for(i = 0; !aim_done && i <= max_fd; i++) {
+      if (FD_ISSET(i, &r) || FD_ISSET(i, &w) || FD_ISSET(i, &e)) {
+        if (FD_ISSET(i, &aim_rfds) || FD_ISSET(i, &aim_wfds)) {
+          owl_process_aim();
+          aim_done = 1;
+        }
+      }
+    }
+    owl_select_io_dispatch(&r, &w, &e, max_fd);
+  }
 }
 
 void owl_select_run_loop(void)
 {
-  context = g_main_context_default();
-  loop = g_main_loop_new(context, FALSE);
-  g_main_loop_run(loop);
+  loop_active = 1;
+  while (loop_active) {
+    owl_select();
+  }
 }
 
 void owl_select_quit_loop(void)
 {
-  if (loop) {
-    g_main_loop_quit(loop);
-    loop = NULL;
-  }
-}
-
-typedef struct _owl_task { /*noproto*/
-  void (*cb)(void *);
-  void *cbdata;
-  void (*destroy_cbdata)(void *);
-} owl_task;
-
-static gboolean _run_task(gpointer data)
-{
-  owl_task *t = data;
-  if (t->cb)
-    t->cb(t->cbdata);
-  return FALSE;
-}
-
-static void _destroy_task(void *data)
-{
-  owl_task *t = data;
-  if (t->destroy_cbdata)
-    t->destroy_cbdata(t->cbdata);
-  g_free(t);
-}
-
-void owl_select_post_task(void (*cb)(void*), void *cbdata, void (*destroy_cbdata)(void*))
-{
-  GSource *source = g_idle_source_new();
-  owl_task *t = g_new0(owl_task, 1);
-  t->cb = cb;
-  t->cbdata = cbdata;
-  t->destroy_cbdata = destroy_cbdata;
-  g_source_set_priority(source, G_PRIORITY_DEFAULT);
-  g_source_set_callback(source, _run_task, t, _destroy_task);
-  g_source_attach(source, context);
-  g_source_unref(source);
-}
+  loop_active = 0;
+}
Index: sepbar.c
===================================================================
--- sepbar.c	(revision 6eb3ed9ee6c4b94d35628e5b6b2bbaeccca565a9)
+++ sepbar.c	(revision 044f19f7c86e3f63b353e7fff2865f139319a45a)
@@ -16,5 +16,4 @@
   int x, y, i;
   const char *foo, *appendtosepbar;
-  int cur_numlines, cur_totallines;
 
   ml=owl_global_get_msglist(&g);
@@ -51,4 +50,12 @@
       wattron(sepwin, A_REVERSE);
 
+  if (owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g))) {
+    getyx(sepwin, y, x);
+    wmove(sepwin, y, x+2);
+    wattron(sepwin, A_BOLD);
+    waddstr(sepwin, " <truncated> ");
+    wattroff(sepwin, A_BOLD);
+  }
+
   i=owl_mainwin_get_last_msg(owl_global_get_mainwin(&g));
   if ((i != -1) &&
@@ -83,14 +90,4 @@
   }
 
-  if (owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g))) {
-    getyx(sepwin, y, x);
-    wmove(sepwin, y, x+2);
-    wattron(sepwin, A_BOLD);
-    cur_numlines = owl_global_get_curmsg_vert_offset(&g) + 1;
-    cur_totallines = owl_message_get_numlines(owl_view_get_element(v, owl_global_get_curmsg(&g)));
-    wprintw(sepwin, " <truncated: %d/%d> ", cur_numlines, cur_totallines);
-    wattroff(sepwin, A_BOLD);
-  }
-
   if (owl_global_get_curmsg_vert_offset(&g)) {
     getyx(sepwin, y, x);
Index: gnal.c
===================================================================
--- signal.c	(revision 1d21d9fd6efdecb79b0bef96aabee3943d6a955a)
+++ 	(revision )
@@ -1,62 +1,0 @@
-#include <errno.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-static pthread_t signal_thread;
-static sigset_t signal_set;
-
-static void (*signal_cb)(const siginfo_t*, void*);
-static void *signal_cbdata;
-
-static void *signal_thread_func(void *data);
-
-/* Initializes the signal thread to listen for 'set' on a dedicated
- * thread. 'callback' is called *on the signal thread* when a signal
- * is received.
- *
- * This function /must/ be called before any other threads are
- * created. (Otherwise the signals will not get blocked correctly.) */
-void owl_signal_init(const sigset_t *set, void (*callback)(const siginfo_t*, void*), void *data) {
-  int ret;
-
-  signal_set = *set;
-  signal_cb = callback;
-  signal_cbdata = data;
-  /* Block these signals in all threads, so we can get them. */
-  if ((ret = pthread_sigmask(SIG_BLOCK, set, NULL)) != 0) {
-    errno = ret;
-    perror("pthread_sigmask");
-  }
-  /* Spawn a dedicated thread to sigwait. */
-  if ((ret = pthread_create(&signal_thread, NULL,
-                            signal_thread_func, NULL)) != 0) {
-    errno = ret;
-    perror("pthread_create");
-    exit(1);
-  }
-}
-
-static void *signal_thread_func(void *data) {
-  while (1) {
-    siginfo_t siginfo;
-    int ret;
-
-    ret = sigwaitinfo(&signal_set, &siginfo);
-    /* TODO: Print an error? */
-    if (ret < 0)
-      continue;
-
-    signal_cb(&siginfo, signal_cbdata);
-    /* Die on SIGTERM. */
-    if (siginfo.si_signo == SIGTERM)
-      break;
-  }
-  return NULL;
-}
-
-void owl_signal_shutdown(void) {
-  pthread_kill(signal_thread, SIGTERM);
-  pthread_join(signal_thread, NULL);
-}
Index: tester.c
===================================================================
--- tester.c	(revision 4c7c21f786a0416a755645b78db0b851f75f8748)
+++ tester.c	(revision f25df21f6284aedd48c098bc68cee9896da5ce98)
@@ -233,5 +233,5 @@
 
   printf("# BEGIN testing owl_dict\n");
-  owl_dict_create(&d);
+  FAIL_UNLESS("create", 0==owl_dict_create(&d));
   FAIL_UNLESS("insert b", 0==owl_dict_insert_element(&d, "b", bv, owl_dict_noop_delete));
   FAIL_UNLESS("insert d", 0==owl_dict_insert_element(&d, "d", dv, owl_dict_noop_delete));
@@ -249,5 +249,5 @@
   FAIL_UNLESS("get_size", 3==owl_dict_get_size(&d));
   owl_list_create(&l);
-  owl_dict_get_keys(&d, &l);
+  FAIL_UNLESS("get_keys", 0==owl_dict_get_keys(&d, &l));
   FAIL_UNLESS("get_keys result size", 3==owl_list_get_size(&l));
   
Index: variable.c
===================================================================
--- variable.c	(revision 4c7c21f786a0416a755645b78db0b851f75f8748)
+++ variable.c	(revision f203cad04d71e968a11be5e72e6c9d805e02010d)
@@ -559,5 +559,5 @@
 int owl_variable_dict_setup(owl_vardict *vd) {
   owl_variable *var, *cur;
-  owl_dict_create(vd);
+  if (owl_dict_create(vd)) return(-1);
   for (var = variables_to_init; var->name != NULL; var++) {
     cur = g_new(owl_variable, 1);
@@ -641,7 +641,7 @@
 
 void owl_variable_update(owl_variable *var, const char *summary, const char *desc) {
-  g_free(var->summary);
+  if(var->summary) g_free(var->summary);
   var->summary = g_strdup(summary);
-  g_free(var->description);
+  if(var->description) g_free(var->description);
   var->description = g_strdup(desc);
 }
@@ -651,5 +651,5 @@
   if(old) {
     owl_variable_update(old, summ, desc);
-    g_free(old->pval_default);
+    if(old->pval_default) g_free(old->pval_default);
     old->pval_default = g_strdup(initval);
   } else {
@@ -944,5 +944,5 @@
 void owl_variable_delete_default(owl_variable *v)
 {
-  g_free(v->val);
+  if (v->val) g_free(v->val);
 }
 
@@ -1076,5 +1076,5 @@
     if (!v->validate_fn(v, newval)) return(-1);
   }
-  g_free(v->val);
+  if (v->val) g_free(v->val);
   v->val = g_strdup(newval);
   return(0);
Index: view.c
===================================================================
--- view.c	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ view.c	(revision d4927a70549407fe7f56b4ae1d3949663a370205)
@@ -160,4 +160,4 @@
 {
   owl_list_cleanup(&v->ml.list, NULL);
-  g_free(v->name);
+  if (v->name) g_free(v->name);
 }
Index: window.c
===================================================================
--- window.c	(revision 4cc49bce5bdc20cd8da2b4e305f60d04ae879d4f)
+++ window.c	(revision b31f1c9929b526b6d90b18b7847a024ff3d0c77d)
@@ -524,53 +524,2 @@
   owl_window_set_position(w, nlines, ncols, w->begin_y, w->begin_x);
 }
-
-/** Redrawing main loop hooks **/
-
-static bool _owl_window_should_redraw(void) {
-  return g.resizepending || owl_window_get_screen()->dirty_subtree;
-}
-
-static gboolean _owl_window_redraw_prepare(GSource *source, int *timeout) {
-  *timeout = -1;
-  return _owl_window_should_redraw();
-}
-
-static gboolean _owl_window_redraw_check(GSource *source) {
-  return _owl_window_should_redraw();
-}
-
-static gboolean _owl_window_redraw_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
-  owl_colorpair_mgr *cpmgr;
-
-  /* if a resize has been scheduled, deal with it */
-  owl_global_check_resize(&g);
-  /* update the terminal if we need to */
-  owl_window_redraw_scheduled();
-  /* On colorpair shortage, reset and redraw /everything/. NOTE: if we
-   * still overflow, this be useless work. With 8-colors, we get 64
-   * pairs. With 256-colors, we get 32768 pairs with ext-colors
-   * support and 256 otherwise. */
-  cpmgr = owl_global_get_colorpair_mgr(&g);
-  if (cpmgr->overflow) {
-    owl_function_debugmsg("colorpairs: used all %d pairs; reset pairs and redraw.",
-                          owl_util_get_colorpairs());
-    owl_fmtext_reset_colorpairs(cpmgr);
-    owl_function_full_redisplay();
-    owl_window_redraw_scheduled();
-  }
-  return TRUE;
-}
-
-static GSourceFuncs redraw_funcs = {
-  _owl_window_redraw_prepare,
-  _owl_window_redraw_check,
-  _owl_window_redraw_dispatch,
-  NULL
-};
-
-GSource *owl_window_redraw_source_new(void) {
-  GSource *source;
-  source = g_source_new(&redraw_funcs, sizeof(GSource));
-  /* TODO: priority?? */
-  return source;
-}
Index: window.h
===================================================================
--- window.h	(revision 4cc49bce5bdc20cd8da2b4e305f60d04ae879d4f)
+++ window.h	(revision 38e2250d6a6cd2691f017563d2eb56b3304d608a)
@@ -72,6 +72,4 @@
 void owl_window_resize(owl_window *w, int nlines, int ncols);
 
-GSource *owl_window_redraw_source_new(void);
-
 /* Standard callback functions in windowcb.c */
 
Index: zcrypt.c
===================================================================
--- zcrypt.c	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ zcrypt.c	(revision 1dd285b0045528991a838942c7ba925dbcf64128)
@@ -476,8 +476,12 @@
 
   for(i = 0; i < MAX_SEARCH; i++) {
-    g_free(varname[i]);
-  }
-
-  g_free(filename);
+    if(varname[i] != NULL) {
+      g_free(varname[i]);
+    }
+  }
+
+  if(filename != NULL) {
+    g_free(filename);
+  }
 
   return keyfile;
@@ -769,5 +773,5 @@
   err = call_filter("gpg", argv, in, &out, &status);
   if(err || status) {
-    g_free(out);
+    if(out) g_free(out);
     return FALSE;
   }
@@ -852,5 +856,5 @@
   err = call_filter("gpg", argv, in, &out, &status);
   if(err || status) {
-    g_free(out);
+    if(out) g_free(out);
     return FALSE;
   }
Index: zephyr.c
===================================================================
--- zephyr.c	(revision b848e308e9f8f212ddbf787f08111af994000512)
+++ zephyr.c	(revision f203cad04d71e968a11be5e72e6c9d805e02010d)
@@ -8,10 +8,4 @@
 
 #ifdef HAVE_LIBZEPHYR
-static GSource *owl_zephyr_event_source_new(int fd);
-
-static gboolean owl_zephyr_event_prepare(GSource *source, int *timeout);
-static gboolean owl_zephyr_event_check(GSource *source);
-static gboolean owl_zephyr_event_dispatch(GSource *source, GSourceFunc callback, gpointer user_data);
-
 static GList *deferred_subs = NULL;
 
@@ -22,11 +16,4 @@
 
 Code_t ZResetAuthentication(void);
-
-static GSourceFuncs zephyr_event_funcs = {
-  owl_zephyr_event_prepare,
-  owl_zephyr_event_check,
-  owl_zephyr_event_dispatch,
-  NULL
-};
 #endif
 
@@ -97,5 +84,4 @@
   Code_t code;
   char *perl;
-  GSource *event_source;
 
   owl_select_remove_io_dispatch(d);
@@ -113,7 +99,5 @@
   }
 
-  event_source = owl_zephyr_event_source_new(ZGetFD());
-  g_source_attach(event_source, NULL);
-  g_source_unref(event_source);
+  owl_select_add_io_dispatch(ZGetFD(), OWL_IO_READ|OWL_IO_EXCEPT, &owl_zephyr_process_events, NULL, NULL);
 
   owl_global_set_havezephyr(&g);
@@ -143,4 +127,6 @@
   perl = owl_perlconfig_execute("BarnOwl::Zephyr::_zephyr_startup()");
   g_free(perl);
+
+  owl_select_add_pre_select_action(owl_zephyr_pre_select_action, NULL, NULL);
 }
 
@@ -194,20 +180,4 @@
     if((code = ZPending()) < 0) {
       owl_function_debugmsg("Error (%s) in ZPending()\n",
-                            error_message(code));
-      return 0;
-    }
-    return code;
-  }
-#endif
-  return 0;
-}
-
-int owl_zephyr_zqlength(void)
-{
-#ifdef HAVE_LIBZEPHYR
-  Code_t code;
-  if(owl_global_is_havezephyr(&g)) {
-    if((code = ZQLength()) < 0) {
-      owl_function_debugmsg("Error (%s) in ZQLength()\n",
                             error_message(code));
       return 0;
@@ -447,5 +417,6 @@
     return 0;
   }
-  g_free(buffer);
+  if (buffer)
+    g_free(buffer);
 
   return owl_zephyr_loadsubs_helper(subs, count);
@@ -1451,8 +1422,8 @@
 #define OWL_MAX_ZEPHYRGRAMS_TO_PROCESS 20
 
-#ifdef HAVE_LIBZEPHYR
 static int _owl_zephyr_process_events(void)
 {
   int zpendcount=0;
+#ifdef HAVE_LIBZEPHYR
   ZNotice_t notice;
   Code_t code;
@@ -1495,40 +1466,15 @@
     }
   }
+#endif
   return zpendcount;
 }
 
-typedef struct { /*noproto*/
-  GSource source;
-  GPollFD poll_fd;
-} owl_zephyr_event_source;
-
-static GSource *owl_zephyr_event_source_new(int fd) {
-  GSource *source;
-  owl_zephyr_event_source *event_source;
-
-  source = g_source_new(&zephyr_event_funcs, sizeof(owl_zephyr_event_source));
-  event_source = (owl_zephyr_event_source*) source;
-  event_source->poll_fd.fd = fd;
-  event_source->poll_fd.events = G_IO_IN | G_IO_HUP | G_IO_PRI | G_IO_ERR;
-  g_source_add_poll(source, &event_source->poll_fd);
-
-  return source;
-}
-
-static gboolean owl_zephyr_event_prepare(GSource *source, int *timeout) {
-  *timeout = -1;
-  return owl_zephyr_zqlength() > 0;
-}
-
-static gboolean owl_zephyr_event_check(GSource *source) {
-  owl_zephyr_event_source *event_source = (owl_zephyr_event_source*)source;
-  if (event_source->poll_fd.revents & event_source->poll_fd.events)
-    return owl_zephyr_zpending() > 0;
-  return FALSE;
-}
-
-static gboolean owl_zephyr_event_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) {
+void owl_zephyr_process_events(const owl_io_dispatch *d, void *data)
+{
   _owl_zephyr_process_events();
-  return TRUE;
-}
-#endif
+}
+
+int owl_zephyr_pre_select_action(owl_ps_action *a, void *p)
+{
+  return _owl_zephyr_process_events();
+}
Index: zwrite.c
===================================================================
--- zwrite.c	(revision 3b8a563ae4e07b1064fe005714793565ac720dc4)
+++ zwrite.c	(revision 3f52e1446b6b705636f09d02d657c28d38ef29a2)
@@ -185,5 +185,5 @@
 void owl_zwrite_set_message_raw(owl_zwrite *z, const char *msg)
 {
-  g_free(z->message);
+  if (z->message) g_free(z->message);
   z->message = owl_validate_utf8(msg);
 }
@@ -195,5 +195,5 @@
   char *tmp = NULL, *tmp2;
 
-  g_free(z->message);
+  if (z->message) g_free(z->message);
 
   j=owl_list_get_size(&(z->recips));
@@ -289,5 +289,5 @@
 void owl_zwrite_set_opcode(owl_zwrite *z, const char *opcode)
 {
-  g_free(z->opcode);
+  if (z->opcode) g_free(z->opcode);
   z->opcode=owl_validate_utf8(opcode);
 }
@@ -306,5 +306,5 @@
 void owl_zwrite_set_zsig(owl_zwrite *z, const char *zsig)
 {
-  g_free(z->zsig);
+  if(z->zsig) g_free(z->zsig);
   z->zsig = g_strdup(zsig);
 }
@@ -353,12 +353,12 @@
 {
   owl_list_cleanup(&(z->recips), &g_free);
-  g_free(z->cmd);
-  g_free(z->zwriteline);
-  g_free(z->class);
-  g_free(z->inst);
-  g_free(z->opcode);
-  g_free(z->realm);
-  g_free(z->message);
-  g_free(z->zsig);
+  if (z->cmd) g_free(z->cmd);
+  if (z->zwriteline) g_free(z->zwriteline);
+  if (z->class) g_free(z->class);
+  if (z->inst) g_free(z->inst);
+  if (z->opcode) g_free(z->opcode);
+  if (z->realm) g_free(z->realm);
+  if (z->message) g_free(z->message);
+  if (z->zsig) g_free(z->zsig);
 }
 
