/*
 * m k f a c e s . c
 *
 * This program reads the file with the list of smileys and writes
 * out an initialized data structure containing the smileys.
 * 
 * It assumes the smileys are each on one line, followed by a tab,
 * followed by some description.
 *
 * DaviD W. Sanderson
 */

#include <stdio.h>

/* avoid the possible <string.h> vs <strings.h> dilemma */

extern int
	strcmp();
extern char *
	strcpy();

/* turn string into C string initialization */

static char    *
enquote(s)
	char           *s;
{
	static char     ar[1024];
	char           *t = ar;

	for (; *s; s++)
	{
		switch (*s)
		{
		case '\\':
		case '\"':
			*t++ = '\\';
		}
		*t++ = *s;
	}
	*t = '\0';
	return ar;
}

int
main()
{
	char            prev[1024];	/* previous face */
	char            face[1024];	/* current face */
	char            desc[1024];	/* current description */
	char		nl[2];		/* for newline at end-of-line */
	int             lineno = 0;	/* number of current line */

	/* prologue */

	(void) printf("#include \"smiley.h\"\n");
	(void) printf("struct smiley faces[] = {\n");

	/* process each smiley line */

	prev[0] = 0;		/* initialize prev to null string */

	/*
	 * If simply matched literal \n at the end of the string, scanf
	 * would skip leading white space on the next line.
	 * This is not what I want.
	 */
	while (scanf("%[^\t]\t%[^\n]%[\n]", face, desc, nl) == 3)
	{
		if (strcmp(prev, face))
		{

			/*
			 * Since this face differs from the last one,
			 * prepare to start a new entry.
			 * 
			 * Complete the previous entry if there was one.
			 */
			if (lineno > 0)
			{
				(void) fputs("\"},\n", stdout);
			}

			(void) printf("{\"%s\",\"", enquote(face));
		}
		else
		{

			/*
			 * Since this face is the same as the last
			 * one, simply continue the description.
			 */
			(void) fputs("\\n\\t", stdout);
		}

		/* write the current description line */
		(void) fputs(enquote(desc), stdout);

		lineno++;
		(void) strcpy(prev, face);
	}

	(void) fputs("\"}\n", stdout);	/* complete the last entry */

	/* epilogue */

	(void) printf("};\n");
	(void) printf("int nfaces = sizeof(faces)/sizeof(struct smiley);\n");

	return 0;
}
