#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "kernel.h"
#include "swis.h"

int main(int argc, char* argv[])
{
	int territory = 0;
	int type = -1;
	const char* string;
	const char* basedir;
	char* pdir;
	char respath[1024];

	if (argc == 3)
	{
		string = argv[1];
		basedir = argv[2];
	}
	else
	{
		fprintf(stderr, "Syntax: SelectRes <var> <basedir>");
		return EXIT_FAILURE;
	}

	// Territory_Number
	_swix(0x43040, _OUT(0), &territory);
	sprintf(respath, "%s.", basedir);
	pdir = respath + strlen(respath);

	// Check if any resource directory exists for current territory
	if (territory > 0)
	{
		sprintf(pdir, "%d", territory);
		// OS_File
		_swix(8, _INR(0,1)|_OUT(6), 23, respath, &type);
		if (type < 0x1000) pdir[0] = 0;
	}

	// Find any resource directory if none found yet
	if (!pdir[0])
	{
		int entry = 0;
		int len;

		while(entry != -1)
		{
			if ((_swix(0x0c, _INR(0, 6) | _OUTR(3, 4)
					, 9, basedir, pdir, 1, entry, 256, 0
					, &len, &entry) != NULL)
			|| !len)
			{
				entry = -1;
			}
			else
			{
				// OS_File
				_swix(8, _INR(0,1)|_OUT(6), 23, respath, &type);
				if (type >= 0x1000) break;
			}
			pdir[0] = 0;
		}
	}

	// If subdir found use subdir, else use basedir itself
	if (pdir[0])
	{
		pdir += strlen(pdir);
		strcpy(pdir, ".");
	}

	// OS_SetVarVal
	_swix(0x24, _INR(0,4), string, respath, strlen(respath), 0, 0);

	return EXIT_SUCCESS;
}
