#define GAIM_PLUGINS

// grumpy.c -- inspired by the spell-check plugin, but i thought it
// would be too messy to tack this onto its split-on-punctuation
// logic.
//
// Copyright 2000 Decklin Foster, <decklin@red-bean.com>, GPLed (see
// the top-level gaim source dir for your copy).

#include "gaim.h"
#include <string.h>
#include <stdlib.h>

// isn't this next line just disgusting?

const char *munge = "<b></b>";

// and we put that after the first char in any of these. "O:-)" has
// it's own graphic, but will be caught looking for ":-)". Entries on
// the same line have the same graphic.

const char *smileys[] = {
    ":-D",
    ":-!",
    ":-X",
    ":'(",
    ":-[",
    ":-*",
    ":-$",
    ":-(", ":(",
    "=-O",
    ":-)", ":)",
    "8-)",
    ":-/",
    ":-P", ":P", ":-p", ":p",
    ";-)", ";)",
    ">:o",
    NULL
};

// this is bad -- free should barf if dest is auto. either g_free
// checks this or i'm very lucky. need a better way to prevent
// memleaks here. (when i doubt, blame the plugin interface for
// forcing me to munge strings like this ;-)

static void insert_str(char **dest, size_t pos, const char *src)
{
    char *new = g_malloc(strlen(*dest) + strlen(src) + 1);

    //printf("  inserting '%s' into '%s' @ %d\n", src, *dest, pos);
    if (!new) {
        fprintf(stderr, "yipes! can't g_malloc.\n");
        return;
    }

    strcpy(new, *dest);
    strcpy(new+pos, src);
    strcpy(new+pos+strlen(src), *dest+pos);
    //printf("  result: '%s'\n", new);

    g_free(*dest);
    *dest = new;
}

// There are probably more efficent ways to do this, given that half
// our keys start with ':'. Do I care? ha!

static void munge_smileys(struct gaim_connection *gc, char *buddy,
    char **im, void *cb_data)
{
    const char **s;
    char *p;

    if (!im) return;
    //printf("im: '%s'\n", *im);

    for (s = smileys; *s; s++) {
        //printf("looking for: '%s'\n", *s);
        p = *im;
        while (p = strstr(p, *s)) {
            //printf(" got substr: '%s'\n", p);
            insert_str(im, p - *im + 1, munge);
            //printf(" advancing %d chars\n", strlen(*s));
            p += strlen(*s);
            //printf(" p is now: '%s'\n", p);
        }
    }
}

// what's my name? say my name, bitch!

char *name()
{
    return "Grumpifier";
}

char *description()
{
    return "Munges smiley faces so that your buddy's AIM software won't "
        "display them as pictures. Fight the evil forces of cuteness!";
}

// these GAIM weirdos really need to use capital letters for their
// constants or something. 'handle'? wuzzat? (hi Rob ;-)

char *gaim_plugin_init(GModule *handle)
{
    gaim_signal_connect(handle, event_im_send, munge_smileys, NULL);
    gaim_signal_connect(handle, event_chat_send, munge_smileys, NULL);
    return NULL;
}

void gaim_plugin_remove()
{
    // dave's not here, man...
}

void gaim_plugin_config()
{
    // FIXME: make a dialog box for stupid people
}
