//	Asuka - VirtualDub Build/Post-Mortem Utility
//	Copyright (C) 2005-2008 Avery Lee
//
//	This program is free software; you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation; either version 2 of the License, or
//	(at your option) any later version.
//
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program; if not, write to the Free Software
//	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

#include "stdafx.h"
#include <math.h>
#include <vd2/system/vdtypes.h>
#include <vd2/system/vdstl.h>

#include "utils.h"

void tool_maketables(const vdfastvector<const char *>& args, const vdfastvector<const char *>& switches) {
	if (args.size() < 1) {
		printf("usage: maketables <C++ output file>\n");
		exit(5);
	}

	FILE *f = fopen(args[0], "w");
	if (!f)
		fail("    couldn't open: %s\n", args[1]);

	fputs("// Automatically generated by Asuka 'maketables.'\" DO NOT EDIT!\n", f);
	fputs("\n", f);
	fputs("#include <vd2/system/vdtypes.h>\n", f);
	fputs("\n", f);

	fputs("extern \"C\" const sint32 kVDCubicInterpTableFX14_075[256][4]={\n", f);
	{
		static const double A = -0.75;

		for(int i=0; i<256; ++i) {
			double d = (double)i / 256.0f;

			double c1 = ((+      A*d -  2.0*A     )*d + A)*d;
			double c3 = ((-(A+2.0)*d + (2.0*A+3.0))*d - A)*d;
			double c4 = ((-      A*d +      A     )*d    )*d;

			int ic1 = (int)floor(0.5 + 16384.0 * c1);
			int ic3 = (int)floor(0.5 + 16384.0 * c3);
			int ic4 = (int)floor(0.5 + 16384.0 * c4);

			fprintf(f, "\t{ %6d, %6d, %6d, %6d },", ic1, 16384 - (ic1+ic3+ic4), ic3, ic4);

			if ((i&3) == 3) fputc('\n', f);
		}
	}
	fputs("};\n", f);
	fputs("\n", f);

	fputs("#ifdef _M_IX86\n", f);
	fputs("extern \"C\" const __declspec(align(16)) sint16 kVDCubicInterpTableFX14_075_MMX[256][8]={\n", f);
	{
		static const double A = -0.75;

		for(int i=0; i<256; ++i) {
			double d = (double)i / 256.0f;

			double c1 = ((+      A*d -  2.0*A     )*d + A)*d;
			double c3 = ((-(A+2.0)*d + (2.0*A+3.0))*d - A)*d;
			double c4 = ((-      A*d +      A     )*d    )*d;

			int ic1 = (int)floor(0.5 + 16384.0 * c1);
			int ic3 = (int)floor(0.5 + 16384.0 * c3);
			int ic4 = (int)floor(0.5 + 16384.0 * c4);
			int ic2 = 16384 - (ic1 + ic3 + ic4);

			fprintf(f, "\t{ %6d, %6d, %6d, %6d, %6d, %6d, %6d, %6d },", ic1, ic2, ic1, ic2, ic3, ic4, ic3, ic4);

			if ((i&1) == 1) fputc('\n', f);
		}
	}
	fputs("};\n", f);
	fputs("\n", f);
	fputs("#endif\n", f);

	fclose(f);
}
