#include "ngspice/cm.h"
extern void cm_mlin(Mif_Private_t *);
/* ===========================================================================
	FILE    cfunc.mod for cm_mlin
	Copyright 2025 Vadim Kuznetsov

	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

	3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */

#include <stdio.h>
#include <math.h>
#include <complex.h>

#include "tline_common.h"

#include "msline_common.h"

#ifdef _MSC_VER
typedef _Dcomplex DoubleComplex;  // double complex
#else
typedef double complex DoubleComplex;
#endif

#ifdef _MSC_VER
static DoubleComplex divide(DoubleComplex n1, DoubleComplex n2)
    {
        DoubleComplex rez;
        double denom = n2._Val[0] * n2._Val[0] + n2._Val[1] * n2._Val[1];
        rez._Val[0] = (n1._Val[0] * n2._Val[0] + n1._Val[1] * n2._Val[1]) / denom;
        rez._Val[1] = (n1._Val[1] * n2._Val[0] - n1._Val[0] * n2._Val[1]) / denom;
        return rez;
    }

static DoubleComplex rdivide(double n1, DoubleComplex n2)
    {
        DoubleComplex rez;
        double denom = n2._Val[0] * n2._Val[0] + n2._Val[1] * n2._Val[1];
        rez._Val[0] = (n1 * n2._Val[0]) / denom;
        rez._Val[1] = (-1. * n1 * n2._Val[1]) / denom;
        return rez;
    }
#endif



//static tline_state_t *sim_points = NULL;

static double zl, alpha, beta, ereff;

static void cm_mline_callback(Mif_Private_t *mif_private, Mif_Callback_Reason_t reason);

static void calcPropagation (double W, int SModel, int DModel,
                             double er, double h, double t, double tand, double rho, double D,
                             double frequency) {

	/* local variables */
	double ac, ad;
	double ZlEff, ErEff, WEff, ZlEffFreq, ErEffFreq;

	// quasi-static effective dielectric constant of substrate + line and
	// the impedance of the microstrip line
	mslineAnalyseQuasiStatic (W, h, t, er, SModel, &ZlEff, &ErEff, &WEff);

	// analyse dispersion of Zl and Er (use WEff here?)
	mslineAnalyseDispersion (W, h, er, ZlEff, ErEff, frequency, DModel,
			&ZlEffFreq, &ErEffFreq);

	// analyse losses of line
	analyseLoss (W, t, er, rho, D, tand, ZlEff, ZlEff, ErEff,
			frequency, HAMMERSTAD, &ac, &ad);

	// calculate propagation constants and reference impedance
	zl    = ZlEffFreq;
	ereff = ErEffFreq;
	alpha = ac + ad;
	beta  = sqrt (ErEffFreq) * 2 * M_PI * frequency / C0;
}

void cm_mlin (Mif_Private_t *mif_private)
{
	Complex_t   z11, z21;
    void **sim_points;


	/* how to get properties of this component, e.g. L, W */
	double W = mif_private->param[1]->element[0].rvalue;
	double l = mif_private->param[0]->element[0].rvalue;
	int SModel = mif_private->param[2]->element[0].ivalue;
	int DModel = mif_private->param[3]->element[0].ivalue;
    int TModel = mif_private->param[10]->element[0].ivalue;

	/* how to get properties of the substrate, e.g. Er, H */
	double er    = mif_private->param[4]->element[0].rvalue;
	double h     = mif_private->param[5]->element[0].rvalue;
	double t     = mif_private->param[6]->element[0].rvalue;
	double tand  = mif_private->param[7]->element[0].rvalue;
	double rho   = mif_private->param[8]->element[0].rvalue;
	double D     = mif_private->param[9]->element[0].rvalue;



	/* Initialize/access instance specific storage for capacitor voltage */
	if(mif_private->circuit.init) {
        *(mif_private->callback) = cm_mline_callback;
        mif_private->inst_var[0]->element[0].pvalue = NULL;
	}

	/* Compute the output */
	if(mif_private->circuit.anal_type == DC) {

		calcPropagation(W,SModel,DModel,er,h,t,tand,rho,D,0);
	    double V1 = mif_private->conn[2]->port[0]->input.rvalue;
		double V2 = mif_private->conn[3]->port[0]->input.rvalue;
		double I1 = mif_private->conn[0]->port[0]->input.rvalue;
		double I2 = mif_private->conn[1]->port[0]->input.rvalue;
		double V2out = V1 + zl*I1;
		double V1out = V2 + zl*I2;
		mif_private->conn[0]->port[0]->output.rvalue = V1out + I1*zl;
		mif_private->conn[1]->port[0]->output.rvalue = V2out + I2*zl;

		cm_analog_auto_partial();
	}
	else if(mif_private->circuit.anal_type == AC) {
	    double frequency = mif_private->circuit.frequency/(2.0*M_PI);
		calcPropagation(W,SModel,DModel,er,h,t,tand,rho,D,frequency);
#ifdef _MSC_VER
		DoubleComplex g = _Cbuild(alpha, beta);
		DoubleComplex _Z11 = rdivide(zl, ctanh(_Cmulcr(g, l)));
		DoubleComplex _Z21 = rdivide(zl, csinh(_Cmulcr(g, l)));
		z11.real = creal(_Z11); z11.imag = cimag(_Z11);
		z21.real = creal(_Z21); z21.imag = cimag(_Z21);
#else
		DoubleComplex g = alpha + beta*I;
		DoubleComplex _Z11 = zl / ctanh(g*l);
		DoubleComplex _Z21 = zl / csinh(g*l);
		z11.real = creal(_Z11); z11.imag = cimag(_Z11);
		z21.real = creal(_Z21); z21.imag = cimag(_Z21);
#endif

		z11.real = creal(_Z11); z11.imag = cimag(_Z11);
		z21.real = creal(_Z21); z21.imag = cimag(_Z21);

		mif_private->conn[0]->port[0]->ac_gain[0].port[0] = z11; mif_private->conn[1]->port[0]->ac_gain[1].port[0] = z11;
		mif_private->conn[0]->port[0]->ac_gain[1].port[0] = z21; mif_private->conn[1]->port[0]->ac_gain[0].port[0] = z21;
	}
	else if(mif_private->circuit.anal_type == TRANSIENT) {
		calcPropagation(W,SModel,DModel,er,h,t,tand,rho,D,0);
        sim_points = &(mif_private->inst_var[0]->element[0].pvalue);
        double time = mif_private->circuit.time;
		double V1 = mif_private->conn[2]->port[0]->input.rvalue;
		double V2 = mif_private->conn[3]->port[0]->input.rvalue;
		double I1 = mif_private->conn[0]->port[0]->input.rvalue;
		double I2 = mif_private->conn[1]->port[0]->input.rvalue;
		double delay = l/(C0) * sqrt(ereff);
		if (TModel == TRAN_FULL) {

            tline_state_t *last = get_tline_last_state(*(tline_state_t **)sim_points);
			double last_time = 0;
			if (last != NULL) last_time = last->time;

			if (mif_private->circuit.time < last_time) {
                //fprintf(stderr,"Rollbacki time=%g\n",TIME);
				delete_tline_last_state((tline_state_t **)sim_points);
			}
			append_state((tline_state_t **)sim_points, time, V1, V2, I1, I2, 1.2*delay);
		}
		if (time > delay && TModel == TRAN_FULL) {
			tline_state_t *pp = get_state(*(tline_state_t **)sim_points, time - delay);
			if (pp != NULL) {
				double V2out = pp->V1 + zl*(pp->I1);
				double V1out = pp->V2 + zl*(pp->I2);
				mif_private->conn[0]->port[0]->output.rvalue = V1out + I1*zl;
				mif_private->conn[1]->port[0]->output.rvalue = V2out + I2*zl;
			}
			cm_analog_auto_partial();
		} else {
            double V2out = V1 + zl*I1;
			double V1out = V2 + zl*I2;
			mif_private->conn[0]->port[0]->output.rvalue = V1out + I1*zl;
			mif_private->conn[1]->port[0]->output.rvalue = V2out + I2*zl;
			cm_analog_auto_partial();
		}

	}
}

static void cm_mline_callback(Mif_Private_t *mif_private, Mif_Callback_Reason_t reason)
{
    switch (reason) {
        case MIF_CB_DESTROY:
            delete_tline_states((tline_state_t **)&(mif_private->inst_var[0]->element[0].pvalue));
            break;
        default: break;
    }
}

