#include <stdio.h>

void rmc(FILE* fin, FILE* fout)
{
	unsigned curr, prev = '\0';
	unsigned comment = 0, charLiteral = 0, stringLiteral = 0;

	while ((curr = fgetc(fin)) != EOF) {
		if (charLiteral) {
			fputc(curr, fout);
			if (curr == '\'' && prev != '\\') { // 'a' ends
				charLiteral = 0;
			}
			prev = (prev == '\\' && curr == '\\') ? '\0' : curr;
		} else if (stringLiteral) {
			fputc(curr, fout);
			if (curr == '\"' && prev != '\\') { // "string" ends
				stringLiteral = 0;
			}
			prev = (prev == '\\' && curr == '\\') ? '\0' : curr;
		} else if (comment) {
			if (curr == '/' && prev == '*') { /* comment ends */
				prev = '\0';
				comment = 0;
			} else { /* comment text */
				prev = curr;
			}
		} else if (prev == '/') {
			if (curr == '/') { // end of line comment
				fputc('\n', fout);
				prev = '\0';
				while (fgetc(fin) != '\n');
			} else if (curr == '*') { /* comment starts */
				prev = '\0';
				comment = 1;
			} else { // normal code
				fputc(prev, fout);
				fputc(curr, fout);
				prev = curr;
			}
		} else {
			if (curr != '/') {
				fputc(curr, fout);
			}
			charLiteral = (prev != '\\' && curr == '\'');
			stringLiteral = (prev != '\\' && curr == '\"');
			prev = (prev == '\\' && curr == '\\') ? '\0' : curr;
		}
	}
}

int main(int argc, char *argv[])
{
	FILE *fin, *fout;
	if (argc != 3) {
		fprintf(stderr, "Usage: %s <input_file> <output_file>\n", argv[0]);
		return 1;
	}

	fin = fopen(argv[1], "r");
	if(!fin)
	{
		perror("Could not open file for reading");
		return(1);
	}
	fout = fopen(argv[2], "w");

	rmc(fin, fout);

	fclose(fin);
	fclose(fout);
	return 0;
}

