/* 
Escape-c: converts an ASCII string (stdin) 
into a valid C/C++ string (stdout).             
Basically just adds quotes and escapes.     
*/
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <math.h>

/*
Convert the characters in the input string to 
C/C++ escape codes on the output string.
Wraps output in quotes.
*/
void c_stringify(const char *in,char *out)
{
	*out++='\"';
	while (*in!='\0')
	{
		char c=*in;
		switch (c)
		{
#define APPEND(str) strcpy(out,str); out+=strlen(str)
		case '\"': APPEND("\\\""); break;
		case '\\': APPEND("\\\\"); break;
		case '\n': APPEND("\\n"); break;
		case '\r': APPEND("\\r"); break;
		case '\f': APPEND("\\f"); break;
		case '\t': APPEND("\t"); break;
		case (char)0x7F: APPEND("\\x7F"); break;
//		case '%'://I'll quote this, too-- for printf's sake
//			APPEND("\\x25"); break;
		default://All other characters
			if ((c<32) || (c>=127))
			{//Is a control character-- escape into a hex code
				sprintf(out,"\\x%02x",(int)c);
				out+=4;
			} else
			//Is an ordinary printing ASCII character
				*out++=c;
		}
		in++;
	}
	//Finish with a quote and terminating NULL
	*out++='\"';
	*out++='\0';
}

int main(int argc,char *argv[])
{
	char lineIn[1000],lineOut[1000];
	if (argc==2)
		{printf("Usage: <stdin> escape <stdout>\n\n"
		"Quotes and escapes the given string into a C/C++ string.\n"); exit(1);}
	while (NULL!=fgets(lineIn,1000,stdin))
	{
		c_stringify(lineIn,lineOut);
		fprintf(stdout,"%s\n",lineOut);
	}
	return 0;
}


