#include "ngspice/cm.h"
extern void cm_tline(Mif_Private_t *);
/* ===========================================================================
	FILE    cfunc.mod for cm_tline
	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 "msline_common.h"
#include "tline_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 void cm_tline_callback(Mif_Private_t *mif_private, Mif_Callback_Reason_t reason);

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


	/* how to get properties of this component, e.g. L, W */
	double z = mif_private->param[1]->element[0].rvalue;
	double l = mif_private->param[0]->element[0].rvalue;
	double a = mif_private->param[2]->element[0].rvalue;

	double alpha = pow(10,0.05*a);
	alpha = log(alpha)/2.0;

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

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

		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 + z*I1;
		double V1out = V2 + z*I2;
		mif_private->conn[0]->port[0]->output.rvalue = V1out + I1*z;
		mif_private->conn[1]->port[0]->output.rvalue = V2out + I2*z;

		cm_analog_auto_partial();
	}
	else if(mif_private->circuit.anal_type == AC) {
		double beta = mif_private->circuit.frequency/C0;
#ifdef _MSC_VER
		DoubleComplex g = _Cbuild(alpha, beta);
		DoubleComplex _Z11 = rdivide(z, ctanh(_Cmulcr(g, l)));
		DoubleComplex _Z21 = rdivide(z, csinh(_Cmulcr(g, l)));
#else
		DoubleComplex g = alpha + beta*I;
		DoubleComplex _Z11 = z / ctanh(g*l);
		DoubleComplex _Z21 = z / csinh (g*l);
#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) {
        sim_points = &(mif_private->inst_var[0]->element[0].pvalue);
		double t = 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);

        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,"Rollback time=%g\n",TIME);
			delete_tline_last_state((tline_state_t **)sim_points);
		}

		append_state((tline_state_t **)sim_points, t, V1, V2, I1, I2, 1.2*delay);
		if (t > delay) {
			tline_state_t *pp = get_state(*(tline_state_t **)sim_points, t - delay);
			if (pp != NULL) {
				double V2out = pp->V1 + z*(pp->I1);
				double V1out = pp->V2 + z*(pp->I2);
				mif_private->conn[0]->port[0]->output.rvalue = V1out + I1*z;
				mif_private->conn[1]->port[0]->output.rvalue = V2out + I2*z;
			}
			cm_analog_auto_partial();
		} else  {
			double V2out = V1 + z*I1;
			double V1out = V2 + z*I2;
			mif_private->conn[0]->port[0]->output.rvalue = V1out + I1*z;
			mif_private->conn[1]->port[0]->output.rvalue = V2out + I2*z;
			cm_analog_auto_partial();
		}
	}
}


static void cm_tline_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;
    }
}
