// txt2c.cpp : This simple app builds a table
// of discrete probability distribution functions
// and generates a .cpp/.h file that describe them.
//

#include <string.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>

#include "dpdf.h"

using namespace std;

int 
main(int argc, char* argv[])
{
    if (argc < 4)
    {
	cerr << "Usage is " << argv[0] << " maxsides maxrolls scale" << endl;
	cerr << "This will build dpdf_table.cpp and dpdf_table.h" << endl;
	return -2;
    }

    ifstream		is(argv[1], ios::in);

    int		maxsides, maxrolls, scale, roll, side;

    maxsides = atoi(argv[1]);
    maxrolls = atoi(argv[2]);
    scale = atoi(argv[3]);

    ofstream	os("dpdf_table.cpp");
    if (!os)
    {
	cerr << "Couldn't open for write " << "dpdf_table.cpp" << endl;
    }
    ofstream	hos("dpdf_table.h");
    if (!hos)
    {
	cerr << "Couldn't open for write " << "dpdf_table.h" << endl;
    }

    // Build the header file.
    hos << "// dpdf_table.h" << endl
        << "// Automagically generated by builddpdf" << endl
	<< "// DO NOT HAND EDIT.  Yes, this means you." << endl
	<< endl;

    hos << "// Dimensions of table, these are inclusive." << endl;
    hos << "#define DPDF_MAXSIDES " << maxsides << endl;
    hos << "#define DPDF_MAXROLLS " << maxrolls << endl;
    hos << "#define DPDF_SCALE    " << scale << endl;
    hos << endl;

    hos << "// Since 0 and 1 are obvious for sides, hence the -1" << endl;
    hos << "extern const int glb_dpdftable[DPDF_MAXROLLS+1][DPDF_MAXSIDES-1];" << endl;


    os  << "// dpdf_table.cpp" << endl
        << "// Automagically generated by builddpdf" << endl
	<< "// DO NOT HAND EDIT.  Yes, this means you." << endl
	<< endl;

    os  << "#include \"dpdf_table.h\"" << endl
	<< endl;

    os  << "const int glb_dpdftable[DPDF_MAXROLLS+1][DPDF_MAXSIDES-1] =" << endl
	<< "{" << endl;

    for (roll = 0; roll <= maxrolls; roll++)
    {
	os << "    { ";
	for (side = 2; side <= maxsides; side++)
	{
	    DPDF	r(1, side), u(1, side);
	    int		mean;
	    int		i;

	    for (i = 0; i < roll; i++)
	    {
		r.max(r, u);
	    }

	    mean = (int) (r.expectedValue() * scale + 0.5);

	    os << mean << ", ";
	}
	os << "}," << endl;
    }

    os << "};" << endl;

    return 0;
}


