/*
logNear1d.c

write near1d.log
*/

#include "omm.h"
#include "complex.h"

void logNear1d(d_complex_t ****e, d_complex_t ****h)
{
	FILE *fp;
	if ((fp = fopen(FN_near1d, "w")) == NULL) {
		fprintf(stderr, "*** %s open error.\n", FN_near1d);
		return;
	}

	for (int n = 0; n < NNear1d; n++) {
		double (*pos)[3] = (double (*)[3])malloc((Near1d[n].div + 1) * 3 * sizeof(double));
		int div = Near1d[n].div;
		char cmp = Near1d[n].cmp[0];

		for (int m = 0; m <= div; m++) {
			double ai = (double)m / div;
			for (int k = 0; k < 3; k++) {
				pos[m][k] = ((1 - ai) * Near1d[n].pos[0][k]) + (ai * Near1d[n].pos[1][k]);
			}
		}

		for (int ifreq = 0; ifreq < NFrequency; ifreq++) {
			fprintf(fp, "#%d : frequency[Hz] = %.3e\n", (n + 1), Frequency[ifreq]);
			fprintf(fp, "%s", " No.     X[m]        Y[m]        Z[m]       ");
			fprintf(fp, "%s\n", (cmp == 'E')
				? "E[V/m]      Ex[V/m]   Ex[deg]    Ey[V/m]   Ey[deg]    Ez[V/m]   Ez[deg]"
				: "H[A/m]      Hx[A/m]   Hx[deg]    Hy[A/m]   Hy[deg]    Hz[A/m]   Hz[deg]");

			for (int m = 0; m <= div; m++) {
				d_complex_t *c = (cmp == 'E') ? e[n][ifreq][m] : h[n][ifreq][m];
				fprintf(fp, "%4d%12.3e%12.3e%12.3e%12.4e%12.4e%9.3f%12.4e%9.3f%12.4e%9.3f\n",
					m, pos[m][0], pos[m][1], pos[m][2],
					sqrt(d_norm(c[0]) + d_norm(c[1]) + d_norm(c[2])),
					d_abs(c[0]), d_deg(c[0]), d_abs(c[1]), d_deg(c[1]), d_abs(c[2]), d_deg(c[2]));
			}
		}

		free(pos);
	}

	fclose(fp);
}
