/* mailmerge.c - dean's 1st attempt @ a formletter program */
#include <stdio.h>
#include <algol68.h>
extern int $$ferr;
#define BUFSIZ 300
#define STROP '@'
#define hope
FILE		*tempptr;	/* input: template */
struct	line
{
	struct	line	*next;
	char		data[1];
};
struct	line	*template;	/* root of template */
char		*subst[10];	/* substitution strings 0 ... 9 */
char		**s;		/* tracks subst[] */
struct	line	*l;		/* tracks linked list of template lines */
struct	line	*nextline;
int		c;		/* character */
char		*p;
char	*help[]	=
{"The TEMPLATE file is your form letter. Within this letter put '@n'"
,"whenever you want a substitution: n is a digit from 0 to 9."
,"One formletter is output for every substitution set in the standard input."
,"A subst-set is a number of lines followed by a blank line."
,"@0 substitutes the 1st line of the subst-set, @1 the second and so on."
,"[will somebody please design this documentation/program! PF 28Jul84]"
,""
};
char		*myname;	/* the name of this program */
int		howmuch;	/* number of bytes in buffer */
char		buffer[BUFSIZ];	/* input buffer */

helpless(gripe)
char	*gripe;
BEGIN
char		**h;
	fprintf(stderr,"\7%s\n",gripe);
	fprintf(stderr,"usage: %s template-file-name <substitution-list >form-letters\n",myname);
	FOR	(h=help;	**h;	h++)	fprintf(stderr,"%s\n",*h);
	exit();
END

main(argc,argv)
int		argc;
char		**argv;
BEGIN
	myname = argv[0];
	IF	(argc!=2)
	THEN	helpless("I want a template-file-name!");
	FI
	IF	(!(tempptr=fopen(argv[1],"r")))
	THEN	error("\7can't open input \"%s\" $$ferr=%oo",argv[1],$$ferr);
	FI
	template = 0;
	WHILE	(fgetss(buffer,BUFSIZ,tempptr))
	DO	howmuch = strlen(buffer);
#ifndef hope
fprintf(stderr,"temp.buffer=\"%s\"\n",buffer);
#endif
		IF	(!(nextline=malloc(howmuch+3)))
		THEN	error("\7no memory");
		FI
		nextline -> next = 0;
		IF	(template)
		THEN	l -> next = nextline;
		ELSE	template = nextline;
		FI
		strcpy((l=nextline)->data,buffer);
	OD
	IF	(ferror(tempptr))
	THEN	error("\7template read error $$ferr=%oo",$$ferr);
	FI
	fclose(tempptr);
	/* here with template read in */
	s = subst;
	WHILE	(fgetss(buffer,BUFSIZ,stdin))
	DO	howmuch = strlen(buffer);
#ifndef hope
fprintf(stderr,"subst.buffer=\"%s\"\n",buffer);
#endif
		IF	(howmuch==0)
		THEN	substitute();
		ELSE	IF	(!(*s=malloc(howmuch+1)))
			THEN	error("no room");
			FI
			strcpy	(*(s++),buffer);
		FI
	OD
	IF	(ferror(stdin))
	THEN	error("\7list read error $$ferr=%oo",$$ferr);
	FI
	IF	(s>subst)
	THEN	substitute();
	FI
END

substitute()
BEGIN
	l = template;
	WHILE	(l)		/* scan each line of template */
	DO	FOR	(p=l->data;	*p;	p++)
		BEGIN	IF	(*p==STROP)
			THEN	c=*++p;
				IF	(isdigit(c))
				THEN	c=c-'0';
					IF	(c<(s-subst))
					THEN	printf("%s",subst[c]);
					/* else substute NOTHING */
					FI
				ELSE	fprintf(stderr,"\7bad character %oo='%c' after %c\n",c,c,STROP);
				FI
			ELSE	putchar(*p);
			FI
		END
		putchar('\n');
		l = l->next;
	OD
	s=subst;
END
