/* Stripper.c - Strips whitespace from INF file. */

#include <windows.h>
#include <stdio.h>

void Strip(FILE * pInput, FILE * pOutput)
{
	BOOL fPreviousLineBlank = TRUE;
	BOOL fThisLineBlank = TRUE;
	char chPrevious = '\0';
	char chThis;
	char szWhiteStore[1024];
	int cchWhiteStore = 0;
	char const szEmitNewLine[] = "^^";
	int const cchEmitNewLine = sizeof(szEmitNewLine) - 1;
	int iEmitNewLine = 0;

	while ((chThis = fgetc(pInput)) != EOF)
	{
		if (chThis == szEmitNewLine[iEmitNewLine])
		{
			if (cchWhiteStore > 0)
			{
				szWhiteStore[cchWhiteStore] = '\0';
				fputs(szWhiteStore, pOutput);
				cchWhiteStore = 0;
			}

			if (++iEmitNewLine != cchEmitNewLine)
				continue;

			chThis = '\n';
			iEmitNewLine = 0;
		}

		if (iEmitNewLine > 0)
		{
			int i;

			for (i = 0; i < iEmitNewLine; i++)
				fputc(szEmitNewLine[i], pOutput);

			iEmitNewLine = 0;
		}

		switch (chThis)
		{
			case ' ':
			case '\t':
			{
				if (!fThisLineBlank)
					szWhiteStore[cchWhiteStore++] = chThis;

				break;
			}

			case '\n':
			{
				cchWhiteStore = 0;

#if defined(NO_BLANK_LINES)

				if (!fThisLineBlank)
					fputc(chThis, pOutput);

#else	// Multiple blank lines collapsed to single blank line.

				if (!(fThisLineBlank && fPreviousLineBlank))
					fputc(chThis, pOutput);

#endif

				fPreviousLineBlank = fThisLineBlank;
				fThisLineBlank = TRUE;

				break;
			}

			default:
			{
				fThisLineBlank = FALSE;

				if (cchWhiteStore > 0)
				{
					szWhiteStore[cchWhiteStore] = '\0';
					fputs(szWhiteStore, pOutput);
					cchWhiteStore = 0;
				}

				if (!(chThis == '\\' && chPrevious == '\\'))
					fputc(chThis, pOutput);

				break;
			}
		}

		chPrevious = chThis;
	}

	if (ferror(pInput))
		perror(NULL);
}

int main(int argc, char ** argv)
{
	int Result = EXIT_FAILURE;
	FILE * pInput = NULL;
	FILE * pOutput = NULL;

	if (argc != 3)
	{
		printf(
			"Usage:\n"
			"\n"
			"STRIPPER input output\n"
			);
		goto Exit;
	}

	pInput = fopen(argv[1], "r");
	if (pInput == NULL)
	{
		perror(argv[1]);
		goto Error;
	}

	pOutput = fopen(argv[2], "w");
	if (pOutput == NULL)
	{
		perror(argv[2]);
		goto Error;
	}

	Strip(pInput, pOutput);

	Result = EXIT_SUCCESS;

Error:

	if (pInput)
		fclose(pInput);

	if (pOutput)
		fclose(pOutput);

Exit:

	return  Result;
}

