/*
 * call-seq:
 *   conn.set_notice_receiver {|result| ... } -> Proc
 *
 * Notice and warning messages generated by the server are not returned
 * by the query execution functions, since they do not imply failure of
 * the query. Instead they are passed to a notice handling function, and
 * execution continues normally after the handler returns. The default
 * notice handling function prints the message on <tt>stderr</tt>, but the
 * application can override this behavior by supplying its own handling
 * function.
 *
 * This function takes a new block to act as the handler, which should
 * accept a single parameter that will be a PGresult object, and returns 
 * the Proc object previously set, or +nil+ if it was previously the default.
 *
 * If you pass no arguments, it will reset the handler to the default.
 */
static VALUE
pgconn_set_notice_receiver(VALUE self)
{
    VALUE proc, old_proc;
    PGconn *conn = get_pgconn(self);

    /* If default_notice_receiver is unset, assume that the current 
     * notice receiver is the default, and save it to a global variable. 
     * This should not be a problem because the default receiver is
     * always the same, so won't vary among connections.
     */
    if(default_notice_receiver == NULL)
        default_notice_receiver = PQsetNoticeReceiver(conn, NULL, NULL);

    old_proc = rb_iv_get(self, "@notice_receiver");
    if( rb_block_given_p() ) {
        proc = rb_block_proc();
        PQsetNoticeReceiver(conn, notice_receiver_proxy, (void *)self);
    } else {
        /* if no block is given, set back to default */
        proc = Qnil;
        PQsetNoticeReceiver(conn, default_notice_receiver, NULL);
    }

    rb_iv_set(self, "@notice_receiver", proc);
    return old_proc;
}