#include <stdio.h>
#include <string.h>
#include "globals.h"
#include "xemoticon.h"

int xemoticon_insert(char *gif, char *parse, int xe_count)
{
    int i, len;

    len = strlen(parse);
    if (strlen(gif) > 29)
	return xe_count;
    if (len > 29)
	return xe_count;

    if (xe_count == MAXXEMOT)
	return xe_count;

    for (i = xe_count; i > 0; i--) {
	if (len > strlen(xe_pars[i - 1])) {
	    snprintf(xe_gifs[i], 30, "%s", gif);
	    snprintf(xe_pars[i], 30, "%s", parse);
	    xe_count++;
	    return xe_count;
	}
	else {
	    snprintf(xe_gifs[i], 30, "%s", xe_gifs[i - 1]);
	    snprintf(xe_pars[i], 30, "%s", xe_pars[i - 1]);
	}
    }

    snprintf(xe_gifs[0], 30, "%s", gif);
    snprintf(xe_pars[0], 30, "%s", parse);

    xe_count++;
    return xe_count;
}

int xemoticon_load(char *dir, int xe_count)
{
    FILE *plik;
    char filename[512];
    char line[3001];
    char *k, *r, *w;
    char *gif, *egif;

    snprintf(filename, sizeof(filename), "%s/1/emots.txt", dir);
    if (!(plik = fopen(filename, "r"))) {
	// no file found
	return xe_count;
    }
    while (fgets(line, 3000, plik)) {
	k = (char *) index(line, 10);
	if (k)
	    k[0] = 0;
	k = (char *) index(line, 13);
	if (k)
	    k[0] = 0;
	if (strlen(line) > 0) {
	    k = line;
	    if (k[0] == '*')
		k++;
	    if (k[0] == '(') {
		k++;
		gif = (char *) strstr(k, "\"),\"");
		if (gif) {
		    gif += 4;
		    egif = (char *) index(gif, '"');
		    if (egif) {
			egif[0] = 0;
			for (r = k; r < gif; r++) {
			    w = (char *) index(r + 1, '"');
			    if (w) {
				w++[0] = 0;
				if (strlen(r + 1) > 0)
				    xe_count = xemoticon_insert(gif, r + 1, xe_count);
				r = w;
			    }
			}
		    }
		}
	    }
	    else {
		gif = (char *) strstr(k, "\",\"");
		if (gif) {
		    gif += 3;
		    egif = (char *) index(gif, '"');
		    if (egif) {
			egif[0] = 0;
			w = (char *) index(k + 1, '"');
			if (w) {
			    w++[0] = 0;
			    if (strlen(k + 1) > 0)
				xe_count = xemoticon_insert(gif, k + 1, xe_count);
			}
		    }
		}
	    }
	}
    }
    fclose(plik);
    return xe_count;
}
