/*
 *  hap -- a mail notification program
 * 
 *  copyright 1995 by Eric Fischer, etaoin@uchicago.edu
 * 
 *  copies of hap may be redistributed under the terms of the
 *  GNU public license, copies of which are available from
 *  the Free Software Foundation, 59 Temple Place, Boston, MA
 *  02111 USA.
 *
 */

#include "hap.h"

/**************************************************************************

   MAILBOX -> NOTIFICATION STUFF

**************************************************************************/

/* returns a big string containing ascii notifications of all the new
   mail in mailbox 'box' beginning at location 'loc'.  the pointer is
   only good until the next call.
*/

char *
getmessages (box, loc)
	mailbox box;
	long loc;
{
	hlist headerlist;
	static char *msg = 0;
	int msgnum = 0;
	static char *thequote = 0;

	FILE *f;
	long here = 0;
	int quotesleft = 0;

	char *s;

	if (msg) free (msg), msg = 0;
	if (thequote) free (thequote), thequote = 0;

	inithlist (&headerlist);

	f = fopen (box.name, "r");
	if (f == 0) {
		msg = addtostr (msg, "   * Unable to open ");
		msg = addtostr (msg, box.name);
		msg = addtostr (msg, ": ");
		msg = addtostr (msg, strerror (errno));
		msg = addtostr (msg, "\n");
		return msg;
	}

	if (loc < 0) loc = 0;

	while (here = ftell (f), s = fgetl (f)) {
		int waspostmark = ispostmark (s);

		if (waspostmark) msgnum++;

		if (here < loc) continue;

		if (waspostmark) {
			headerlist.endpoint = here;
			headerlist.msgnumint = msgnum - 1;

			/* -1 because we just incremented it for the
			   following message...
			*/

			dumpheaders (&msg, &headerlist);
			dumpquote (&msg, &thequote);
			quotesleft = wantquote;

			{
				int mboxkind = ismbox (s);

				if (mboxkind) {
					headerlist.postmark = strdupe (s + 5);
					headerlist.postmark [
					    strlen (headerlist.postmark) -
					    mboxkind
					] = 0;
				}
			}

			readheaders (&headerlist, f);
			headerlist.startpoint = here;

			continue;
		}

		if (isbabyl2 (s)) {
			clearheaders (&headerlist);
			readheaders (&headerlist, f);
		}

		if (quotesleft && nottobeignored (s)) {
			addstr (&thequote, "     ");
			addstr (&thequote, s);
			quotesleft--;
		}
	}

	fclose (f);

	headerlist.endpoint = here;
	headerlist.msgnumint = msgnum;

	dumpheaders (&msg, &headerlist);
	dumpquote (&msg, &thequote);

	return msg;
}

/* return true if this is a line of the message actually
   worth printing, instead of some quoted text or suchlike.
*/

int
nottobeignored (s)
	char *s;
{
	return (s[0] != '\n'
	    &&  s[0] != '>'
	    &&  s[0] != ':'
	    &&  !starts (s, "In article")
	    &&  !starts (s, "-----BEGIN")
	    &&  s[0] != '#'
	    &&  s[0] != '<'

	/* to keep BABYL message-terminators from getting quoted */

	    &&  s[0] != '\037');
}

