/* Syntax: ascii2mush < infile > outfile
 *
 * This program takes data from an input stream, and escapes it into a
 * format suitable for pasting onto a PennMUSH. The following
 * transformations are performed:
 *
 * '\n' into %r
 * '\t' into %t
 * multiple spaces into %b or [space(n)], whichever is shorter
 * single space at the beginning of the line into %b
 * other single spaces untouched
 * '\' added before: % ; [ ] { } \
 *
 * Copyright (c) 2004 by Philip Mak <pmak@aaanime.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include <stdio.h>

main() {
	char c, d;
	int start_of_line = 1;
	int num_spaces;
	int i;

	while ((c = getchar()) != EOF) {
		switch (c) {
			case ' ':
				/* Count the number of consecutive spaces */
				num_spaces = 1;
				while (d = getchar()) {
					if (d == ' ') {
						num_spaces++;
					} else {
						ungetc(d, stdin);
						break;
					}
				}

				if (num_spaces == 1 && !start_of_line) {
					/* A single space in the middle of the line */
					printf(" ");
				} else if (num_spaces > 5) {
					/* More than 5 consecutive spaces */
					printf("[space(%d)]", num_spaces);
				} else {
					for (i = 0; i < num_spaces; i++)
						printf("%%b");
				}
				break;
			case '\n':
				/* Suppress last newline in file */
				if ((d = getchar()) != EOF) {
					ungetc(d, stdin);
					printf("%%r");
				}
				break;
			case '\t':
				printf("%%t");
				break;
			case '%':
			case ';':
			case '[':
			case ']':
			case '{':
			case '}':
			case '\\':
				printf("\\%c", c);
				break;
			default:
				putchar(c);
				break;
		}

		/* Determine whether we are at the start of a line */
		start_of_line = c == '\n';
	}
}
