/*
 *  This program extracts all C style comments from the input file and
 *  prints them to stdout.  It uses a simple state machine to parse the
 *  input.  Below is the state table; basically if it makes it to S2 then
 *  you've found a comment, until it reaches S4 where the comment ends.
 *
 *       S1 -> S2 on '/', otherwise S1 -> S1
 *       S2 -> S3 on '*', otherwise S2 -> S1
 *       S3 -> S4 on '*', otherwise S3 -> S3
 *       S4 -> S1 on '/', S4 -> S4 on '*', otherwise S4 -> S3
 */
#include <stdio.h>

main(argc, argv)
int argc;
char *argv[];
{
	FILE *fp;
	int state = 1;
	char c;

	if (argc != 2) {
		fprintf(stderr, "Usage: print-c-comments <file>\n");
		exit(1);
	}
	if (argv[1][0] == '-') {
		fp = stdin;
	} else if ((fp = fopen(argv[1], "r")) == NULL) {
		perror(argv[1]);
		exit(1);
	}
	while ((c = getc(fp)) != EOF) {
		switch (state) {
		case 1:
			if (c == '/') 
				state = 2;
			break;
		case 2:
			if (c == '*') {
				putchar('/');
				putchar('*');
				state = 3;
			} else 
				state = 1;
			break;
		case 3:
			putchar(c);
			if (c == '*') 
				state = 4;
			break;
		case 4:
			putchar(c);
			if (c == '/') {
				putchar('\n');
				state = 1;
			} else if (c == '*') {
				state = 4;
			} else {
				state = 3;
			}
			break;
		default:
			fprintf(stderr, "Fatal Internal Error\n");
			exit(1);
		}
	}
	fclose(fp);
	exit(0);
}
