/* cs-opt0.c - Don Yang (uguu.org) Compress whitespaces and remove comments. 04/26/05 */ /*@ -usedef @*/ #include static void Filter(FILE *infile, FILE *outfile) { int c, q, n, state; state = 0; while( (c = fgetc(infile)) != EOF ) { switch( state ) { case 1: /* quote ^ */ (void)fputc(c, outfile); if( c == (int)'\\' ) { state++; } else if( c == q ) { state = 0; } break; case 2: /* quote escape ^ */ (void)fputc(c, outfile); state--; break; case 3: /* space ^ */ if( c == (int)'/' ) { state++; } else if( c == (int)' ' || c == (int)'\t' ) { } else if( c == (int)'\n' || c == (int)'\r' ) { n = 1; } else { (void)ungetc(c, infile); (void)fputc(n != 0 ? '\n' : ' ', outfile); state = 0; } break; case 4: /* / ^ */ if( c == (int)'/' ) { state++; } else if( c == (int)'*' ) { state = 6; } else { (void)ungetc(c, infile); (void)fputc('/', outfile); state = 0; } break; case 5: /* / / ^ */ if( c == (int)'\n' || c == (int)'\r' ) state = n = 3; break; case 6: /* / * ^ */ if( c == (int)'*' ) state++; break; case 7: /* / * * ^ */ if( c == (int)'/' ) state = 3; else if( c != (int)'*' ) state--; break; default: if( c == (int)'\'' || c == (int)'\"' ) { (void)fputc(c, outfile); q = c; state = 1; } else if( c == (int)' ' || c == (int)'\t' ) { n = 0; state = 3; } else if( c == (int)'\n' || c == (int)'\r' ) { state = n = 3; } else if( c == (int)'/' ) { n = 0; state = 4; } else { (void)fputc(c, outfile); } break; } } if( state != 0 ) (void)fputc('\n', outfile); } int main(int argc, char **argv) { FILE *infile, *outfile; infile = stdin; outfile = stdout; if( argc > 1 ) { if( (infile = fopen(argv[1], "rb")) == NULL ) return printf("Can not open %s\n", argv[1]); if( argc > 2 ) { if( (outfile = fopen(argv[2], "wb+")) == NULL ) { (void)fclose(infile); return printf("Can not write to %s\n", argv[2]); } } } Filter(infile, outfile); (void)fclose(infile); (void)fclose(outfile); return 0; }