/*
outputCoupling.c

output coupling
*/

#include "oth.h"
#include "complex.h"


d_complex_t coupling(int ifeed, int ipoint, int ifreq)
{
	d_complex_t cvf = Feed[ifeed].volt;

	int i = Point[ipoint].i;
	int j = Point[ipoint].j;
	int k = Point[ipoint].k;
	d_complex_t cvp = d_complex(0, 0);
	if      (Point[ipoint].dir == 'X') {
		cvp = d_rmul(-DXc[i], d_cast(Ex[ifreq][i][j][k]));
	}
	else if (Point[ipoint].dir == 'Y') {
		cvp = d_rmul(-DYc[j], d_cast(Ey[ifreq][i][j][k]));
	}
	else if (Point[ipoint].dir == 'Z') {
		cvp = d_rmul(-DZc[k], d_cast(Ez[ifreq][i][j][k]));
	}

	return d_div(cvp, cvf);
}


static void _outputCoupling(FILE *fp)
{
	char str[BUFSIZ];

	fprintf(fp, "%s\n", "=== coupling ===");

	fprintf(fp, "%s", "  freq[Hz] ");
	for (int ifeed = 0; ifeed < NFeed; ifeed++) {
		for (int ipoint = 0; ipoint < NPoint; ipoint++) {
			sprintf(str, "C%d%d", ipoint + 1, ifeed + 1);
			fprintf(fp, "  %s[dB] %s[deg]", str, str);
		}
	}
	fprintf(fp, "\n");

	for (int ifreq = 0; ifreq < NFrequency; ifreq++) {
		fprintf(fp, "%11.3e", Frequency[ifreq]);
		for (int ifeed = 0; ifeed < NFeed; ifeed++) {
			for (int ipoint = 0; ipoint < NPoint; ipoint++) {
				d_complex_t couple = coupling(ifeed, ipoint, ifreq);
				fprintf(fp, "%9.3f%9.3f", 10 * log10(MAX(d_norm(couple), EPS2)), d_deg(couple));
			}
		}
		fprintf(fp, "\n");
	}

	fflush(fp);
}


void outputCoupling(FILE *fp)
{
	if ((NFeed <= 0) || (NPoint <= 0) || (NFrequency <= 0)) return;

	// output
	_outputCoupling(stdout);
	_outputCoupling(fp);
}
