%{
/*

This is a quick-and-dirty indenter/formatter for Quake .map files.
You'll need a C compiler and lex or flex to compile this.

Copy, redistribute and alter freely.  No warranty.

Jeff Epler
jepler@inetnebr.com

*/

#include <stdio.h>
#define MAX(x,y) (fprintf(stderr,"%d %d\n",(x),(y)),(x)<(y)?(y):(x))
int indent=0;
int ilevel=4;
int chars=0;
char ichar=' ';

void indent_in(void) {
	indent += ilevel;
}

void indent_out(void) {
	if(indent>0) indent -= ilevel;
	else fprintf(stderr,"Braces don't balance\n");
}

void nl(void) {
	int i=indent;
	putchar('\n');
	for(;i>0;i--) putchar(ichar);
}

%}

%%
\{	{ putchar('{'); indent_in(); nl(); }
\}	{ indent_out(); if(chars) nl(); putchar('}'); nl(); }
^[\t ]+	{ ; }
[\t ]+  { if(chars) putchar(' '); }
\"([^"](\\\")?)*\"[\t ]*\"([^"](\\\")?)*\" { 
		char *s0, *s1, *s2;
		int i=0;
		s0=s2=yytext+1; /* Point at the beginning of the string */
		while(*s2!='\"') { /* Find the end */
			if(*s2=='\\') s2++;
			s2++;
		}
		*s2=0; /* Zot! */
		while(*s2!='\"') { /* Find beginning of second string */
			if(*s2=='\\') s2++;
			s2++;
		}
		s1=s2=s2+1; /* Point to it */
		while(*s2!='\"') { /* Find the end */
			if(*s2=='\\') s2++;
			s2++;
		}
		*s2=0; /* Zot! */
		printf("\"%s\"%*s\"%s\"",s0,MAX(40-strlen(s0),0),"",s1);
		chars=1;
	}
\n	{ if (chars) nl(); chars=0; }
.	{ chars=1; putchar(*yytext); }
