/* Mail by Juha Tuominen && Pasi Ojala */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utility/tagitem.h>
#include <dos/dostags.h>
#include <clib/dos_protos.h>
#include <dos.h>
#include <time.h>
#include <exec/types.h>
#include <exec/memory.h>
#include <exec/execbase.h>
#include <libraries/dosextens.h>
#include <proto/exec.h>
#include <libraries/locale.h>
#include <clib/locale_protos.h>

/* These are only used in ks1.3 , in 2.0 we use System() */
long SyncRun(char *,char *,BPTR,BPTR);
#pragma libcall ArpBase SyncRun                 021C    109804
struct 	Library *ArpBase=NULL;

int tolower(int);

#include "/lib/users.h"
#include "/lib/iomodes.h"
#include "/lib/misc.h"

#include "mail.h"

#define STRINGARRAY
#include "maillanguage.h"

#define VERSION 	"Mail 1.19"
#define COPYRIGHT 	"Copyright 1991 Digital Design, Inc.\n"
#define UPDATED 	"31.3.95"
#define MAXMSGS		120


struct User	usr;

void __regargs __chkabort(void);
void __regargs __chkabort(void){}

void chkabort(void) {}
int CXBRK(void) { return(0);}

extern struct DosLibrary *DOSBase;
struct LocaleBase *LocaleBase=NULL;
struct Catalog *catalog=NULL;

char *vers="\0$VER: "VERSION" ("UPDATED")\n";
char	mailhome[128]="AXsh:usr/spool/mail/",
		passwdfile[80]="AXsh:etc/passwd",
		user[64]="root",
		editor[80]="editor",
		language[80]="",
		home[128]="AXsh:home/root/",
		thismachine[64]="pasbox.hro.fi",
		realname[128]="Pasi 'Albert' Ojala",
		organization[128]="AXsh development team";
char	Sendmail[MAXLINELEN]="internal",
		Routetable[MAXLINELEN]="AXsh:usr/spool/mail/Routetable",
		Aliasfile[MAXLINELEN]="AXsh:usr/spool/mail/Mailaliases",
		Spooldir[MAXLINELEN]="AXsh:usr/spool/outgoing/%s/",
		Timezone[10]="GMT";
int 	numberofmsgs,
		lastread=0,
		rows=24;
BOOL	group_reply=FALSE,
		reply=FALSE;

struct message
{	char	from[MAXNAMELEN];
	char	cc[MAXNAMELEN];
	char	date[MAXNAMELEN];
	char	subject[MAXNAMELEN];
	int		size;
	int		firstline;
	int		length;
};


struct message	messagelist[MAXMSGS];

long MyRunCommand(char *,char *,BPTR,BPTR);

void cleanexit(int error);
void openthings(void);
int  getstring(char *CommandString, BOOL echo);
int  scanmsgs(void);
void readconfig(void);
void mailmenu(void);
int  generatemail(char *to,char *sub,char *cc);
void get_time(char *);
void deletemsg(int msg);
void readmsg(int msg);
void savemsg(char *name);
void parsefrom(char *emailaddr,char *str);
int  check_mail(char *mailhome,char *loginname);


long MyRunCommand(char *command,char *args,BPTR in,BPTR out)
{
	struct TagItem stags[3];
	static char commandbuffer[256];

	if(!in)
		in=Input();
	if(!out)
		out=Output();

	if(ArpBase)
	{
		return (SyncRun(command,args,in,out));
	}
	else
	{
		sprintf(commandbuffer,"%s %s\n",command,args);
		stags[0].ti_Tag = SYS_Input;
		stags[0].ti_Data = in;
		stags[1].ti_Tag = SYS_Output;
		stags[1].ti_Data = out;
		stags[2].ti_Tag = TAG_DONE;
		return(System(commandbuffer, stags));
	}
}


void cleanexit(int error)
{
	if(ArpBase)
	{
		setmode(MODE_CONSOLE);
		CloseLibrary(ArpBase);
	}
	else
	{
		SetMode(Input(),MODE_CONSOLE);
	}

	if(LocaleBase)
	{
		if(catalog)
			CloseCatalog(catalog);
		CloseLibrary((struct Library *)LocaleBase);
	}
	exit(error);
}

void openthings(void)
{
	if(DOSBase->dl_lib.lib_Version<36)
	{
		if(!(ArpBase=OpenLibrary("arp.library",39)))
		{
			printf(printout(MSG_CANT_OPEN_ARP));
			cleanexit(10);
		}
		setmode(MODE_RAW);
	}
	else
	{
		SetMode(Input(),MODE_RAW);
	}

	/* Let's see if we're running on 2.1 .. :-) */
	LocaleBase=(struct LocaleBase *)OpenLibrary("locale.library",38L);
}


char *printout(ULONG strnum)
{
	if(catalog)
		return (char *)GetCatalogStr(catalog,strnum,AppStrings[strnum].as_Str);
	else
		return (char *)AppStrings[strnum].as_Str;
}


int getstring(char *a, BOOL echo)
{
	int i=0,found=0,z=0;
	const int b=79;

    while(!found)
    {
		if(WaitForChar(Input(),50000000))
		{
			z = Read(Input(), &a[i], 1);
		}
		else
		{
			if((SetSignal(0,0) & SIGBREAKF_CTRL_C))
			{
				printf(printout(MSG_BREAK));
				a[i] = '\0';
				return -1;
			}
			continue;
		}

		if(z<1 || a[i]==0x03 || (SetSignal(0,0) & SIGBREAKF_CTRL_C))
		{
			printf(printout(MSG_BREAK));
			a[i] = '\0';
			return -1;
		}

    	if(a[i]=='\n' || a[i]=='\r')
    	{
			found=1;
    		a[i]='\0';
    	}
    	else
    	{
			if(a[i]==0x7f || a[i]==0x08)
    		{
				if(i>0)
				{
					if(echo)
						printf("\010 \010");
					i--;
				}
			}
   			else
   			{
				if(i<b-2 && a[i]>0x1f && (a[i]<0x80 || a[i]>0x9f))
				{
					if(echo)
						Write(Output(),&a[i],1);
					i++;
				}
			}
   		}
	}
	printf("\n");
	return 0;
}


int scanmsgs(void)
{
	FILE	*fp;
	char	thisline[MAXNAMELEN],temp[MAXNAMELEN];
	int		length=0,size=0,mode,
			counter=0,count=0;

	sprintf(temp,"%s%s",mailhome,user);
	if(!(fp=fopen(temp,"r")))
	{
		return 0;
	}

	messagelist[0].firstline=0;
	mode=1;	/* search for end of the header */
	while(!feof(fp) && counter<MAXMSGS)
	{
		if(fgets(thisline,MAXNAMELEN,fp)==0)
			break;
		if(feof(fp))
			break;

		if(strlen(thisline))
			thisline[strlen(thisline)-1]=0;

		count++;
		length++;

		if(mode==0)	/* message body or between :-) */
		{
			if(!strnicmp(thisline,"From ",5))
			{
				messagelist[counter].length=length-1;
				messagelist[counter++].size=size;
				length=1;
				size=0;
				messagelist[counter].firstline=count-1;

				messagelist[counter].from[0]=0;
				messagelist[counter].cc[0]=0;
				messagelist[counter].date[0]=0;
				messagelist[counter].subject[0]=0;

				mode=1;
			}
		}
		else
		if(mode==1)
		{
			if(!thisline[0] || !strcmp(thisline,"."))	/* end of header/message */
				mode=0;

			if(!strnicmp("From: ",thisline,6))
				strcpy(messagelist[counter].from,thisline+6);
			if(!strnicmp("Cc: ",thisline,4))
				strcpy(messagelist[counter].cc,thisline+4);
			if(!strnicmp("Date: ",thisline,6))
				strcpy(messagelist[counter].date,thisline+6);
			if(!strnicmp("Subject: ",thisline,9))
				strcpy(messagelist[counter].subject,thisline+9);
		}
		size+=strlen(thisline);
	}
	if(length)
	{
		messagelist[counter].length=length;
		messagelist[counter++].size=size;
	}

	fclose(fp);
	return counter;
}

void readconfig(void)
{
	FILE	*fp;
	char	thisline[82],
			nextline[82],
			temp[82];

	if(fp=fopen("AXsh:etc/rc","rb"))
	{
		while(!feof(fp))
		{
			if(fgets(thisline,80,fp)==0)
				break;
			if(thisline[0]=='%')
			{
				if(fgets(nextline,80,fp)==0)
					break;
				nextline[strlen(nextline)-1]=0;

				if(!strnicmp("%thismachine:",thisline,13))
					strcpy(thismachine,nextline);
				if(!strnicmp("%passwdfile:",thisline,12))
					strncpy(passwdfile,nextline,80);
				if(!strnicmp("%organization:",thisline,14))
					strcpy(organization,nextline);
				if(!strnicmp("%spooldir:",thisline,10))
					strcpy(Spooldir,nextline);
				if(!strnicmp("%timezone:",thisline,10))
				{
					strncpy(Timezone,nextline,9);
					Timezone[9]=0;
				}
			}
		}
		fclose(fp);
	}
	else
	{
		printf(printout(MSG_NO_RC));
		cleanexit(0);
	}

	if(fp=fopen("AXsh:etc/rc.mail","rb"))
	{
		while(!feof(fp))
		{
			if(fgets(thisline,80,fp)==0)
				break;
			if(thisline[0]=='%')
			{
				if(fgets(nextline,80,fp)==0)
					break;
				nextline[strlen(nextline)-1]=0;

				if(!strnicmp("%mailhome:",thisline,10))
					strcpy(mailhome,nextline);
				if(!strnicmp("%sendmail:",thisline,10))
					strcpy(Sendmail,nextline);
				if(!strnicmp("%routetable:",thisline,12))
					strcpy(Routetable,nextline);
				if(!strnicmp("%aliasfile:",thisline,11))
					strcpy(Aliasfile,nextline);
			}
		}
		fclose(fp);
	}

    /* read user's config */
	who(COM_GET,NULL,"user",user);
	who(COM_GET,NULL,"language",language);
	who(COM_GET,NULL,"home",home);
	who(COM_GET,NULL,"realname",realname);
	who(COM_GET,NULL,"visual",editor);	/* default was 'editor' */
	who(COM_GET,NULL,"rows",temp);
	rows=atoi(temp);
	if(!rows)	rows=24;	/* default */
	if(rows<5)	rows=5;
	if(rows>100)	rows=100;
}

void mailmenu(void)
{
	FILE	*fp,*fp2;
	int		i,j,messu;
	char 	com[128],temp[128],to[160],subject[160],
			prompt[]="Mail menu> ";
	BOOL	exitbit=FALSE,
			show_headers=TRUE;

	sprintf(com,"%s.mailrc",home);
	if(!(fp=fopen(com,"r")))
	{
		if(!(fp=fopen(com,"w")))
		{
			printf(printout(MSG_CANT_CREATE),".mailrc");
			cleanexit(0);
		}
		else
		{
			fprintf(fp,"%d\n",lastread);
			fclose(fp);
		}
	}
	else
	{
		fgets(com,10,fp);
		lastread=atoi(com);
		fclose(fp);
	}
	com[0]=0;
	numberofmsgs=scanmsgs();
	if(!numberofmsgs)
	{
		printf(printout(MSG_NO_MAIL_FOR),user);
		sprintf(temp,"%s%s",mailhome,user);
		DeleteFile(temp);
		cleanexit(0);
	}

	if(lastread>=numberofmsgs)
		lastread=numberofmsgs-1;
	while(com[0]!='x' && !exitbit)
	{
		if(check_mail(mailhome,user))
		{
			numberofmsgs=scanmsgs();
			printf(printout(MSG_NEW_MAIL_ARRIVED));
		}
		if(!show_headers)
		{
			printf("%s",prompt);
			if(getstring(com,TRUE))
				cleanexit(0);
		}
		if((com[0]==0 || com[0]=='n') && !show_headers)
		{
			if(lastread<numberofmsgs-1)
				readmsg(++lastread);
			else
				printf(printout(MSG_LAST_MESSAGE));
		}
		if(com[0]=='h' || show_headers)
		{
			show_headers=FALSE;
			for(i=0;i<numberofmsgs;i++)
			{
				if(i==lastread)		printf(">");
				else 				printf(" ");
				printf("%d %s %s %d/%d %s\n",i+1, messagelist[i].from, messagelist[i].date, messagelist[i].length, messagelist[i].size, messagelist[i].subject);
			}
		}
		if(com[0]=='?')
		{
			printf(printout(MSG_MAIL_HELP));
		}
		if(com[0]=='q')
		{
			if(numberofmsgs)
			{
				sprintf(temp,"%s%s",mailhome,user);
				if(fp=fopen(temp,"r"))
				{
					sprintf(temp,"%smbox",home);
					if(fp2=fopen(temp,"a"))
					{
						while(temp[0])
						{
							if(fgets(temp,80,fp)==0)
								break;
							fputs(temp,fp2);
						}
						fclose(fp2);
					}
					else
					{
						printf(printout(MSG_CANT_OPEN),"mbox");
						cleanexit(0);
					}
					fclose(fp);
				}
				else
				{
					printf(printout(MSG_CANT_OPEN),temp);
					cleanexit(0);
				}
			}
			sprintf(temp,"%s%s",mailhome,user);
			if(remove(temp))
				printf(printout(MSG_CANT_DELETE),temp);
			lastread=0;
			printf(printout(MSG_SAVED_MESSAGES),numberofmsgs,"mbox");
			exitbit=TRUE;
		}
		if(com[0]=='s')
		{
			j=0;
			while(com[j]!=' ') j++;
			while(com[j]==' ') j++;
			savemsg(com+j);
		}

		if(com[0]=='r')
		{
			group_reply=FALSE;
			reply=TRUE;
			if(lastread<1)
				lastread=1;
			if(strnicmp(messagelist[lastread].subject,"Re:",3))
				sprintf(subject,"Re:%s",messagelist[lastread].subject);
			else
				strcpy(subject,messagelist[lastread].subject);
			parsefrom(to,messagelist[lastread].from);

			if(generatemail(to,subject,""))
				cleanexit(0);
			numberofmsgs=scanmsgs();
		}
		if(com[0]=='R')
		{
			group_reply=reply=TRUE;
			if(lastread<1)
			lastread=1;
			if(strnicmp(messagelist[lastread].subject,"Re:",3))
				sprintf(subject,"Re:%s",messagelist[lastread].subject);
			else
				strcpy(subject,messagelist[lastread].subject);
			parsefrom(to,messagelist[lastread].from);

			if(generatemail(to,subject,messagelist[lastread].cc))
				cleanexit(0);
			numberofmsgs=scanmsgs();
		}
		if(com[0]=='d')
		{
			j=0;
			while(com[j]!=' ') j++;
			while(com[j]==' ') j++;
			i=atoi(com+j);
			if(i>0 && i<=numberofmsgs)
			{
				deletemsg(i-1);
				show_headers=TRUE;
				com[0]=0;
				if(!numberofmsgs) exitbit=TRUE;
				if(lastread>=numberofmsgs)	lastread=numberofmsgs-1;
			}
		}
		if(com[0]=='m')
		{
			group_reply=reply=FALSE;
			j=0;
			while(com[j]!=' ') j++;
			while(com[j]==' ') j++;
			strcpy(to,com+j);
			if(generatemail(to,"",""))
				cleanexit(0);
			numberofmsgs=scanmsgs();
		}
		messu=atoi(com);
		if(messu>0 && messu<=numberofmsgs)
		{
			readmsg(messu-1);
			lastread=messu-1;
		}
	}
	sprintf(com,"%s.mailrc",home);
	if(!(fp=fopen(com,"w")))
	{
		printf(printout(MSG_CANT_OPEN),".mailrc");
		cleanexit(0);
	}
	else
	{
		sprintf(com,"%d",lastread);
		fputs(com,fp);
		fclose(fp);
	}
}

void savemsg(char *name)
{
	FILE	*fpsource, *fpdest;
	char	temp[128];
	int		i;

	sprintf(temp,"%s%s",mailhome,user);
	if(fpsource=fopen(temp,"r"))
	{
		sprintf(temp,"%s%s",home,name);
		if(fpdest=fopen(temp,"a"))
		{
			for(i=0;i<messagelist[lastread].firstline;i++)
				fgets(temp,100,fpsource);
			for(i=0;i<=messagelist[lastread].length;i++)
			{
				fgets(temp,100,fpsource);
				fputs(temp,fpdest);
			}
			fclose(fpdest);
		}
		else
			printf(printout(MSG_CANT_OPEN),temp);
		fclose(fpsource);
	}
	else
		printf(printout(MSG_CANT_OPEN),temp);
}

void readmsg(int msg)
{
	FILE	*fp;
	char	temp[128],c;
	int		i,j=0,lines=0;

	sprintf(temp,"%s%s",mailhome,user);
	if(fp=fopen(temp,"r"))
	{
		printf(printout(MSG_MESSAGE),msg+1);
		for(i=0;i<messagelist[msg].firstline;i++)
			fgets(temp,80,fp);
		for(i=0;i<messagelist[msg].length;i++)
		{
			fgets(temp,80,fp);
			if(++lines>(rows-2))
			{
				j=0;
				while(!j)
				{
					printf("\033[7m-More-\033[m");
					while(!WaitForChar(Input(),60000000));
					if(Read(Input(),&c,1) != 1)
					{
						j=2;
						break;
					}
					if(SetSignal(0,0) & SIGBREAKF_CTRL_C)
					{
						j=2;
						break;
					}
					printf("\b\b\b\b\b\b\033[K");

					switch(c)
					{
					case 'h':
						printf(printout(MSG_PAGER_HELP));
						break;
					case 0x03:
					case 'q':
						j=2;
						break;	/* quit== ok */
					case ' ':
						lines=0;	/* full page */
						j=1;
						break;
					case 0x0a:
					case 0x0d:
						lines--;	/* one line */
						j=1;
						break;
					case 'd':
						lines-=(rows-2)/2+1;	/* half page */
						j=1;
						break;
					default:
						printf(printout(MSG_H_FOR_HELP));
					}
				}
			}
			if(j==2)
				break;
			printf("%s",temp);
		}
		fclose(fp);
	}
	else
		printf(printout(MSG_CANT_OPEN),temp);
}

void deletemsg(int msg)
{
	FILE	*fpsource, *fpdest;
	char	temp[128], com[128];
	int		i;
	BOOL	ok=FALSE;

	sprintf(temp,"%s%s",mailhome,user);
	if(fpsource=fopen(temp,"r"))
	{
		sprintf(temp,"%s.%smailtemp",mailhome,user);
		if(fpdest=fopen(temp,"w"))
		{
			for(i=0;i<messagelist[msg].firstline;i++)
			{
				fgets(temp,80,fpsource);
				fputs(temp,fpdest);
			}
			for(i=0;i<messagelist[msg].length;i++)
				fgets(temp,80,fpsource);
			while(!feof(fpsource))	/* copy rest, there may be new messages */
			{
				fgets(temp,80,fpsource);
				fputs(temp,fpdest);
			}
			ok=TRUE;
			fclose(fpdest);
		}
		else
			printf(printout(MSG_CANT_OPEN),temp);
		fclose(fpsource);
	}
	else
		printf(printout(MSG_CANT_OPEN),temp);
	if(ok)
	{
		sprintf(temp,"%s%s",mailhome,user);
		if(!DeleteFile(temp))
			printf(printout(MSG_CANT_DELETE),temp);
		sprintf(temp,"%s.%smailtemp",mailhome,user);
		sprintf(com,"%s%s",mailhome,user);
		if(rename(temp,com))
			printf(printout(MSG_CANT_RENAME),temp,com);
		if((numberofmsgs=scanmsgs())<1)
		{
			DeleteFile(com);
			cleanexit(0);
		}
	}
}

#define ALLOCSIZE	16*MAXLINELEN
int generatemail(char *oldto,char *sub,char *oldcc)
{
	FILE	*fp,*fp2;
	char	*buffer,*temp,*subject,*aika,*from,*cc,*to,*arg[10];
	int		i,j,count,alku,argcount;

	if(!(buffer=(char *)AllocMem(ALLOCSIZE,MEMF_PUBLIC | MEMF_CLEAR)))
	{
		printf(printout(MSG_MEM_ALLOC_ERR),ALLOCSIZE);
		return -1;
	}
	to=(cc=(from=(aika=(subject=(temp=buffer)+MAXLINELEN)+MAXLINELEN)+MAXLINELEN)+MAXLINELEN)+MAXLINELEN;
	for(i=0;i<10;i++)
		arg[i]=to+MAXLINELEN*i+MAXLINELEN;

	if(!oldto[0])
	{
		printf("To: ");
		if(getstring(to,TRUE))
		{
			FreeMem(buffer,ALLOCSIZE);
			return -1;
		}
	}
	else
		strcpy(to,oldto);
	if(!sub[0])
	{
		printf("Subject: ");
		if(getstring(subject,TRUE))
		{
			FreeMem(buffer,ALLOCSIZE);
			return -1;
		}
	}
	else
		strcpy(subject,sub);
	if(!oldcc[0])
	{
		printf("Cc: ");
		if(getstring(cc,TRUE))
		{
			FreeMem(buffer,ALLOCSIZE);
			return -1;
		}
	}
	else
		strcpy(cc,oldcc);

	if(subject[0])
	{
		get_time(aika);
		sprintf(temp,"%s.letter",home);

		if(!(fp=fopen(temp,"w")))
		{
			printf(printout(MSG_CANT_WRITE),".letter");
			FreeMem(buffer,ALLOCSIZE);
			return -1;
		}
		else
		{
			fprintf(fp,"Date: %sSubject: %s\nOrganization: %s\n\n",aika,subject,organization);
			fclose(fp);
			sprintf(temp,"%s.letter",home);
			do
			{
				sprintf(aika,"AXsh:bin/%s",editor);
				MyRunCommand(aika,temp,Input(),Output());
				setmode(MODE_RAW);
				printf(printout(MSG_EDIT_SEND_ABORT));
				do
				{
					i=getchar();
					if(i==0x03)
						cleanexit(0);
					i=tolower(i);
				}
				while(i!='a' && i!='s' && i!='e');
				printf("%c\n",i);
				if(i=='a')
				{
					FreeMem(buffer,ALLOCSIZE);
					return 0;
				}
			}
			while(i!='s');

			sprintf(temp,"%s.signature",home);
			if(fp=fopen(temp,"r"))
			{
				sprintf(temp,"%s.letter",home);
				if(fp2=fopen(temp,"a"))
				{
					while(!feof(fp))
					{
						if(fgets(temp,80,fp)==0)
							break;
						fputs(temp,fp2);
					}
					fputc('\n',fp2);
					fclose(fp2);
				}
				else
					printf(printout(MSG_CANT_OPEN),temp);
				fclose(fp);
			}
			else
				printf(printout(MSG_CANT_OPEN),temp);
			sprintf(from,"%s@%s",user,thismachine);

			strcat(cc," ");
			strcat(cc,to);
			i=alku=argcount=0;
			while(cc[i] && argcount<10)
			{
				while(cc[i]==' ' || cc[i]==',')
					i++; /* skip soft spaces */
				alku=i;
				while(cc[i] && cc[i]!=' ' && cc[i]!=',')
					arg[argcount][i-alku]=cc[i++];
				arg[argcount][i-alku]=0;
				if(i!=alku)
					argcount++;
			}

			for(count=0;count<argcount;count++)	/* expand hostnames */
			{
				i=strlen(arg[count]);
				while(i && arg[count][i]!='@')
					i--;
				if(i)
				{
					strcpy(temp,arg[count]+i+1);
					arg[count][i+1]=0;/* mask host name */

					expandhostname(temp,temp);

					strcat(arg[count],temp);	/* append host name */
				}
				else
				{
					if(!strcmp(Sendmail,"internal"))
					{
						strcat(arg[count],"@");
						strcat(arg[count],thismachine);
					}
				}
			}

			if(!strcmp(Sendmail,"internal"))
			{
				for(count=0;count<argcount;count++)
				{
					strcpy(to,arg[count]);
					cc[0]=0;
					for(i=0;i<argcount;i++)
					{
						if(i!=count)
						{
							if(cc[0])
								strcat(cc," ");
							strcat(cc,arg[i]);
						}
					}
					sprintf(temp,"%s.letter",home);
					delivermessage(temp,from,realname,to,cc,-1,-1);
				}
			}
			else
			{
				strcpy(to,arg[0]);
				cc[0]=0;
				for(i=1;i<argcount;i++)
				{
					if(cc[0])
						strcat(cc," ");
					strcat(cc,arg[i]);
				}

				i=j=0;
				while(Sendmail[i])
				{
					if(Sendmail[i]=='%')
					{
						switch(Sendmail[i+1])
						{
						case 'f':
							strcpy(temp+j,home);
							strcat(temp,".letter");
							j+=strlen(home)+7;
							i+=2;
							break;
						case 'u':
							strcpy(temp+j,user);
							j+=strlen(user);
							i+=2;
							break;
						case 'r':
							strcpy(temp+j,realname);
							j+=strlen(realname);
							i+=2;
							break;
						case 't':
							strcpy(temp+j,to);
							j+=strlen(to);
							i+=2;
							break;
						case 'c':
							strcpy(temp+j,cc);
							j+=strlen(cc);
							i+=2;
							break;
						default:
							i++;
						}
					}
					else
						temp[j++]=Sendmail[i++];
				}
				temp[j]=0;
			/*	printf("%s\n",temp);*/
				Execute(temp, NULL, Output());
			}
		}
	}
	FreeMem(buffer,ALLOCSIZE);
	return 0;
}


void parsefrom(char *emailaddr,char *str)
{
	int i=0,j=0,lmode=1;

	while(str[i])
	{
		switch(str[i])
		{
		case '\"':
			break;
		case '(':
			lmode=0;
			break;
		case ')':
			lmode=1;
			break;
		case '<':
			j=0;
			break;
		case '>':
			emailaddr[j]='\0';
			return;
		default:
			if(lmode)
				emailaddr[j++]=str[i];
		}
		i++;
	}
	emailaddr[j]='\0';
	i=0;
	while(emailaddr[i] && emailaddr[i]==' ')
		i++;
	if(i)
		strcpy(emailaddr,emailaddr+i);	/* remove leading spaces */
	i=0;
	while(emailaddr[i] && emailaddr[i]!=' ')
		i++;
	emailaddr[i]='\0';			/* take only first word */
}

int check_mail(char *mailhome,char *loginname)
{
	static struct DateStamp lastmail={0,0,0};
	static long mailsize=0;
	struct FileInfoBlock fib;
	int error=0;
	BPTR lock;
	char temp[200];

	if(lastmail.ds_Days==-1 || !mailhome || !loginname)	/* first time around here get date */
	{
		DateStamp(&lastmail);
		return 0;
	}

	sprintf(temp,"%s%s",mailhome,loginname);	/* any new mail to user? */
	if(lock=Lock(temp,ACCESS_READ))
	{
		if(Examine(lock,&fib))
		{
			if(lastmail.ds_Days<fib.fib_Date.ds_Days ||
				((lastmail.ds_Days==fib.fib_Date.ds_Days) && (lastmail.ds_Minute<fib.fib_Date.ds_Minute)) ||
				((lastmail.ds_Days==fib.fib_Date.ds_Days) && (lastmail.ds_Minute==fib.fib_Date.ds_Minute) && lastmail.ds_Tick<fib.fib_Date.ds_Tick))
			{
			    if(fib.fib_Size>mailsize)
			    {
	    			error=-1;
	    		}
			}
    		mailsize=fib.fib_Size;
			lastmail=fib.fib_Date;	/* remember the date */
		}
		UnLock(lock);
	}
	/* else no mail at all */
	return error;
}


void main(int argc, char *argv[])
{
	setvbuf(stdout,NULL,_IONBF,0);
	printf("\n");
	printf(vers+7);
	printf(COPYRIGHT);
	openthings();
	readconfig();
	check_mail(NULL,NULL);

	if(LocaleBase && language[0])
	{
		catalog=(struct Catalog *)OpenCatalog(NULL,"AXsh.mail.catalog",OC_Language,language,TAG_DONE);
	}

	switch(argc)
	{
	case 2:
		generatemail(argv[1],"","");
		break;
	case 3:
		generatemail(argv[1],argv[2],"");
		break;
	case 4:
		generatemail(argv[1],argv[2],argv[3]);
		break;
	default:
		mailmenu();
	}
	cleanexit(0);
}
