#include "volume.h"
#include "path.h"

int main(int argc, char* argv[])
{
	if (argc < 4) {
		printf("GTtool for Gran Turismo 5/6 (c) flatz, 2014\n");
		printf("Usage: gttool <volume file> <GT5/GT6> <output directory>\n");
		return 0;
	}

	GameID game_id;
	if (stricmp(argv[2], "GT5") == 0)
		game_id = GameID::GT5;
	else if (stricmp(argv[2], "GT6") == 0)
		game_id = GameID::GT6;
	else
		game_id = GameID::UNKNOWN;
	if (game_id == GameID::UNKNOWN) {
		printf("Unsupported game ID.\n");
		exit(1);
	}

	char* const output_dir = static_cast<char*>(_alloca(_MAX_PATH));
	memset(output_dir, 0, _MAX_PATH);
	uint32_t output_dir_length = 0;
	for (int i = 0; i < _MAX_PATH; ++i, ++output_dir_length)
		output_dir[i] = output_dir[i] != '\\' ? argv[3][i] : '/';
	if (output_dir_length > 0 && output_dir[output_dir_length - 1] != '/')
		strcat(output_dir, "/");

	Volume volume;
	if (!volume.open(argv[1], game_id)) {
		printf("Unable to process volume file.\n");
		exit(1);
	}

	if (!directory_exists(output_dir)) {
		if (!make_directories(output_dir)) {
			printf("Unable to create output directory.\n");
			exit(1);
		}
	}
	if (!volume.extract(output_dir)) {
		printf("Unable to extract volume files.\n");
		exit(1);
	}

	printf("All files have been extracted.\n");

	volume.close();

	return 0;
}