#include <stdio.h>
#include "pi.h"
#include "type.h"

/* structure which saves transformer parameters */

typedef struct {

	float inductance; /* self inductance in henries of primary
				and secondary windings */
	float k;	/* coupling coefficient (<1) */

	} TRANSFORMER;

extern FILE *fdata;

extern COMPLEX unity,zero;

/**********************************************************************

			transformer()

************************************************************************

Function computes the ABCD matrix of a transformer
(at present does not include capacitance between primary and
secondary, assumes self inductance of primary and secondary
are the same; also no shunt capacitance or series resistance
but those can be easily modelled using linemod)

Inputs: pointer to the data structure for the twoport and the frequency
Output: ABCD matrix for the twoport
*/

ABCD transformer(current,f)
TWOPORT *current; 	/* twoport being modelled */
double f;		/* frequency */

{
	ABCD tmsect;
	POINTER calloc();
	TRANSFORMER *param;

/* the first time this function is called we simply read the parameters
   of the line from the input line */

	if(current->line != NULL) {

		/* allocate storage for the twoport parameters -- this
		   function may be called for many twoports so it has to
		   be unique */

		if((current->param = calloc(1,sizeof(TRANSFORMER))) == NULL)
			error_alloc();

		param = (TRANSFORMER *) current->param;

		if(sscanf(current->line,"transformer%f%f",
		   &param->inductance, &param->k) != 2) {
			fprintf(stderr,
		"transformer(): cannot read parameters on line\n%s\n",
			current->line);
			exit(1);
			}

		fprintf(fdata,"Transformer %g henries %g coupling coef.\n", param->inductance, param->k);
		}

/* every other time this function is called we calculate the ABCD matrix */

	else 	{

		param = (TRANSFORMER *) current->param;

		/* ABCD matrix */
		tmsect.a.real = tmsect.d.real = 1./param->k;
		tmsect.a.imag = tmsect.d.imag = 0.0;
		tmsect.b.real = tmsect.c.real = 0.0;
		tmsect.b.imag = 2.*PI*f*param->inductance*
				(1.- param->k*param->k);
		/* ABCD matrix blows up at d.c. -- fixup */
		if(f == 0)
			tmsect.c.imag = 1.0e6;
		else
			tmsect.c.imag = - 1./(2.*PI*f*param->inductance);
		}

	return(tmsect);
}
