#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <descrip.h>
#include "bboard.h"

#define SEPARATOR "\xff"

static void dig_build_topic(FILE * note, FILE * com_file, struct list_info *
	list, char * subj);
static int dig_build_reply(FILE * note, FILE * com_file, struct list_info *
	list, int cur_count);
static void dig_kill_files(FILE * com_file);
static void new_dlg_fn(char * name, char * conf, int count);
static void copy_with_scan(FILE * o, FILE * i, int trg, int err, char
	scan_char);

static char * files_to_del;

void digest_run(FILE * note, struct rule_info * rule, struct list_info * list)
{
    char * top_subj;			/* Topic subject */
    FILE * com_file;			/* Command file */
    int i;				/* Counter for text files */

    /* Get the subject for the topic */

    top_subj = find_source(rule->id_subj);
#ifdef DEBUG
    printf("digest_run: top_subj = %ld\n", top_subj);
    if (top_subj) {
	printf("digest_run: top_subj = >%s<\n", top_subj);
    }
#endif

    if (!top_subj)			top_subj = "";
    subj_text_fondle(top_subj);

    /* Open the command file */

    com_file = com_open();

    /* Need a string for text files that we need to delete */

    files_to_del = xmalloc(10000);

    /* Set the name and jump into Notes */

    if (list->conf_user[0]) {
	fprintf(com_file, "$ setuname %s\n", list->conf_user);
	setuname_used = TRUE;
    }

    fprintf(com_file, "$ notes/nonotebook 0::%s\n", list->conf_name);
    fputs("set moderator\n", com_file);

    /* Build the topic, first off */

    dig_build_topic(note, com_file, list, top_subj);

    /* Now on to the serious stuff... */
    /* Do it until we fall off the end... */

    for (i = 1; !feof(note); i++) {

	/* See if we've received any interactive messages to fondle. */

	process_message();

	/* Now go build another reply */

	if (!dig_build_reply(note, com_file, list, i)) {
	    break;
	}
    }

    /* Close up time */

    fputs("exit\n", com_file);

    /* Build commands to delete files */

    dig_kill_files(com_file);

    /* Lose the allocated memory */

    xfree(files_to_del);

    /* And we've added a lot of notes */

    com_close(i+1);
}

/* Build the initial topic for a new digest */

static void dig_build_topic(FILE * note, FILE * com_file, struct list_info *
	list, char * subj)
{
    char text_fn[200];			/* File name of file to write to */
    FILE * text_file;

    /* Open the topic text file */

    new_dlg_fn(text_fn, list->conf_name, 0);
    text_file = fopen(text_fn, "w", "ctx=rec", "rat=cr", "rfm=var");

    /* Copy until we get to the divider */

    copy_with_scan(text_file, note, 70, 11, '-');

    fclose(text_file);

    /* Start generating commands */

    fputs("set prof/temp/pers=\"Notes Poster Daemon\"\n", com_file);
    fprintf(com_file, "write/noed %s\n", text_fn);
    fprintf(com_file, "%s\n", subj);
    fputs("yes\n", com_file);

    /* Need to delete the text file */

    strcpy(files_to_del, text_fn);
    strcat(files_to_del, SEPARATOR);
}

/* We'll hold onto the header information here... */

#define SUBJ_LEN 99
#define FROM_LEN 255
#define END_LEN 80

static char subj_text[SUBJ_LEN+SLOP_LEN];
static char from_text[FROM_LEN+SLOP_LEN];
static char end_text[END_LEN+SLOP_LEN];

/* Header information to pull in */

static struct source_info dig_src[] = {
    { "SB", "subject:", SUBJ_LEN, subj_text },
    { "FR", "from:",    FROM_LEN, from_text },
    { "EN", "end of ",  END_LEN,  end_text },
    { "",   "",         0,   NULL}
};

/* Build an individual reply */

static int dig_build_reply(FILE * note, FILE * com_file, struct list_info *
	list, int cur_count)
{
    char text_fn[200];			/* File name of text file */
    FILE * text_file;
    int trig_level;
    int error_level;

    /* Fill in the header information */

    scan_header(note, dig_src);

    /* Did we reach the "End of ...." message? */

    if (end_text[0] && !subj_text[0] && !from_text[0]) {
	return (FALSE);
    }

    /* Fix the From and Subj lines */

#ifdef DEBUG
    printf("Digest: From = >%s<\n", from_text);
    printf("Digest: Subject = >%s<\n", subj_text);
#endif

    from_text_fondle(from_text);
    subj_text_fondle(subj_text);

#ifdef DEBUG
    printf("Digest: Fondled from = >%s<\n", from_text);
    printf("Digest: Fondled subj = >%s<\n", subj_text);
#endif

    /* Time to build a new text file */

    new_dlg_fn(text_fn, list->conf_name, cur_count);
    text_file = fopen(text_fn, "w", "ctx=rec", "rat=cr", "rfm=var");

    /* Figure out what we need to look for */

    if (!digest_find(list->new_topic_interval, &trig_level, &error_level)) {
	trig_level = 30;		/* If not found, use defaults */
	error_level = 1;
    }

    /* Now copy over the text */

    copy_with_scan(text_file, note, trig_level, error_level, '-');

    fclose(text_file);

    /* Now let's build the appropriate commands */

    fprintf(com_file, "set prof/temp/pers=\"%s\"\n", from_text);
    fprintf(com_file, "reply/noed %s\n", text_fn);
    fprintf(com_file, "%s\n", subj_text);
    fputs("yes\n", com_file);

    /* Need to delete the text file */

    strcat(files_to_del, text_fn);
    strcat(files_to_del, SEPARATOR);

    /* Yes, we really did something */

    return (TRUE);
}

/* Write commands to delete all of the text files that we came up with */

static void dig_kill_files(FILE * com_file)
{
    char * next_file;

    /* Start searching through the list of files to delete */

    next_file = strtok(files_to_del, SEPARATOR);

    while (next_file) {
	fprintf(com_file, "$ delete %s;*\n", next_file);
	next_file = strtok(NULL, SEPARATOR);
    };
}

/* Build a filename for a digest text file */

static void new_dlg_fn(char * name, char * conf, int count)
{
    SYSTIM cur_time;
    struct $NUMTIM t;

    get_time(cur_time);
    get_numtim(&t, cur_time);

    sprintf(name, "%s%s.%04d-%04d%02d-%d", scratch_dir.dsc$a_pointer, conf,
	    t.month * 100 + t.day, t.hour * 100 + t.minute, t.second,
	    count);
}

/* Copy text until a separator is found */

static void copy_with_scan(FILE * o, FILE * i, int trg, int err,
	char scan_char)
{
    int cur_count;			/* How many found? */
    char * t;				/* Search through separator line */

    while (TRUE) {
	if (!fgets(temp, 255, i)) {	/* Got a line? */
	    return;			/* Nope, it's all over... */
	}

	/* Might we have found a separator? */

	if (temp[0] == scan_char) {

	    /* We don't want trailing blanks */

	    strcpy(temp+256, temp);
	    trim_end(temp+256);

	    /* How many contiguous characters are there? */

	    for (cur_count = 0, t = temp+256; *t == scan_char; t++, cur_count++);

	    /* Is there anything after the contiguous scan_char's? */

	    if (*t && *t != '\n') {
		goto copy_with_scan_write;
	    }

	    /* Did we find enough? */

	    if ((cur_count >= trg-err) && (cur_count <= trg+err)) {
		return;
	    }
	}
    copy_with_scan_write:
	fputs(temp, o); 		/* And, finally, write it out. */
    }
}
