/*
 *	Copyright (C) 1991, 1992      TGV, Incorporated
 *
 *	Check for new mail
 *
 */
#include "mm_header.h"
#include <stdio.h>

Check_New_Mail()
{
	int fd;
	register char *cp,*cp1;
	register int i;
	int Text_Offset;
	struct Header_File_Header Header;
	struct Msg Msg;
	register struct Msg *Msgs;
	char *Text;

	/*
	 *	Open the header cache file
	 */
	fd = open("sys$login:$hdrs$mail.txt",0,0,
			"shr=get","shr=put","shr=upd");
	if (fd < 0)
		return;

	/*
	 *	Read in the header file header
	 */
	if (read(fd,&Header,sizeof(Header)) != sizeof(Header)) {
		close(fd);
		return;
	}

	/*
	 *	Seek to the last message header and read it in
	 */
	if (lseek(fd,-sizeof(struct Msg),2) < 0) {
		close(fd);
		return;
	}
	if (read(fd,&Msg,sizeof(Msg)) != sizeof(Msg)) {
		close(fd);
		return;
	}

	/*
	 *	Check for UNSEEN
	 */
	if (!(Msg.Flags & MSG_SEEN) && (Msg.Date >= Header.Last_Read)) {

		/*
		 *	Make sure there is a good FROM offset
		 */
		if (Msg.From_Size == 0) goto New_Mail1;

		/*
		 *	Read in the entire header file
		 */
		i = Header.Number_Of_Messages * sizeof(struct Msg);
		Msgs = (struct Msg *)mm_malloc(i);
		if (Msgs == 0) goto New_Mail1;
		lseek(fd,sizeof(Header),0);
		if (read(fd,Msgs,i) != i) goto New_Mail1;

		/*
		 *	Calculate the text file offset
		 */
		Text_Offset = 0;
		i = Header.Number_Of_Messages - 1;
		while(--i >= 0)
			Text_Offset += Msgs[i].Real_Size;

		/*
		 *	Open the text file and get the message
		 */
		close(fd);
		fd = open("sys$login:mail.txt",0,0,
			  "shr=get","shr=put","shr=upd");
		if (fd < 0) goto New_Mail1;
		if (lseek(fd,Text_Offset,0) != Text_Offset) goto New_Mail1;
		i = Header.Number_Of_Messages-1;
		Text = (char *)mm_malloc(Msgs[i].Real_Size);
		if (read(fd,Text,Msgs[i].Real_Size) != Msgs[i].Real_Size)
			goto New_Mail1;
		Text += Msgs[i].From_Offset;
		Text[Msgs[i].From_Size] = 0;

		/*
		 *	Get the FROM field to print
		 */
		cp = (char *)strchr(Text,'<');
		if (cp != 0) {
			cp++;
		} else {
			cp = Text;
			while(*cp &&
			      ((*cp == ' ') || (*cp == '\t'))) cp++;
		}
		if (*cp == 0) goto New_Mail1;
		cp1 = (char *)strchr(cp,'>');
		if (cp1 != 0) *cp1 = 0;

		/*
		 *	Print it
		 */
		printf("[You have mail from %s]\n",cp);
	}
	if (fd >= 0) close(fd);
	return;

New_Mail1:
	printf("        You have new mail.\n");
	if (fd >= 0) close(fd);
	return;
}
