/*
outputofd.c

output OpenFDTD datafile
*/

#include "omm.h"

void outputofd(const char fn[], int nx, int ny, double lx, double ly, double h, int sdiv)
{
	const char program[] = "OpenFDTD 4 0";

	// open
	FILE *fp;
	if ((fp = fopen(fn, "w")) == NULL) {
		fprintf(stderr, "file %s open error.\n", fn);
		exit(1);
	}

	// header
	fprintf(fp, "%s\n", program);
	//fprintf(fp, "title = OpenFDTD optimization\n");

	// mesh
	const int margin = 5;
	const int zmargin = 7;
	const double d = (lx + ly) / (nx + ny);
	const double x0 = -lx / 2 - (margin * d);
	const double x1 = -x0;
	const double y0 = -ly / 2 - (margin * d);
	const double y1 = -y0;
	const double z0 = -(2 * d / sdiv);
	const double z1 = h + (zmargin * d);
	fprintf(fp, "xmesh = %g %d %g\n", x0, NINT(sdiv * (x1 - x0), d), x1);
	fprintf(fp, "ymesh = %g %d %g\n", y0, NINT(sdiv * (y1 - y0), d), y1);
	fprintf(fp, "zmesh = %g %d %g\n", z0, NINT(sdiv * (z1 - z0), d), z1);

	// ground
	fprintf(fp, "geometry = 1 1 %g %g %g %g %g %g\n", x0, x1, y0, y1, z0, 0.0);

	// geometry
	assert(NGeometry > 0);
	for (int n = 0; n < NGeometry; n++) {
		fprintf(fp, "geometry = 1 1 %g %g %g %g %g %g\n",  // PEC, BOX
			Geometry[n].pos[0][0], Geometry[n].pos[1][0],
			Geometry[n].pos[0][1], Geometry[n].pos[1][1],
			Geometry[n].pos[0][2], Geometry[n].pos[1][2]);
	}

	// feed
	const double z = 1e-3;
	fprintf(fp, "feed = Z 0 0 %g 1 0 %g\n", z, Z0);
	fprintf(fp, "rfeed = %g\n", 10.0);

	// misc.
	assert(NFrequency > 0);
	fprintf(fp, "frequency1 = %g %g %d\n", Frequency[0], Frequency[NFrequency - 1], NFrequency - 1);
	fprintf(fp, "frequency2 = %g %g %d\n", Frequency[0], Frequency[NFrequency - 1], NFrequency - 1);
	fprintf(fp, "solver = 20000 200 1e-3\n");

	// tailor
	fprintf(fp, "end\n");

	fclose(fp);
}
