#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "swis.h"

static void BootTypes_AddRunType(const char* type)
{
	const char value[] = "Run DigitalCD:!Run %*0";
	char string[20];

	sprintf(string, "Alias$@RunType_%s", type);

	_swix(OS_SetVarVal, _INR(0,4), string, value, strlen(value), 0, 0);
}

#define File_BufLen 1024
static char File_Buf[File_BufLen];

static bool File_FindSection(FILE* file, const char* section, int bRestart)
{
	int  len = strlen(section);

	if (bRestart)
	{
		// Set position to start of file
		fseek(file, 0, SEEK_SET);
	}

	// Scan file until end of file
	while(true)
	{
		// Try to read a line
		if (fgets(File_Buf, File_BufLen, file) == NULL)
			return false;

		// Test for start of section marker
		if (File_Buf[0] != '[')
			continue;

		// Test if text following is section
		if (strncmp(File_Buf + 1, section, len))
			continue;

		// Test for end of section marker
		if (File_Buf[len + 1] == ']')
			return true;
	}

	return false;
}

static void File_FindEndOfSection(FILE* file)
{
	fpos_t	pos;

	// Scan file until end of file
	while(true)
	{
		// Store current pos in file
		fgetpos(file, &pos);

		// Try to read a line
		if (fgets(File_Buf, File_BufLen, file) == NULL)
			break;

		// Test for start of section marker
		if (File_Buf[0] == '[')
		{
			// Restore pos in file to start of this line
			fsetpos(file, &pos);
			break;
		}
	}
}

static void String_StripBlanks(char* string)
{
	int len;
	int i;

	// strip trailing blanks
	for (len = strlen(string); (len > 0) && (string[len - 1] <= ' '); len--)
		;

	// count leading blanks
	for (i = 0; (i < len) && (string[i] <= ' '); i++) ;

	// remove leading blanks
	if (i > 0)
	{
		len = len - i;
		memmove(string, string + i, len);
	}
	string[len] = 0;

	// replace control characters by blanks
	for(i = 1; i < len; i++)
	{
		if (iscntrl(string[i]))
		{
			string[i] = ' ';
			break;
	        }
	}
}

int main(void)
{
	FILE*		file;
	static char	string[256];
	long int	restorepos;
	long int	endpos;
	char*		pValue;

	// scan the Setup file for the section FileTypes
	if ((file = fopen("DigitalCDRes:Setup", "rb")) == NULL)
	{
		return EXIT_SUCCESS;
	}

	if (File_FindSection(file, "FileTypes", true))
	{
		// found
		restorepos = ftell(file);
		File_FindEndOfSection(file);
		endpos = ftell(file);
		fseek(file, restorepos, SEEK_SET);

		while(ftell(file) < endpos)
		{
			char* pstr;

			// extract a line
			if (fgets(string, 255, file) == NULL)
				break;

			// find '=' in string
			pValue = strchr(string, '=');

			// loop if not found
			if (pValue == NULL) continue;

			*pValue = 0;
			pValue++;
			String_StripBlanks(pValue);
			if (!*pValue) continue;

			String_StripBlanks(string);

			// Ignore boot flag
			pstr = string;
			if (*pstr == '!')
			{
				pstr++;

				if (!*pstr) continue;

				BootTypes_AddRunType(pstr);
			}
		}
	}

	fclose(file);

	return EXIT_SUCCESS;
}
