

// Refer to  "Roberts_BDFM_dissertation_2005-(Modified).pdf".
//
// We are modeling a single stator induction motor here. We will lump the mutual inductances of the stator and rotor into simple representations of windings
// without regard to physical layout.
//
// The machine will be reduced to:
//
//     p1 = 1, p2 = 0   (This is a 2 pole machine traditional induction motor)
//     S = 2  (With a single set of windings, the meaning of S has changed. However in Robert's, S = p1 + p2 = 2 + 4 = 6. Six circuits defined the requirement
//             that for a 4/8 pole BDFM, there must always be a point in rotation that any two of the six rotor bars line up with the "pitch" of a 4 pole or
//             8 pole stator. With this in mind, we define S = 2.
//
//     This reduces the mutual inductance matrix to the following (from Eq 2.30 and Eq. 2.56)
//
//
//      | Ms     Msr |
//      | Msr_T  Mr  |
//
//      where Ms is a 3 x 3 matrix, Ms is a 2 x 2 matrix, Msr is a 3 x 2 matrix and Msr_T is a 2 x 3 matrix.
//
//
//      We will use the top left block of Equation B.9 on age 256 for Ms.
//
//				| 210.0e-3    -96.3e-3   -96.3e-3 |
//              | -96.3e-3    210.0e-3   -96.3e-3 |
//              | -96.3e-3    -96.3e-3   210.0e-3 |
//
//      Msr of Equation 2.53 on page 63 reduces to this (for S = 2).
//
//
//              | Sum{M*cos(theta_r 		- B)        Sum{M*cos(theta_r 		  - PI -  B) |
//				| Sum{M*cos(theta_r - 2PI/3 - B)        Sum{M*cos(theta_r - 2PI/3 - PI -  B) |
//				| Sum{M*cos(theta_r - 4PI/3 - B)        Sum{M*cos(theta_r - 4PI/3 - PI -  B) |
//
//
//      For S = 2, Mr will be interperted from the "Rotor 5: 6 bar cage rotor design", Section B.7, Equation B.29
//
//
//      		|  271.0e-7  -271.0e-7 |
//              | -271.0e-7   271.0e-7 |
//
//




typedef enum {
  SRC_FUNC_NULL = -1,
  SRC_FUNC_TriangleWave,
  SRC_FUNC_PwmA,
  SRC_FUNC_PwmB,
  SRC_FUNC_PwmC,

} SRC_FUNCTION;

	// ODE Functions based on Equations 2.56 and 2.59 on page 65 of "Roberts_BDFM_dissertation_2005-(Modified).pdf"
typedef enum {
  ODE_FUNC_NULL = -1,
  ODE_FUNC_Is1_Is2_Is3_Ir1_Ir2_Ir3_Ir4_Ir5_Ir6_1,
  ODE_FUNC_Is1_Is2_Is3_Ir1_Ir2_Ir3_Ir4_Ir5_Ir6_2,
  ODE_FUNC_Is1_Is2_Is3_Ir1_Ir2_Ir3_Ir4_Ir5_Ir6_3,
  ODE_FUNC_Ir1_Ir2_Ir3_Ir4_Ir5_Ir6_1,
  ODE_FUNC_Ir1_Ir2_Ir3_Ir4_Ir5_Ir6_2,
  ODE_FUNC_Theta_r,
  ODE_FUNC_Omega_r,
  
} ODE_FUNCTION;

//(NOTE: As of 6/12/08, "pTranslationList" and "pTrajectoryList" CTRL's have been 
//       deprecated and replaced with a "group" structure. However, we still maintain
//       only one "CTRL_FUNCTION" enumeration for all groups)
typedef enum {
  CTRL_FUNC_NULL = -1,
  CTRL_FUNC_RefGen,
  CTRL_FUNC_VDqCmd,


} CTRL_FUNCTION;

typedef enum {
  COEF_FUNC_NULL = -1,
} COEF_FUNCTION;



typedef enum {
  SWITCH_FUNC_NULL = -1,

} SWITCH_FUNCTION;

typedef enum {
  SPICE_FUNC_NULL = -1,

} SPICE_FUNCTION;



#include "Simulation.hpp" 





     // un-comment to plot all probes and object outputs.
//#define RECORD_ALL_PROBES


//Parameters....

// Inductance matrix's calculated from test "Section_2_7_2", "Section_B_2", and "Section_B_7"
#include "../BDFM-Dissertation-2005-Tests/Section_2_7_2/Stator_Rotor_Mutual_Inductance.h"
#include "../BDFM-Dissertation-2005-Tests/Section_2_7_2/Stator_Rotor_Derivative_Mutual_Inductance.h"
#include "../BDFM-Dissertation-2005-Tests/Section_B_2/Stator_Stator_Mutual_Inductance.h"
#include "../BDFM-Dissertation-2005-Tests/Section_B_7/Rotor_Rotor_Mutual_Inductance.h"



#define PI 3.1415926535897932384626433832795

// Form "Roberts..."  Section 2.5.3, Equation 2.31 and Equation 2.32, page 49.
//
//    R = rho * l / A    (length in meters, area in square meters)
//
//    l_stator = 2.0 * 1.1 * N *((_coil_pitch_ * d / 2.0) + w)             //(used to calculate the stator winding resistance. All distances in meters)
//

//
//
//
// From "Section_2_7_2" experiment....
//
//
//	w = .1955 m
//  d = .175065 m
//  N = 10 * 16    //(For stator calculation, actually from Table B.1 page and Table B.3 page 252 of "Roberts..." for 4 pole winding (2 pole pairs))
//
//  A = 1.13 mm**2    //(For stator calculation, also from Table B.3 page 252 of "Roberts..." )
//  _coil_pitch_  =  2.0 * PI * ( d / 2.0) * 10.0 / 48.0  //See "Ack" in "Section_2_7_2.c" for stator coil pitch)
//
//  A = 205.84 mm**2   //(Rotor bar conductor area, see Table B.4, Section B.10 on page 274 of "Roberts...")
//
//
//
//  Interpertation for bar resistance from Section B.7.1, Figure B.8 page 267
//
//	  l_rotor_bar = d (approximate)
//    l_rotor_end = 2.0 * PI * (d / 2.0) / 6.0 (approximate)
//
//
//
//  rho (copper) = 1.68e-8

//
//
//  From Section B.7.1, Figure B.8 page 267 calculate the  the elements of the resistor matrix for "6 bar cage rotor design"
#define Rr_matrix_loop  (2.0 * 1.68e-8 * (0.1955 + (2.0 * PI * (0.175065 / 2.0) / 6.0))  / (205.84 / 1.0e6))
#define Rr_matrix_bar   (- 1.68e-8 * 0.1955 (205.84 / 1.0e6))

double Rr_res[6][6] = {
							{R_matrix_loop,    R_matrix_bar,    0,               0,               0,               R_matrix_bar  },
							{R_matrix_bar,     R_matrix_loop,   R_matrix_bar,    0,               0,               0             },
							{0,                R_matrix_bar,    R_matrix_loop,   R_matrix_bar,    0,               0             },
							{0,                0,               R_matrix_bar,    R_matrix_loop,	  R_matrix_bar,    0             },
							{0,                0,               0,               R_matrix_bar,    R_matrix_loop,   R_matrix_bar  },
							{R_matrix_bar,     0,               0,               0,               R_matrix_bar,    R_matrix_loop }
					  };


#define Rs_matrix_elem  (1.68e-8 *  2.0 * 1.1 * (10 * 16) * ((2.0 * PI * ( .175065 / 2.0) * 10.0 / 48.0)  + 0.1955))

double Rs_res[3][3] = {
							{Rs_matrix_elem,   0,				0				},
							{0,				   Rs_matrix_elem,	0				},
							{0,				   0,				Rs_matrix_elem	}
					  };

// Mechanical Parameters:
//
// 1 Newton = 1 kg * m / sec**2  (eg. F = mass * acceleration)
// T (torque) in units of Newton * meters (N*m)
// J (moment of interia) in units of kg * meter**2  (kg*m**2)
//
// Therefore:
// T / J = (m * kg * m / sec**2) / kg * m**2 = rad / sec**2


#define Tl  50.0  //N*m, can be as high as 143 N*m, see Table B.2, Section B.1, page 250.

#define Jm  .11   //kg * m**2 (Also from Table B.2, Section B.1, page 250.)






// These modulus based on "QUARTER_PWM_CYCLE" time below
#define REF_GEN_QUANTUM_CNT       8
#define VDQ_CMD_QUANTUM_CNT       4
#define PWM_CYCLE_QUANTUM_CNT     4

#define QUANTUM_PERIOD .0000125   




#define QUARTER_PWM_CYCLE QUANTUM_PERIOD
 


   




#define  RT_TRAJ     .2      
#define  CT_TRAJ     .5
#define  VO_TRAJ   100.0








          //uncoment if linear mode....
//#define LINEAR_AMP_MODE 
         
#define PWM_GAIN    5.0
#define PWM_OFFSET  0











// **** SrcObject Classes ********************************

// ---- TriangleWave ---------------------------------------

class TriangleWave : public SrcObject
{
public:
  virtual void SrcFunction(double t);
  virtual void OdeRValueUpdate(void);
  TriangleWave(void);
  ~TriangleWave(void);
  double t_mod;
  double t_prev;
  double PwmRampDir;
  double PwmFreqScale;



};


TriangleWave Inst_TriangleWave;


// --------------------------------------------------------

// ---- PwmA  ---------------------------------------------

class PwmA : public SrcObject
{
public:
  virtual void SrcFunction(double t);
  virtual void OdeRValueUpdate(void);
  PwmA(void);
  ~PwmA(void);
  //source for this ODE
  double TriAngWave;
  double V_xo;   //"x" is equal to "r", "y", or "b" depending on the sector of operation.

 
};



PwmA Inst_PwmA;

// -------------------------------------------------------------

// ---- PwmB  ---------------------------------------------

class PwmB : public SrcObject
{
public:
  virtual void SrcFunction(double t);
  virtual void OdeRValueUpdate(void);
  PwmB(void);
  ~PwmB(void);
  //source for this ODE
  double TriAngWave;
  double V_xo;   //"x" is equal to "r", "y", or "b" depending on the sector of operation.


};



PwmB Inst_PwmB;

// -------------------------------------------------------------

// ---- PwmC  ---------------------------------------------

class PwmC : public SrcObject
{
public:
  virtual void SrcFunction(double t);
  virtual void OdeRValueUpdate(void);
  PwmC(void);
  ~PwmC(void);
  //source for this ODE
  double TriAngWave;
  double V_xo;   //"x" is equal to "r", "y", or "b" depending on the sector of operation.

 

};



PwmC Inst_PwmC;

// -------------------------------------------------------------


SrcObject * SrcObjectList[] = {(SrcObject *) &Inst_TriangleWave,
			       (SrcObject *) &Inst_PwmA,
			       (SrcObject *) &Inst_PwmB,
			       (SrcObject *) &Inst_PwmC,
			       0};


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

// **** OdeObject Classes ********************************



// ---- Ia_Ib_Ic_1 -----------------------------------------

class Is1_Is2_Is3_Ir1_Ir2_1 : public OdeObject
{
public:
  virtual double OdeFunction(double y, double t);
  virtual void PostOdeFunction(double t);
  virtual void OdeRValueUpdate(void);
  virtual void OdeGroupMSolve(double dydt[],  double dmdt[]);
  //we use some probes in this object to get a better understanding
  //of what is going on.
  virtual void RecordProbes(void);
  virtual void PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[]);
  Is1_Is2_Is3_Ir1_Ir2_1(void);
  ~Is1_Is2_Is3_Ir1_Ir2_1(void);
  //source for this ODE
  void CalculateMutualInductances(void);
  double Ts_2[3][24] =  {{1,  1, -1, -1,  1,  1,  -1, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0},
  			              {0,  0,  0,  0,  0,  0,  0,  0,   1,  1, -1, -1,  1,  1,  -1, -1, 0,  0,  0,  0,  0,  0,  0,  0},
  			              {0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 1,  1, -1, -1,  1,  1,  -1, -1}};
  double Mss_2[3][3];

//  double vs_a;
//  double pwm_sig;
//  double ia;
//  double omega;
//  double theta;
//  double v_n;
//  int PositionFeedback;    //(this will ultimately to "FSFCtrl")
//  int VelocityFeedback;    //(this will ultimately to "FSFCtrl")
//  //storage for probes...
//  vector<double> Cemf_a;   //for expression "Ka*omega*sin(Nr*theta)"
//  vector<double> VBus_a;   //"vs_a" (processed DC_BUS_VOLTAGE or 0 depending on "pwm_sig")
//  vector<double> VRa;      //for expression "Ra*ia"
//  vector<double> Theta_enc;     //quantitized motor position based on ENCODER_RESOLUTION (rad).
//  vector<double> Omega_enc;     //quantitized motor velocity based on ENCODER_RESOLUTION (rad/sec).
};

Is1_Is2_Is3_Ir1_Ir2_1 Inst_Is1_Is2_Is3_Ir1_Ir2_1;


// --------------------------------------------------------

// ---- Ia_Ib_Ic_2 -----------------------------------------

class Ia_Ib_Ic_2 : public OdeObject
{
public:
  virtual double OdeFunction(double y, double t);
  virtual void OdeRValueUpdate(void);
  virtual void RecordProbes(void);
  virtual void PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[]);
  Ia_Ib_Ic_2(void);
  ~Ia_Ib_Ic_2(void);
  //source for this ODE
  double vs_b;
  double pwm_sig;
  double ib;
  double omega;
  double theta;
  double v_n;
  //storage for probes...   
  vector<double> Cemf_b;   //for expression "Kb*omega*sin(Nr*theta - 2*PI/3)"
  vector<double> VBus_b;   //"vs_b" (processed DC_BUS_VOLTAGE or 0 depending on "pwm_sig")
  vector<double> VRb;      //for expression "Rb*ib"
};

Ia_Ib_Ic_2 Inst_Ia_Ib_Ic_2;

  


// --------------------------------------------------------


// ---- Ia_Ib_Ic_3 -----------------------------------------

class Ia_Ib_Ic_3 : public OdeObject
{
public:
  virtual double OdeFunction(double y, double t);
  virtual void OdeRValueUpdate(void);
  virtual void RecordProbes(void);
  virtual void PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[]);
  Ia_Ib_Ic_3(void);
  ~Ia_Ib_Ic_3(void);
  //source for this ODE
  double vs_c;
  double pwm_sig;
  double ic;
  double omega;
  double theta;
  double v_n;
  //storage for probes...
  vector<double> Cemf_c;   //for expression "Kc*omega*sin(Nr*theta - 4*PI/3)"
  vector<double> VBus_c;   //"vs_c" (processed DC_BUS_VOLTAGE or 0 depending on "pwm_sig")
  vector<double> VRc;      //for expression "Rc*ic"
};

Ia_Ib_Ic_3 Inst_Ia_Ib_Ic_3;


// --------------------------------------------------------


// ---- Omega ---------------------------------------------

class Omega : public OdeObject
{
public:
  virtual double OdeFunction(double y, double t);
  virtual void OdeRValueUpdate(void);
  Omega(void);
  ~Omega(void);
  //source for this ODE
  double ia;
  double ib;
  double ic;
  double theta;



};

Omega Inst_Omega;


// --------------------------------------------------------

// ---- Theta ---------------------------------------------

class Theta : public OdeObject
{
public:
  virtual double OdeFunction(double y, double t);
  virtual void OdeRValueUpdate(void);
  virtual void CtrlRValueUpdate(void);
  Theta(void);
  ~Theta(void);
  //source for this ODE
  double omega;

};

Theta Inst_Theta;

// --------------------------------------------------------

// ---- Probe ---------------------------------------------

class Probe : public OdeObject
{
public:
  //(No OdeFunction() here, we are just using this to sync.data for probes.
  //The variable "v_n" is the problem here. It is calculated in a "group solve").
  virtual void RecordProbes(void);
  virtual void PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[]);
  Probe(void);
  ~Probe(void);
  //soure for this ODE
  double ia;
  double ib;
  double ic;
  double vs_a;
  double vs_b;
  double vs_c;
  double v_n;
  double omega;
  double theta;
  //storage for probes...
  vector<double> Vcm_a;    //for expression  "vs_a - Ra*ia - Ka*omega*sin(Nr*theta) - v_n"        
  vector<double> Vcm_b;    //for expression  "vs_b - Rb*ib - Kb*omega*sin(Nr*theta - 2*PI/3) - v_n"     
  vector<double> Vcm_c;    //for expression  "vs_c - Rc*ic - Kc*omega*sin(Nr*theta - 4*PI/3) - v_n" 
  vector<double> V_n;       //for the instantanious neutral voltage "v_n"
};

Probe Inst_Probe;

// --------------------------------------------------------




OdeObject * OdeObjectList[] = {(OdeObject *) &Inst_Ia_Ib_Ic_1, //the next three are in a group and must be maintained in this order.
			       (OdeObject *) &Inst_Ia_Ib_Ic_2,
			       (OdeObject *) &Inst_Ia_Ib_Ic_3,
			       (OdeObject *) &Inst_Omega,
			       (OdeObject *) &Inst_Theta,
			       (OdeObject *) &Inst_Probe,
			       0};


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



// **** CtrlObject Classes **********************************




// ---- VDqCmd  ---------------------------------------------

class VDqCmd : public CtrlObject
{
public:
  virtual void CtrlFunction(double t);
  virtual void OdeRValueUpdate(void);
  virtual void CtrlRValueUpdate(void);
  virtual void RecordProbes(void);
  virtual void PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[]);
  VDqCmd(void);
  ~VDqCmd(void);
  void SpaceVectorControl(void);
  //source for this CTRL
  double V_xo[3];
  double theta;
  double omega;    
  double alpha;    
  double vdd;
  double vqd;
     // Commands for magnitude and angle in the rotating D/Q plane. (These
     // commands ultimately come from another CTRL that is not part
     // of this simulation).
  double vcmd_mag;
  double vcmd_ang;
     // This signal is ultimate feed by a SRC or ODE that simulates the DC bus with
     // ripple voltage. For now, it will be set to a constant.
  double v_bus;
     // This table used to construct the reference commands for each phase.
  REFERENCE_CONSTRUCT SVTable[6][3];  
     // Set to FALSE if operation is SVPWM "clamped" mode (minus side).
  bool HighSpeedSVPwm;
  //intermediary varables need for debugging only.
  double V_xo_debug[3];
  double PwmFreqScale;
  //storage for probes..
  vector<double> VCmd_a;  //value of V_xo[0].
  vector<double> VCmd_b;  //value of V_xo[1].
  vector<double> VCmd_c;  //value of V_xo[2].
  vector<double> VCmd_mag; 
  vector<double> VCmd_ang; 
  vector<double> FreqScale;
};



VDqCmd Inst_VDqCmd;

// -------------------------------------------------------------




// ---- RefGen  ---------------------------------------------

class RefGen : public CtrlObject
{

public:
  virtual void CtrlFunction(double t);
  virtual void CtrlRValueUpdate(void);
  virtual void RecordProbes(void);
  virtual void PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[]);
  double sgn(double omegad);
  double impulse(double sgn_omegad);
  RefGen(void);
  ~RefGen(void);
  //source for this CTRL
  double betad;
  double alphad;
  double omegad;
  double thetad;
  double zetad;
  double idd;
  double iqd;
  double didd;
  double diqd;
  double vdd;
  double vqd;
  //storage for probes..
  vector<double> beta_d;
  vector<double> alpha_d;
  vector<double> omega_d;
  vector<double> theta_d;
  vector<double> zeta_d;
  vector<double> id_d;
  vector<double> iq_d;
  vector<double> did_d;
  vector<double> diq_d;
  vector<double> vd_d;
  vector<double> vq_d;  




};








RefGen Inst_RefGen;

// -------------------------------------------------------------





//(NOTE: As of 6/12/08, "pTranslationList" and "pTrajectoryList" CTRL's have been 
//       deprecated and replaced with a "group" structure. However, we still maintain
//       only one "CtrlObjectList[]" array for all groups, but we add a "CtrlObjGroupStatus[]"
//       array to specify the "quantum" value for each CTRL object)

CtrlObject * CtrlObjectList[] = {(CtrlObject *) &Inst_RefGen,
                                 (CtrlObject *) &Inst_VDqCmd,
				 0};
        //This array contains the value of the execution quantium for each CtrlObject listed above
        //The order of this list must be relative to the order of the "CtrlObjectList[]" above.
        //CtrlObjects with the same quantum values may be considered a "group" of CtrlObjects.
        //However, there is no requirement that these CtrlObjects be related to each other.
      
int CtrlObjectQuantum[] = { REF_GEN_QUANTUM_CNT,
                            VDQ_CMD_QUANTUM_CNT,
                          };

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











// **** SrcObject Functions **************************************

// ---- TriangleWave  ----------------------------------------------------

TriangleWave::TriangleWave(void)
{
 
  SrcObjItem * pCurSrcItem;
  OdeObjItem * pCurOdeItem;

  SrcFuncName = SRC_FUNC_TriangleWave;
  LiteralName = "TriangleWave";


  //build the SRC Rvalue list.

  pSrcObjRValList = new SrcObjItem;
  pCurSrcItem = pSrcObjRValList;

  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_PwmA];
  pCurSrcItem->pNextSrcItem = new SrcObjItem;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_PwmB];
  pCurSrcItem->pNextSrcItem = new SrcObjItem;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_PwmC];





  PwmRampDir = 1.0;
#ifdef RECORD_ALL_PROBES
  PlotThisOutput = TRUE;
#endif 
  Plot_Tag = "TriangleWave";
}

TriangleWave::~TriangleWave(void)
{



}

void TriangleWave::SrcFunction(double t)
{
  t_mod += (t - t_prev);
  t_prev = t;

  if(t_mod > QUARTER_PWM_CYCLE){
    t_mod -=  QUARTER_PWM_CYCLE;
    PwmRampDir *= -1.0;
  }
 
  y = PWM_GAIN*(t_mod/QUARTER_PWM_CYCLE - .5)*PwmRampDir + PWM_OFFSET;

}

void TriangleWave::OdeRValueUpdate(void)         //!!!!! Pwm's should be in SrcRValueUpdate() (should not change operation) !!!!!!1
{
  SrcObjItem * pCurSrcItem;
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurSrcItem = pSrcObjRValList;

  ((PwmA *) pCurSrcItem->pSrcObject)->TriAngWave = y;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;    
  ((PwmB *) pCurSrcItem->pSrcObject)->TriAngWave = y;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;    
  ((PwmC *) pCurSrcItem->pSrcObject)->TriAngWave = y;


  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((ISample *) pCurOdeItem->pOdeObject)->TriAngWave = y;

 

}




// -----------------------------------------------------------------

// ---- PwmA ---------------------------------------------------

PwmA::PwmA(void)
{
  OdeObjItem * pCurOdeItem;

  SrcFuncName = SRC_FUNC_PwmA;
  LiteralName = "PwmA";
  
  //build the ODE Rvalue list.

  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_1];  

}

PwmA::~PwmA(void)
{



}

void PwmA::SrcFunction(double t)
{



  //For simulation, "V_xo" is space vector reference to a triangle wave
  //running between 0 and PWM_GAIN.
  y = V_xo > TriAngWave ? 1.0 : 0;




}

void PwmA::OdeRValueUpdate(void)
{


  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

#ifndef LINEAR_AMP_MODE

  ((Ia_Ib_Ic_1 *) pCurOdeItem->pOdeObject)->pwm_sig = y;

#endif 

}


// -----------------------------------------------------------------


// ---- PwmB ---------------------------------------------------


PwmB::PwmB(void)
{
  OdeObjItem * pCurOdeItem;

  SrcFuncName = SRC_FUNC_PwmB;
  LiteralName = "PwmB";
  
  //build the ODE Rvalue list.

  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_2];  

}


PwmB::~PwmB(void)
{


}


void PwmB::SrcFunction(double t)
{



  //For simulation, "V_xo" is space vector reference to a triangle wave
  //running between 0 and PWM_GAIN.
  y = V_xo > TriAngWave ? 1.0 : 0;





}

void PwmB::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

#ifndef LINEAR_AMP_MODE

  ((Ia_Ib_Ic_2 *) pCurOdeItem->pOdeObject)->pwm_sig = y;

#endif 


}

// ----------------------------------------------------------------- 


// ---- PwmC ---------------------------------------------------

PwmC::PwmC(void)
{
  OdeObjItem * pCurOdeItem;

  SrcFuncName = SRC_FUNC_PwmC;
  LiteralName = "PwmC";
  
  //build the ODE Rvalue list.

  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_3];  

}

PwmC::~PwmC(void)
{


}


void PwmC::SrcFunction(double t)
{



  //For simulation, "V_xo" is space vector reference to a triangle wave
  //running between 0 and PWM_GAIN.
  y = V_xo > TriAngWave ? 1.0 : 0;




}

void PwmC::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

#ifndef LINEAR_AMP_MODE

  ((Ia_Ib_Ic_3 *) pCurOdeItem->pOdeObject)->pwm_sig = y;

#endif 


}

// ----------------------------------------------------------------- 






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


// **** OdeObject Functions **************************************


// ---- Ia_Ib_Ic_1  ----------------------------------------------------

Ia_Ib_Ic_1::Ia_Ib_Ic_1(void)
{
  OdeObjItem * pCurOdeItem;

  OdeFuncName = ODE_FUNC_Ia_Ib_Ic_1;
  LiteralName = "Ia_Ib_Ic_1"; 
  

  //this object marks the beginning of a "group solve" of
  //three objects.
  GroupSolve = 1;
  NumberOfGrpOdes = 3;

  //build the ODE Rvalue list.
 
  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Omega];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];

  pwm_sig = 0;
  ia = 0;
 

  PlotThisOutput = TRUE;
  Plot_Tag = "Ia";
  DoProbes = TRUE;
  
}

Ia_Ib_Ic_1::~Ia_Ib_Ic_1(void)
{

}

double Ia_Ib_Ic_1::OdeFunction(double y, double t)
{

  //Note: This is within a "group" ODE so we are really returning for "dm/dt + v_n"

          //"vs_a - Ra*ia + Ka*omega*sin(Nr*theta)" 
#ifdef LINEAR_AMP_MODE
     //generating the voltage command directly through CtrlObject "VDqCmd" 
  vs_a = pwm_sig + .5*DC_BUS_VOLTAGE;
#else
  vs_a = ShapeSquareWaveSource(((pwm_sig > 0) ? DC_BUS_VOLTAGE : 0), SRC_SLEW_RATE ,t);
#endif 
  //(Note: "v_n" is really part of the LValue when we are doing the calculations).
  return(vs_a - Ra*y + Ka*omega*sin(Nr*theta));
}

void Ia_Ib_Ic_1::PostOdeFunction(double t)
{
  //un-comment this to allow encoder single to generated.
  //#define GENERATE_ENCODER_FEEDBACK
#ifdef GENERATE_ENCODER_FEEDBACK

  PositionFeedback = (int) (theta/(2*PI) * ENCODER_RESOLUTION);
  VelocityFeedback = (int) (omega/(2*PI) * ENCODER_RESOLUTION);
#endif 

}


void Ia_Ib_Ic_1::RecordProbes(void)
{
  VBus_a.push_back(vs_a);
#ifdef RECORD_ALL_PROBES
  Cemf_a.push_back(Ka*omega*sin(Nr*theta));
  //"Ra*ia"
  VRa.push_back(Ra*y); 
#ifdef GENERATE_ENCODER_FEEDBACK
  Theta_enc.push_back((double) PositionFeedback * 2 * PI / ENCODER_RESOLUTION);
  Omega_enc.push_back((double) VelocityFeedback * 2 * PI / ENCODER_RESOLUTION);
#endif 
#endif 

}

void Ia_Ib_Ic_1::PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[])
{
  int i;
  if(TagNamesToPlot[0] == ""){
    SimuPlot.plot_xy(Plot_t, Cemf_a, "Cemf_a");
    SimuPlot.plot_xy(Plot_t, VBus_a, "VBus_a");
    SimuPlot.plot_xy(Plot_t, VRa, "VRa");  
#ifdef GENERATE_ENCODER_FEEDBACK
    SimuPlot.plot_xy(Plot_t, Theta_enc, "Theta_enc");
    SimuPlot.plot_xy(Plot_t, Omega_enc, "Omega_enc");
#endif 
  }
  else{
    for(i = 0; i < 20; i++){
      if(TagNamesToPlot[i] == "Cemf_a"){
	SimuPlot.plot_xy(Plot_t, Cemf_a, "Cemf_a");
      }
      else if(TagNamesToPlot[i] == "VBus_a"){
	SimuPlot.plot_xy(Plot_t, VBus_a, "VBus_a");
      }
      else if(TagNamesToPlot[i] == "VRa"){
	SimuPlot.plot_xy(Plot_t, VRa, "VRa");
      }
#ifdef GENERATE_ENCODER_FEEDBACK
      else if(TagNamesToPlot[i] == "Theta_enc"){
	SimuPlot.plot_xy(Plot_t, Theta_enc, "Theta_enc");
      }
      else if(TagNamesToPlot[i] == "Omega_enc"){
	SimuPlot.plot_xy(Plot_t, Omega_enc, "Omega_enc");
      }
#endif 
      else if(TagNamesToPlot[i] == ""){
	break;
      }
    }

  }
}

       

void Ia_Ib_Ic_1::OdeGroupMSolve(double dydt[], double dmdt[])
{
  //Note: This instance is the first of the group. As such, this
  //      is where the "group solve" of the individual 
  //      "dy/dt's" is performed.

  //
  //   We must solve for dia/dt, dib/dt, dic/t and v_n in (1), (2), and (3)
  //   where the right side of these equations is passed to us, the values
  //   in "dmdt[]". The "dydt[]" array hold the results. The value "v_n"
  //   is an intermediate value need to solve for dia/dt, dib/dt, and dic/d.
  //
  //
  //   Let
  //         dia = dia/dt, dib = dib/dt and dic = dic/dt
  //         
  //
  //       Lm_a*dia - Mab*dib - Mac*dic + v_n = dmdt[0]       (a)
  //
  //       - Mab*dia + Lm_b*dib - Mbc*dic + v_n = dmdt[1]     (b)
  //
  //       - Mac*dia - Mbc*dib + Lm_c*dic + v_n = dmdt[2]     (c)
  //
  //
  //
  //   Solve for dia in (b) and (c) and subtract (c) from (b)
  //
  //
  //          
  //       dia = (Lm_b*dib - Mbc*dic + v_n - dmdt[1])/Mab            
  //
  //       dia = (- Mbc*dib + Lm_c*dic + v_n - dmdt[2])/Mac          
  //
  //       (Lm_b*dib - Mbc*dic + v_n - dmdt[1])/Mab = (- Mbc*dib + Lm_c*dic + v_n - dmdt[2])/Mac 
  //
  //       (Lm_b/Mab + Mbc/Mac)*dib + (- Lm_c/Mac - Mbc/Mab)*dic = - v_n/Mab + dmdt[1]/Mab + v_n/Mac - dmdt[2]/Mac       (d)
  //
  //
  //
  //
  //
  //   Solve for dia in (a) and (b) and subtract (b) from (a)
  //
  //
  //       dia = (Mab*dib + Mac*dic - v_n + dmdt[0])/Lm_a
  //
  //       dia = (Lm_b*dib - Mbc*dic + v_n - dmdt[1])/Mab  
  //     
  //       (Mab*dib + Mac*dic - v_n + dmdt[0])/Lm_a = (Lm_b*dib - Mbc*dic + v_n - dmdt[1])/Mab 
  //
  //       (Mab/Lm_a - Lm_b/Mab)*dib + (Mac/Lm_a + Mbc/Mab)*dic = v_n/Lm_a + v_n/Mab - dmdt[0]/Lm_a - dmdt[1]/Mab       (e)
  //
  //
  //
  //
  //       Simplify (d) and (e)   
  //
  //       A1*dib + B1*dic = C1                 (f)           
  //
  //       A2*dib + B2*dic = C2                 (g)
  //
  //                 Where...
  //
  //       A1 = (Lm_b/Mab + Mbc/Mac)       
  //       B1 = (- Lm_c/Mac - Mbc/Mab)
  //       C1 = - v_n/Mab + dmdt[1]/Mab + v_n/Mac - dmdt[2]/Mac
  //       A2 = (Mab/Lm_a - Lm_b/Mab)
  //       B2 = (Mac/Lm_a + Mbc/Mab)
  //       C2 = v_n/Lm_a + v_n/Mab - dmdt[0]/Lm_a - dmdt[1]/Mab
  //
  //
  //
  //
  //       Solve for dib and dic, (g) into (f) 
  //
  //       A1*dib + B1*(C2 - A2*dib)/B2 = C1
  //
  //       A1*dib - B1*A2*dib/B2 = C1 - B1*C2/B2
  //
  //       dib = (C1 - B1*C2/B2)/(A1 - B1*A2/B2) = (B2*C1 - B1*C2)/(B2*A1 - B1*A2)     (h)
  //           
  //       Note that (h) can be simplified further (see below)
  //
  //       And (h) into (g)
  //
  //       A2*(B2*C1 - B1*C2)/(B2*A1 - B1*A2) + B2*dic = C2
  //
  //       dic = (C2 - A2*(B2*C1 - B1*C2)/(B2*A1 - B1*A2))/B2 = (C2 - A2*dib)/B2       (i)
  //
  //       (h) and (i) into (a) and solve for dia
  //
  //       dia = (Mab*dib + Mac*dic - v_n + dmdt[0])/Lm_a                              (j)
  //
  //
  //
  //
  //       Now, using the identity,
  //
  //           dia + dib + dic = 0   and (h), (i), (j)
  //
  //       Solve for v_n
  //
  //       (Mab*(B2*C1 - B1*C2)/(B2*A1 - B1*A2) + Mac*(C2 - A2*(B2*C1 - B1*C2)/(B2*A1 - B1*A2))/B2 - v_n + dmdt[0])/Lm_a + 
  //       (B2*C1 - B1*C2)/(B2*A1 - B1*A2) + 
  //       (C2 - A2*(B2*C1 - B1*C2)/(B2*A1 - B1*A2))/B2 
  //       = 0                                                                         
  //
  //       Simplify 
  //
  //       (Mab*E/D + Mac*(C2 - A2*E/D)/B2 - v_n + dmdt[0])/Lm_a + 
  //       E/D + 
  //       (C2 - A2*E/D)/B2 
  //       = 0  
  //
  //                Where...
  //                    
  //                       D = (B2*A1 - B1*A2)                                  (k)                        
  //                       E = (B2*C1 - B1*C2)
  //      
  //       Expand
  //
  //       Mab*E/(D*Lm_a) + Mac*C2/(B2*Lm_a) - Mac*A2*E/(D*B2*Lm_a) - v_n/Lm_a + dmdt[0]/Lm_a + E/D + C2/B2 - A2*E/(D*B2) = 0
  //
  //       And
  //
  //       Mab*E/(D*Lm_a) + Mac*C2/(B2*Lm_a) - Mac*A2*E/(F*Lm_a) - v_n/Lm_a + dmdt[0]/Lm_a + E/D + C2/B2 - A2*E/F = 0 
  //
  //                Where...
  //              
  //                       F = (D*B2)
  //
  //       Group C2 and E expressions to the left
  //        
  //
  //       Mab*E/(D*Lm_a) - Mac*A2*E/(F*Lm_a) + E/D - A2*E/F + Mac*C2/(B2*Lm_a) + C2/B2  = v_n/Lm_a - dmdt[0]/Lm_a 
  //
  //       E*(Mab/(D*Lm_a) - Mac*A2/(F*Lm_a) + 1/D - A2/F) + C2*(Mac/(B2*Lm_a) + 1/B2)  = v_n/Lm_a - dmdt[0]/Lm_a 
  //
  //       And
  //
  //       E*G + C2*H = v_n/Lm_a - dmdt[0]/Lm_a 
  //
  //               Where...
  //
  //                       G = (Mab/(D*Lm_a) - Mac*A2/(F*Lm_a) + 1/D - A2/F)
  //                       H = (Mac/(B2*Lm_a) + 1/B2)
  //
  //
  //       Expand E and group terms
  //
  //       (B2*C1 - B1*C2)*G + C2*H = v_n/Lm_a - dmdt[0]/Lm_a 
  //   
  //       C1*B2*G + C2*(H - B1*G) = v_n/Lm_a - dmdt[0]/Lm_a  
  //
  //
  //       Expand C1 and C2 and group terms
  //
  //       (- v_n/Mab + dmdt[1]/Mab + v_n/Mac - dmdt[2]/Mac)*B2*G + (v_n/Lm_a + v_n/Mab - dmdt[0]/Lm_a - dmdt[1]/Mab)*(H - B1*G) = 
  //                  v_n/Lm_a - dmdt[0]/Lm_a                         
  //
  //       v_n*(-B2*G/Mab + B2*G/Mac + (H - B1*G)/Lm_a + (H - B1*G)/Mab - 1/Lm_a) = (dmdt[2]/Mac - dmdt[1]/Mab)*B2*G +
  //                                                       (dmdt[0]/Lm_a + dmdt[1]/Mab)*(H - B1*G) - dmdt[0]/Lm_a 
  //
  //
  //       Finally,
  //
  //
  //       v_n = ((dmdt[2]/Mac - dmdt[1]/Mab)*B2*G + (dmdt[0]/Lm_a + dmdt[1]/Mab)*(H - B1*G) - dmdt[0]/Lm_a)/ 
  //                     (-B2*G/Mab + B2*G/Mac + (H - B1*G)/Lm_a + (H - B1*G)/Mab - 1/Lm_a)                     (l)
  //
  //
  //       Note that (h) and be further simplified by (k).
  //
  //       dib = (B2*C1 - B1*C2)/D
  //
  //       And (l) can be reduced further
  //
  //       v_n = ((dmdt[2]/Mac - dmdt[1]/Mab)*J + (dmdt[0]/Lm_a + dmdt[1]/Mab)*I - dmdt[0]/Lm_a)/ 
  //                     (-J/Mab + J/Mac + I/Lm_a + I/Mab - 1/Lm_a)   
  //
  //
  //           Where...
  //
  //                   I = (H - B1*G)
  //                   J = (B2*G)
  //
  //

  
#define A1  (Lm_b/Mab + Mbc/Mac) 
#define B1  (- Lm_c/Mac - Mbc/Mab)
#define A2  (Mab/Lm_a - Lm_b/Mab)
#define B2  (Mac/Lm_a + Mbc/Mab)

#define D   (B2*A1 - B1*A2)
#define F   (D*B2)
#define G   (Mab/(D*Lm_a) - Mac*A2/(F*Lm_a) + 1/D - A2/F)
#define H   (Mac/(B2*Lm_a) + 1/B2)
  
#define I   (H - B1*G)
#define J   (B2*G) 


  double dia;
  double dib;
  double dic;

  double C1;
  double C2;

  v_n = ((dmdt[2]/Mac - dmdt[1]/Mab)*J + (dmdt[0]/Lm_a + dmdt[1]/Mab)*I - dmdt[0]/Lm_a) / 
    (-J/Mab + J/Mac + I/Lm_a + I/Mab - 1/Lm_a);  

  C1 = - v_n/Mab + dmdt[1]/Mab + v_n/Mac - dmdt[2]/Mac;
  C2 = v_n/Lm_a + v_n/Mab - dmdt[0]/Lm_a - dmdt[1]/Mab;

  dib = (B2*C1 - B1*C2)/D;                
  dic = (C2 - A2*dib)/B2; 
  dia = (Mab*dib + Mac*dic - v_n + dmdt[0])/Lm_a; 

  dydt[0] = dia;
  dydt[1] = dib;
  dydt[2] = dic;

}

void Ia_Ib_Ic_1::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((Omega *) pCurOdeItem->pOdeObject)->ia = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->ia = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->vs_a = vs_a;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->v_n = v_n;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((ISample *) pCurOdeItem->pOdeObject)->ia = y;
  
}


void Is1_Is2_Is3_Ir1_Ir2_1::CalculateMutualInductances(void)
{


	#define PI 3.1415926535897932384626433832795

	// Parameters for 2 pole stator mutual inductance calculation:
	// (Example code in /home/maiello/Development-Simulation/BDFM-Dissertation-2005-Tests/Section_B_2 for 4 pole stator)


	#define w  .1955
	#define d  .175065
	#define Nk  10.0
	#define Nj  10.0
	#define g  .000555
	#define u0  (4.0*PI*1.0e-7)   //Permeability of vacuum.

	#define Ack  (2.0*PI*10.0/24.0)     //From Figure 2.2 on page 42.
	#define Wsk  (2.0*PI*.0032/(2.0*PI*d/2.0))   //


	#define Acj  Ack	       //These the same as the k'th circuit.
	#define Wsj  Wsk               //




	#define slot_pitch (2.0*PI/24.0)  //degrees center-to-center of two consecutive slots.
	#define dTheta (2.0*PI/360.0)      //One degree integration.




	double Bk;    	   	  //This changes depending on which row of the mutual inductance matrix is being calculated.
	double Bj;		       //This becomes the variable for computing each matrix element of a given row.
	double M[24][24] = {0};		       //One row of the mutual inductance matrix for the 4 pole calculation and 8 pole calculation

	double Theta;


	double integral_cos_cos = 0;





	double Mss_2_r[3][24];
	double Mss_2[3][3];



	int n,i,j,k;

	//We use the mutual inductance equation defined in Eq 2.27 on page 46, Section 2.4.3 because there is no coil groups.
	//This seems to be the method taken by the paper when reviewing the equations listed in Eq. B.8, page 256. However
	//what is misleading is the addition of parameters Kd,  Kp and Ks winding factors which tend to suggest the use of
	//of equations Eq. 2.36 through Eq. 2.39 on pages 52 and 53.)

	for(i = 0; i < 24; i++)
	{


		if(i < 8)
		{
			if(i < 4)
			{
			    Bk = slot_pitch * (double) i;                 //Start of Uout (i = 0)
			}
			else
			{
			    Bk = 12.0 * slot_pitch + slot_pitch * (double) (i - 4);
			}
		}
		else if(i < 16)
		{

			if(i < 12)
			{
			    Bk = slot_pitch * (double) (i - 8) + slot_pitch * 8.0;       //Start of Vout  (i = 8)
			}
			else
			{
			    Bk = 12.0 * slot_pitch + slot_pitch * (double) (i - 12)  + slot_pitch * 8.0;
			}

		}
		else
		{
			if(i < 20)
			{
			    Bk = slot_pitch * (double) (i - 16) + slot_pitch * 16.0;          //Start of Wout (i = 16)
			}
			else
			{
			    Bk = 12.0 * slot_pitch + slot_pitch * (double) (i - 20)  + slot_pitch * 16.0;
			}

		}

		for(k = 0; k < 24; k++)
		{

			if(k < 8)
			{
				if(k < 4)
				{
				    Bj = slot_pitch * (double) k;                 //Start of Uout (i = 0)
				}
				else
				{
				    Bj = 12.0 * slot_pitch + slot_pitch * (double) (k - 4);
				}
			}
			else if(k < 16)
			{

				if(k < 12)
				{
				    Bj = slot_pitch * (double) (k - 8) + slot_pitch * 8.0;       //Start of Vout  (i = 8)
				}
				else
				{
				    Bj = 12.0 * slot_pitch + slot_pitch * (double) (k - 12)  + slot_pitch * 8.0;
				}

			}
			else
			{
				if(k < 20)
				{
				    Bj = slot_pitch * (double) (k - 16) + slot_pitch * 16.0;          //Start of Wout (i = 16)
				}
				else
				{
				    Bj = 12.0 * slot_pitch + slot_pitch * (double) (k - 20)  + slot_pitch * 16.0;
				}

			}




		   for(n = 1; n < 100; n++)
		   {

				for(Theta = 0; Theta < 2.0*PI; Theta = Theta + dTheta)
				{
					integral_cos_cos = integral_cos_cos + cos((double) n * (Theta - Bk - Ack/2.0 - Wsk/2.0)) * cos((double) n * (Theta - Bj - Acj/2.0 - Wsj/2.0)) * dTheta;
				}

				M[i][k] = M[i][k] + ((w*d*2.0*Nk*u0*2.0*Nj)/(2.0*PI*g*PI))*sin((double) n * Ack/2.0) * sin((double) n * Wsk/2.0) * sin((double) n * Acj/2.0) * sin((double) n * Wsj/2.0) *
											integral_cos_cos /
												(((double) n * (double) n * Wsk/2.0) * ((double) n * (double) n * Wsj/2.0));

				integral_cos_cos = 0;
	 	    }


	    }

	}


	for(k = 0; k < 24; k++)
    {
	   for(j = 0; j < 3; j++)
	   {
		  for(i = 0; i < 24; i++)
	      {
			  Mss_2_r[j][k] = Mss_2_r[j][k] + M[k][i]*Ts_2[j][i];
	      }
	   }
    }


	for(k = 0; k < 3; k++)
    {
	   for(j = 0; j < 3; j++)
       {
	      for(i = 0; i < 24; i++)
	      {
	    	  Mss_2[k][j] = Mss_2[k][j] + Ts_2[j][i]*Mss_2_r[k][i];
	      }
        }
    }



}


// -----------------------------------------------------------------


// ---- Ia_QI_Ic_2  ----------------------------------------------------



Ia_Ib_Ic_2::Ia_Ib_Ic_2(void)
{
  OdeObjItem * pCurOdeItem;

  OdeFuncName = ODE_FUNC_Ia_Ib_Ic_2;
  LiteralName = "Ia_Ib_Ic_2";  

  //build the ODE Rvalue list.
 
  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Omega];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];

  pwm_sig = 0;
  ib = 0;
 

  PlotThisOutput = TRUE;
  Plot_Tag = "Ib";
  DoProbes = TRUE;
  
}



Ia_Ib_Ic_2::~Ia_Ib_Ic_2(void)
{

}



double Ia_Ib_Ic_2::OdeFunction(double y, double t)
{
 
  //Note: This is within a "group" ODE so we are really returning for "dm/dt + v_n"

          //"vs_b - Rb*ib + Kb*omega*sin(Nr*theta - 2*PI/3))" 
#ifdef LINEAR_AMP_MODE
     //generating the voltage command directly through CtrlObject "VDqCmd" 
  vs_b = pwm_sig + .5*DC_BUS_VOLTAGE;
#else
  vs_b = ShapeSquareWaveSource(((pwm_sig > 0) ? DC_BUS_VOLTAGE : 0), SRC_SLEW_RATE ,t);
#endif
  //(Note: "v_n" is really part of the LValue when we are doing the calculations).
  return(vs_b - Rb*y + Kb*omega*sin(Nr*theta - 2*PI/3));
}


void Ia_Ib_Ic_2::RecordProbes(void)
{
  VBus_b.push_back(vs_b);
#ifdef RECORD_ALL_PROBES
  Cemf_b.push_back(Kb*omega*sin(Nr*theta - 2*PI/3));
  //"Rb*ib"
  VRb.push_back(Rb*y); 
#endif
}




void Ia_Ib_Ic_2::PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[])
{
  int i;
  if(TagNamesToPlot[0] == ""){
    SimuPlot.plot_xy(Plot_t, Cemf_b, "Cemf_b");
    SimuPlot.plot_xy(Plot_t, VBus_b, "VBus_b");
    SimuPlot.plot_xy(Plot_t, VRb, "VRb");  
  }
  else{
    for(i = 0; i < 20; i++){
      if(TagNamesToPlot[i] == "Cemf_b"){
	SimuPlot.plot_xy(Plot_t, Cemf_b, "Cemf_b");
      }
      else if(TagNamesToPlot[i] == "VBus_b"){
	SimuPlot.plot_xy(Plot_t, VBus_b, "VBus_b");
      }
      else if(TagNamesToPlot[i] == "VRb"){
	SimuPlot.plot_xy(Plot_t, VRb, "VRb");
      }
      else if(TagNamesToPlot[i] == ""){
	break;
      }
    }

  }
}




void Ia_Ib_Ic_2::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((Omega *) pCurOdeItem->pOdeObject)->ib = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->ib = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->vs_b = vs_b;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((ISample *) pCurOdeItem->pOdeObject)->ib = y;
  
}





// -----------------------------------------------------------------


// ---- Ia_Ib_Ic_3  ----------------------------------------------------


Ia_Ib_Ic_3::Ia_Ib_Ic_3(void)
{
  OdeObjItem * pCurOdeItem;

  OdeFuncName = ODE_FUNC_Ia_Ib_Ic_3;
  LiteralName = "Ia_Ib_Ic_3";   

  //build the ODE Rvalue list.
 
  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Omega];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];



  pwm_sig = 0;
  ic = 0;
 

  PlotThisOutput = TRUE;
  Plot_Tag = "Ic";
  DoProbes = TRUE;
  
}



Ia_Ib_Ic_3::~Ia_Ib_Ic_3(void)
{

}

double Ia_Ib_Ic_3::OdeFunction(double y, double t)
{
 
  //Note: This is within a "group" ODE so we are really returning for "dm/dt + v_n"

          //"vs_c - Rc*ic + Kc*omega*sin(Nr*theta - 4*PI/3))" 
#ifdef LINEAR_AMP_MODE
     //generating the voltage command directly through CtrlObject "VDqCmd" 
  vs_c = pwm_sig + .5*DC_BUS_VOLTAGE;
#else
  vs_c = ShapeSquareWaveSource(((pwm_sig > 0) ? DC_BUS_VOLTAGE : 0), SRC_SLEW_RATE ,t);
#endif 
  //(Note: "v_n" is really part of the LValue when we are doing the calculations).
  return(vs_c - Rc*y + Kc*omega*sin(Nr*theta - 4*PI/3));
}


void Ia_Ib_Ic_3::RecordProbes(void)
{
  VBus_c.push_back(vs_c);
#ifdef RECORD_ALL_PROBES
  Cemf_c.push_back(Kc*omega*sin(Nr*theta - 4*PI/3));
  //"Rc*ic"
  VRc.push_back(Rc*y);
#endif  
}



void Ia_Ib_Ic_3::PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[])
{
  int i;
  if(TagNamesToPlot[0] == ""){
    SimuPlot.plot_xy(Plot_t, Cemf_c, "Cemf_c");
    SimuPlot.plot_xy(Plot_t, VBus_c, "VBus_c");
    SimuPlot.plot_xy(Plot_t, VRc, "VRc");  
  }
  else{
    for(i = 0; i < 20; i++){
      if(TagNamesToPlot[i] == "Cemf_c"){
	SimuPlot.plot_xy(Plot_t, Cemf_c, "Cemf_c");
      }
      else if(TagNamesToPlot[i] == "VBus_c"){
	SimuPlot.plot_xy(Plot_t, VBus_c, "VBus_c");
      }
      else if(TagNamesToPlot[i] == "VRc"){
	SimuPlot.plot_xy(Plot_t, VRc, "VRc");
      }
      else if(TagNamesToPlot[i] == ""){
	break;
      }
    }

  }
}



void Ia_Ib_Ic_3::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((Omega *) pCurOdeItem->pOdeObject)->ic = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->ic = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->vs_c = vs_c;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((ISample *) pCurOdeItem->pOdeObject)->ic = y;
  
}

// -----------------------------------------------------------------

// ---- Omega  ----------------------------------------------------

Omega::Omega(void)
{

  OdeObjItem * pCurOdeItem;

  OdeFuncName = ODE_FUNC_Omega;
  LiteralName = "Omega";     

  //build the ODE Rvalue list.

  pOdeObjRValList = new OdeObjItem;          
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_1];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_2];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_3];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Theta];  
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];

  ia = 0;
  ib = 0;
  ic = 0;
  
  
  PlotThisOutput = TRUE;
  Plot_Tag = "Omega";

}

Omega::~Omega(void)
{

}

double Omega::OdeFunction(double y, double t)
{



  //#define FORCE_CONSTANT_OMEGA   //un-comment this generate constant "Omega" to test phase characteristics
#ifdef FORCE_CONSTANT_OMEGA
  //Force "dOmega/dt" to some constant value so that probes like "Cemf_a" and "VBus_a" can be compared.
  //This gives us an Omega that starts from zero and increases in time.

  return(2*PI*100);  //rad/sec**2 (we should see a change of 2*PI*10 radians/sec every .1 sec?) 

#else

         //(- Ka*ia*sin(Nr*theta) - Kb*ib*sin(Nr*theta - 2*PI/3) - Kc*ic*sin(Nr*theta - 4*PI/3) -
         //                        Bm*omega - Cm*sgn(omega) - Dm*sin(2*Nr*theta))/Jm  

  return((- Ka*ia*sin(Nr*theta) - Kb*ib*sin(Nr*theta - 2*PI/3) - Kc*ic*sin(Nr*theta - 4*PI/3) -
	              Bm*y - Cm*(y < 0 ? -1 : (y > 0 ? 1 : 0)) - Dm*sin(2*Nr*theta))/Jm); 

#endif 



}

void Omega::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((Ia_Ib_Ic_1 *) pCurOdeItem->pOdeObject)->omega = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Ia_Ib_Ic_2 *) pCurOdeItem->pOdeObject)->omega = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Ia_Ib_Ic_3 *) pCurOdeItem->pOdeObject)->omega = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Theta *) pCurOdeItem->pOdeObject)->omega = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->omega = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((ISample *) pCurOdeItem->pOdeObject)->omega = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((ISample *) pCurOdeItem->pOdeObject)->alpha = dydt;


}


// -----------------------------------------------------------------




// ---- Theta  ----------------------------------------------------

Theta::Theta(void)
{

  OdeObjItem * pCurOdeItem;
  CtrlObjItem * pCurCtrlItem;

  OdeFuncName = ODE_FUNC_Theta;
  LiteralName = "Theta";    

  //build the ODE Rvalue list.

  pOdeObjRValList = new OdeObjItem;          
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_1];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_2];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_3];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Omega];  
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Probe];


  //build the CTRL Rvalue list
  
  pCtrlObjRValList = new CtrlObjItem;          
  pCurCtrlItem = pCtrlObjRValList;
 
  pCurCtrlItem->pCtrlObject = CtrlObjectList[CTRL_FUNC_VDqCmd];


  omega = 0;
  
#ifdef RECORD_ALL_PROBES  
  PlotThisOutput = TRUE;
#endif 
  Plot_Tag = "Theta";

}

Theta::~Theta(void)
{

}

double Theta::OdeFunction(double y, double t)
{
 


     //omega;
  return(omega); 

}

void Theta::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((Ia_Ib_Ic_1 *) pCurOdeItem->pOdeObject)->theta = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Ia_Ib_Ic_2 *) pCurOdeItem->pOdeObject)->theta = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Ia_Ib_Ic_3 *) pCurOdeItem->pOdeObject)->theta = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Omega *) pCurOdeItem->pOdeObject)->theta = y;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;       
  ((Probe *) pCurOdeItem->pOdeObject)->theta = y;
}

void Theta::CtrlRValueUpdate(void)
{
  CtrlObjItem * pCurCtrlItem;

  //Update Rvalues
  pCurCtrlItem = pCtrlObjRValList;

  ((VDqCmd *) pCurCtrlItem->pCtrlObject)->theta = y;


}


// -----------------------------------------------------------------




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

// ***** CtrlObject Functions ***************************************


// ** (Control of D/Q voltage command) **


// ---- VDqCmd  ---------------------------------------------------

VDqCmd::VDqCmd(void)
{
  SrcObjItem * pCurSrcItem;
  OdeObjItem * pCurOdeItem;

  CtrlFuncName = CTRL_FUNC_VDqCmd;
  LiteralName = "VDqCmd";

  // Refering to Figure 11 of "SpaceVector_PWM_Inverter.pdf", we set  up the reference constructs.
  // The form here is:
  //
  //       SVTable[<sector_index>][<phase>] = <reference construct>
  //
  //                    where
  //                        <sector_index> == SectorNumber - 1
  //
  //                        <phase> == 0 -> "A", 1 -> "B", 2 -> "C"
  //
  //                        <reference construct> == TIME_T1_T2 -> "T1 + T2", TIME_T1 -> "T1", TIME_T2 -> "T2", TIME_NONE -> 0
  //                                                 (for non-clamped SVPWM, add ".5*T0" to all references.
  //

  // Definitions here are for minus side "clamped" SVPWM. For regular SVPWM, add ".5*TO" to all reference values.
  SVTable[0][0] = TIME_T1_T2;
  SVTable[0][1] = TIME_T2;
  SVTable[0][2] = TIME_NONE;
  SVTable[1][0] = TIME_T1;
  SVTable[1][1] = TIME_T1_T2;
  SVTable[1][2] = TIME_NONE;
  SVTable[2][0] = TIME_NONE;
  SVTable[2][1] = TIME_T1_T2;
  SVTable[2][2] = TIME_T2;
  SVTable[3][0] = TIME_NONE;
  SVTable[3][1] = TIME_T1;
  SVTable[3][2] = TIME_T1_T2;
  SVTable[4][0] = TIME_T2;
  SVTable[4][1] = TIME_NONE;
  SVTable[4][2] = TIME_T1_T2;
  SVTable[5][0] = TIME_T1_T2;
  SVTable[5][1] = TIME_NONE;
  SVTable[5][2] = TIME_T1;

  //for now, we run strictly in SVPWM "clamped" mode.
  HighSpeedSVPwm = FALSE;
  //until we can simulate DC bus ripple voltage, we set for a constant value.
  v_bus = DC_BUS_VOLTAGE;

  //build the SRC Rvalue list.

  pSrcObjRValList = new SrcObjItem;
  pCurSrcItem = pSrcObjRValList;

  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_PwmA];
  pCurSrcItem->pNextSrcItem = new SrcObjItem;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_PwmB];
  pCurSrcItem->pNextSrcItem = new SrcObjItem;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_PwmC];
  pCurSrcItem->pNextSrcItem = new SrcObjItem;
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  pCurSrcItem->pSrcObject = SrcObjectList[SRC_FUNC_TriangleWave];


  //build the ODE Rvalue list.

  pOdeObjRValList = new OdeObjItem;
  pCurOdeItem = pOdeObjRValList;

  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_ISample];

#ifdef LINEAR_AMP_MODE
  //we are send the analog voltage commands directly to the "Ia_Ib_Ic_x" OdeObjects's
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_1];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_2];
  pCurOdeItem->pNextOdeItem = new OdeObjItem;
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  pCurOdeItem->pOdeObject = OdeObjectList[ODE_FUNC_Ia_Ib_Ic_3];

#endif

  DoProbes = TRUE;

}

VDqCmd::~VDqCmd(void)
{



}



void VDqCmd::CtrlFunction(double t)
{
  int i;

  //(Note: "y" is not used in this CTRL. We use this CTRL to send command
  //       to the "PwmA", "PwmB" and "PwmC" CTRL's directly.


  //For simulation mode, we generate space vector PWM references.

  //#define CONSTANT_VDQ_COMMAND
#ifdef CONSTANT_VDQ_COMMAND

  //For now, we provide constant commands for magnitude and angle.
  //These will come form seperate CTRL later.
  vcmd_mag = 10.0;
  vcmd_ang = PI/2;   //valid values are  +/-PI/2 <= vcmd_ang < +/-PI (pure "q" to pure "d")
#else

  //#define FSF_CTRL_VDQ_COMMAND
#ifdef FSF_CTRL_VDQ_COMMAND

  //"vcmd_mag" and "vcmd_ang" will be generated from signals "vd" and "vq", the command voltages
  //originating form CtrlObject 'FSFCtrl".

#else



  //This is a "Space Vector" command reference test....

  //VDQ command is generated by "RefGen" CtrlObject. This is a test to see
  //"theta", "omega", and "alpha" tracks "thedad", "omegad", and "alphad". Also if "id" and "iq" (generated in
  //"FSFCtrl" tracks "idd" and "idq"

  vcmd_mag = sqrt(vdd*vdd + vqd*vqd);

  if(vqd != 0){

     if(vqd >= 0)
       vcmd_ang = PI/2.0;
     else
       vcmd_ang = - PI/2.0;


     vcmd_ang -= atan(vdd/vqd);

  }
  else{
    vcmd_ang = PI/2.0;
  }


#endif

#endif


  //#define DEBUG_SPACE_VECTOR_CONTROL   //un-comment this to debug function "SpaceVectorControl()"
#ifdef DEBUG_SPACE_VECTOR_CONTROL
  //force feedback position to sweep a number of cycles so
  //that we may view "V_xo[]"
  theta = PI*t*10;   //specify "- PI*t*10" for minus test.
#endif

  //generate the references.
  SpaceVectorControl();

#ifdef DEBUG_SPACE_VECTOR_CONTROL
  for(i = 0; i < 3; i++){
    //transfer over to debug buffers.
    V_xo_debug[i] = V_xo[i];
    //keep the actual commands zero to prevent the simulation from running away.
    V_xo[i] = 0;
  }

#endif






}

void VDqCmd::RecordProbes(void)
{
#ifdef DEBUG_SPACE_VECTOR_CONTROL

  VCmd_a.push_back(V_xo_debug[0]);
  VCmd_b.push_back(V_xo_debug[1]);
#ifdef RECORD_ALL_PROBES
  VCmd_c.push_back(V_xo_debug[2]);
#endif

#else

  VCmd_a.push_back(V_xo[0]);
  VCmd_b.push_back(V_xo[1]);
#ifdef RECORD_ALL_PROBES
  VCmd_c.push_back(V_xo[2]);
#endif


#endif

  VCmd_mag.push_back(vcmd_mag);
  VCmd_ang.push_back(vcmd_ang);
  FreqScale.push_back(PwmFreqScale);

}

void VDqCmd::PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[])
{

  int i;
  if(TagNamesToPlot[0] == ""){
    SimuPlot.plot_xy(Plot_t, VCmd_a, "VCmd_a");
    SimuPlot.plot_xy(Plot_t, VCmd_b, "VCmd_b");
    SimuPlot.plot_xy(Plot_t, VCmd_c, "VCmd_c");
    SimuPlot.plot_xy(Plot_t, VCmd_mag, "VCmd_mag");
    SimuPlot.plot_xy(Plot_t, VCmd_ang, "VCmd_ang");
    SimuPlot.plot_xy(Plot_t, FreqScale, "FreqScale");
  }
  else{
    for(i = 0; i < 20; i++){
      if(TagNamesToPlot[i] == "VCmd_a"){
	SimuPlot.plot_xy(Plot_t, VCmd_a, "VCmd_a");
      }
      else if(TagNamesToPlot[i] == "VCmd_b"){
	SimuPlot.plot_xy(Plot_t, VCmd_b, "VCmd_b");
      }
      else if(TagNamesToPlot[i] == "VCmd_c"){
	SimuPlot.plot_xy(Plot_t, VCmd_c, "VCmd_c");
      }
      else if(TagNamesToPlot[i] == "VCmd_mag"){
	SimuPlot.plot_xy(Plot_t, VCmd_mag, "VCmd_mag");
      }
      else if(TagNamesToPlot[i] == "VCmd_ang"){
	SimuPlot.plot_xy(Plot_t, VCmd_ang, "VCmd_ang");
      }
      else if(TagNamesToPlot[i] == "FreqScale"){
	SimuPlot.plot_xy(Plot_t, FreqScale, "FreqScale");
      }

    }
  }


}

void  VDqCmd::CtrlRValueUpdate(void)     //!!!!! Pwm's should be in SrcRValueUpdate() (should not change operation) !!!!!!1
{
  SrcObjItem * pCurSrcItem;

  //Update Rvalues
  pCurSrcItem = pSrcObjRValList;

  ((PwmA *) pCurSrcItem->pSrcObject)->V_xo = V_xo[0];
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  ((PwmB *) pCurSrcItem->pSrcObject)->V_xo = V_xo[1];
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  ((PwmC *) pCurSrcItem->pSrcObject)->V_xo = V_xo[2];
  pCurSrcItem = pCurSrcItem->pNextSrcItem;
  ((TriangleWave *) pCurSrcItem->pSrcObject)->PwmFreqScale = PwmFreqScale;


}

void VDqCmd::OdeRValueUpdate(void)
{
  OdeObjItem * pCurOdeItem;

  //Update Rvalues
  pCurOdeItem = pOdeObjRValList;

  ((ISample *) pCurOdeItem->pOdeObject)->V_xo[0] = V_xo[0];
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  ((ISample *) pCurOdeItem->pOdeObject)->V_xo[1] = V_xo[1];
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  ((ISample *) pCurOdeItem->pOdeObject)->V_xo[2] = V_xo[2];

#ifdef LINEAR_AMP_MODE

  //we are sending the analog voltage commands directly to the "Ia_Ib_Ic_x" OdeObjects's
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  ((Ia_Ib_Ic_1 *) pCurOdeItem->pOdeObject)->pwm_sig = V_xo[0];
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  ((Ia_Ib_Ic_2 *) pCurOdeItem->pOdeObject)->pwm_sig = V_xo[1];
  pCurOdeItem = pCurOdeItem->pNextOdeItem;
  ((Ia_Ib_Ic_3 *) pCurOdeItem->pOdeObject)->pwm_sig = V_xo[2];

#endif

}


void VDqCmd::SpaceVectorControl(void)
{



  double CtrlAngle;
  double Amplitude;






  CtrlAngle = Nr*theta;

#ifdef LINEAR_AMP_MODE
  //Here we generate analog voltage commands directly....

  Amplitude = (2.0/3.0);

  V_xo[0] = Amplitude*(vdd*cos(CtrlAngle) - vqd*sin(CtrlAngle));
  V_xo[1] = Amplitude*(vdd*cos(CtrlAngle - 2*PI/3) - vqd*sin(CtrlAngle - 2*PI/3));
  V_xo[2] = Amplitude*(vdd*cos(CtrlAngle - 4*PI/3) - vqd*sin(CtrlAngle - 4*PI/3));

#else

  Amplitude = (2.0/3.0)*PWM_GAIN;

  V_xo[0] = Amplitude*(vdd*cos(CtrlAngle) - vqd*sin(CtrlAngle)) / v_bus;
  V_xo[1] = Amplitude*(vdd*cos(CtrlAngle - 2*PI/3) - vqd*sin(CtrlAngle - 2*PI/3)) / v_bus;
  V_xo[2] = Amplitude*(vdd*cos(CtrlAngle - 4*PI/3) - vqd*sin(CtrlAngle - 4*PI/3)) / v_bus;

#endif



}


// ---------------------------------------------------------------



// ---- RefGen  ---------------------------------------------------

RefGen::RefGen(void)
{
  CtrlObjItem * pCurCtrlItem;

  CtrlFuncName = CTRL_FUNC_RefGen;
  LiteralName = "RefGen";

    //We want this "RefGen" to immediately update "VDqCmd" and other selected CtrlObject's ahead of it after it's
    //control function is executed.
  DoImmedCtrlUpdate = TRUE;

    //build the CTRL Rvalue list

  pCtrlObjRValList = new CtrlObjItem;
  pCurCtrlItem = pCtrlObjRValList;

  pCurCtrlItem->pCtrlObject = CtrlObjectList[CTRL_FUNC_VDqCmd];
  pCurCtrlItem->pNextCtrlItem = new CtrlObjItem;
  pCurCtrlItem = pCurCtrlItem->pNextCtrlItem;
  pCurCtrlItem->pCtrlObject = CtrlObjectList[CTRL_FUNC_VDqCmd];

  //!!!!!!!!!!!!!!!
  //
  //   Here is where we setup to write the following R-values to "FSFCtrl" below
  //
  //   vdd, vqd, idd, iqd, omegad, thetad, zetad
  //
  //
  //
  //!!!!!!!!!!

  DoProbes = TRUE;


}

RefGen::~RefGen(void)
{



}



void RefGen::CtrlFunction(double t)
{
  //Here we generate trajectory and feedforward copensation.
  //Here, the design is based on work presented in Section 3.1 "Reference Trajectory" of document
  //"High Performance Non-Linear Control of Perminant Magnet stepper Motor". A PDF file was generated
  //to highlight this section (see "ReferenceTrajectory.pdf").

  //The system described in the documents above must be translated for use on a AC Brushless Motor
  //(ref "Marc's Original, NOT John's)
  //Refer to documents "AcMotorNotes.pdf" for the model of a AC Brushless Motor, and document
  //"MotorEquations.txt" for a varification of the model. Note that "MotorEquations.txt" MUST be
  //viewed using Microsoft "WordPad". Also refer to document "LagrangeMultipliers.txt" which must
  //be viewed using "emacs".

  //  Equations (13), (14), (15), and (16) of "ReferenceTrajectory.pdf" translated to the equivilent
  //  AC Brushless motor model are as follows (here, variables are stated as "desired" as opposed to "actual").
  //
  //     didd = (vdd - Ridd + omegad*(Lm + M)*iqd)/(Lm + M)                                       (a)
  //
  //     diqd = (vqd - Riqd - omegad*(Lm + M)*idd - 3*K*omegad/2)/(Lm + M)                        (b)
  //
  //     domegad = (K*iqd - Bm*omegad - Cm*sgn(omegad) - Dm*sin(2*Nr*thetad))/Jm                  (c)
  //
  //     dthetad = omegad                                                                         (d)
  //
  //                   where:
  //                          didd => didd/dt
  //                          diqd => diqd/dt
  //                          domegad => domegad/dt
  //                          dthetad => dthetad/dt
  //
  //  In the D/Q form, the following conditions are assumed:
  //
  //      Lm = (Lm_a + Lm_b + Lm_c) / 3
  //      M = (Mab + Mac + Mbc) / 3
  //      R = (Ra + Rb + Rc) / 3
  //      K = (Ka + Kb + Kc) / 3
  //
  //  Similar to  (17), (18), (19), and (20) of "ReferenceTrajectory.pdf",
  //
  //      idd = - ((Lm + M)*K*(3/2)*Nr*omegad**2) / (R**2 + ((Lm + M)*Nr*omegad)**2)               (e)
  //
  //      iqd = (Jm*alphad  + Bm*omegad + Cm*sgn(omegad) + Dm*sin(2*Nr*thetad)) / K                (f)
  //
  //      didd = - (2*K*(3/2)*(Lm + M)*R**2*Nr*omegad*alphad) / (R**2 + (Nr*omegad*(Lm + M))**2)   (g)
  //
  //      diqd = (Jm*betad  + Bm*alphad  + Cm*sgn(omegad) + Dm*sin(2*Nr*thetad)) / K               (h)
  //
  //                    where:
  //                           alphad => domagad
  //                           betad => dalphad
  //
  //
  //                    Note: The equation for "idd" (equation "(e)" above) is an approximation that assumes
  //                          that "alphad" and it's higher order derivitives are are zero. It derivation is
  //                          provided in document "LagrangeMultipliers.txt"
  //
  //                          Also note the "3/2" scale factor added "K" in equation (e) and (g) that differeciates the AC
  //                          Brushless motor expression for "idd" from the Stepping motor expression for "idd".
  //
  //
  //
  //  The values for "dtheda", "domega", "dalpha", and "dbeta" are derived from the trajectory generator
  //  which is explained below. These values are used to determine "idd", "iqd", "didd" and "diqd" in
  //  equations (e) through (h) above.
  //
  //  In turn, these values are used to determine "desired" voltage command "vdd" and "vqd" described
  //  in equations (a) and (b) above.
  //
  //      vdd = (Lm + M)*didd + R*idd - Nr*omegad*(Lm + M)*iqd                                     (i)
  //
  //      vqd = (Lm + M)*idq + R*iqd + Nr*omegad*(Lm + M)*idd + K*(3/2)*omegad                     (j)
  //
  //
  //                  (Again, note the "3/2" scale factor applied to "K" in equation (j))
  //
  //
  //  Equations (i) and (j) provide the feed forward command voltages "vdd" and "vqd" that are used to
  //  calculate "vcmd_mag" and "vcmd_ang" in CtrlObject "VDqCmd".
  //
  //
  //


  double Lm = (Lm_a + Lm_b + Lm_c) / 3.0;
  double M = (Mab + Mac + Mbc) / 3.0;
  double R = (Ra + Rb + Rc) / 3.0;
  double K = (Ka + Kb + Kc) / 3.0;




  //#define EXPONENTIAL_RAMPING
#ifdef EXPONENTIAL_RAMPING

  //  To do:
  //
  //   Implement exponential ramping (with linear ramping within accel/decel segments)
  //
  //     Something like this....
  //
  //     - Generate a velocity profile out of seven (7) segments.
  //     - For t0 <= t < t1, v = t**k
  //     - For t1 <= t < t2, v = t1**k + k*(t - t1)**k-1
  //     - For t2 <= t < t3, v = t1**k + k*(t2 - t1)**k-1 + (t1**k - ((t1 - t0) - (t - t2))**k
  //     - For t3 <= t < t4, v = v_const = t1**k + k*(t2 - t1)**k-1 + (t1**k - ((t1 - t0) - (t3 - t2))**k
  //     - (Similar calculations for ramping down...)
  //
  //
  //     - Now, integrate the final equation above for t between t0 and t7 and equate it to the desired position.
  //
  //     - Given t0, t1, t2, k, v_const and position with t7 - t6 == t1 - t0, t6 - t5 == t2 - t1, and t5 - t4 == t3 - t2
  //       and t3 - t2 == t1 - t0, solve for t3, t4, t5, t6 and t7.
  //
  //     - Execute each equation based on the current value of t within it's time segment.
  //
  //


#else


  //Point to point, "modified sin" trajectory generator.


  if(t < RT_TRAJ){
    omegad = VO_TRAJ*(sin(t*PI/RT_TRAJ - PI/2.0) + 1)/2.0;
    thetad =  VO_TRAJ*(-(RT_TRAJ/PI)*cos(t*PI/RT_TRAJ - PI/2.0) + t)/2.0;
    alphad = VO_TRAJ*(PI/RT_TRAJ)*cos(t*PI/RT_TRAJ - PI/2.0)/2.0;
    betad = VO_TRAJ*(-PI/RT_TRAJ)*(PI/RT_TRAJ)*sin(t*PI/RT_TRAJ - PI/2.0)/2.0;

  }
  else if(t < (RT_TRAJ + CT_TRAJ)){
    omegad = VO_TRAJ;
    thetad = VO_TRAJ*RT_TRAJ/2.0 + VO_TRAJ*(t-RT_TRAJ);
    alphad = 0;
    betad = 0;

  }
  else if(t < (2*RT_TRAJ + CT_TRAJ)){
    omegad = VO_TRAJ*(sin((CT_TRAJ+2*RT_TRAJ-t)*PI/RT_TRAJ - PI/2.0) + 1)/2.0;
    thetad =  VO_TRAJ*RT_TRAJ/2.0 + VO_TRAJ*(CT_TRAJ) + VO_TRAJ*(-(RT_TRAJ/PI)*cos((CT_TRAJ+RT_TRAJ-t)*PI/RT_TRAJ - PI/2.0) +
							      t-(RT_TRAJ+CT_TRAJ))/2.0;
    alphad = VO_TRAJ*(-PI/RT_TRAJ)*cos((CT_TRAJ+2*RT_TRAJ-t)*PI/RT_TRAJ - PI/2.0)/2.0;
    betad = VO_TRAJ*(PI/RT_TRAJ)*(-PI/RT_TRAJ)*sin((CT_TRAJ+2*RT_TRAJ-t)*PI/RT_TRAJ - PI/2.0)/2.0;

  }
  else{
    omegad = 0;
    thetad = VO_TRAJ*RT_TRAJ + VO_TRAJ*(CT_TRAJ);
    alphad = 0;
    betad = VO_TRAJ*(PI/RT_TRAJ)*(-PI/RT_TRAJ)*(-1.0/2.0);
    
  }

  //!!!!!!!!!!!!!!!!!!!!! NOTE !!!!!!!!!!!!!!!!!!!!!!!!1

  //"betad" being discontinuous causes small trajectory generation.

  betad = 0;

  //This is why exponential based ramping is ideal (no discontinuities at higher differencials)
  //Interesting howerver, if we force to "0", we can get a pretty good representation without generating
  //a "bump" on vdq.

  //In any event, this enforces the idea that the trajectory should be generated with using exponential ramping.

  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

#endif





  //generate the commands "vdd" and "vqd"


  idd = - ((Lm + M)*K*(3.0/2.0)*Nr*omegad*omegad) / (R*R + (Lm + M)*(Lm + M)*Nr*Nr*omegad*omegad);
  iqd = (Jm*alphad  + Bm*omegad + Cm*sgn(omegad) + Dm*sin(2*Nr*thetad)) / K;
  didd = - (2*K*(3.0/2.0)*(Lm + M)*R*R*Nr*omegad*alphad) / (R*R + (Lm + M)*(Lm + M)*Nr*Nr*omegad*omegad);
  diqd = (Jm*betad  + Bm*alphad  + Cm*impulse(sgn(omegad)) + Dm*2*Nr*cos(2*Nr*thetad)) / K;


  vdd = (Lm + M)*didd + R*idd - Nr*omegad*(Lm + M)*iqd;
                           //Like above, note the "3/2" scale factor on "K" below.
  vqd = (Lm + M)*diqd + R*iqd + Nr*omegad*(Lm + M)*idd + K*(3.0/2.0)*omegad;

  //For the full state feedback controller, we will integrate "thedad"

  zetad = zetad + thetad*(QUANTUM_PERIOD  * (double) REF_GEN_QUANTUM_CNT);

}

void RefGen::RecordProbes(void)
{
#ifdef RECORD_ALL_PROBES
  beta_d.push_back(betad);
  alpha_d.push_back(alphad);
#endif
  omega_d.push_back(omegad);
#ifdef RECORD_ALL_PROBES
  theta_d.push_back(thetad);
  zeta_d.push_back(zetad);
  id_d.push_back(idd);
  iq_d.push_back(iqd);
  did_d.push_back(didd);
  diq_d.push_back(diqd);
#endif
  vd_d.push_back(vdd);
  vq_d.push_back(vqd);

}


void RefGen::PlotProbes(Gnuplot & SimuPlot, vector<double> & Plot_t, string TagNamesToPlot[])
{

  int i;
  if(TagNamesToPlot[0] == ""){
    SimuPlot.plot_xy(Plot_t, beta_d, "betad");
    SimuPlot.plot_xy(Plot_t, alpha_d, "alphad");
    SimuPlot.plot_xy(Plot_t, omega_d, "omegad");
    SimuPlot.plot_xy(Plot_t, theta_d, "thetad");
    SimuPlot.plot_xy(Plot_t, zeta_d, "zetad");
    SimuPlot.plot_xy(Plot_t, id_d, "idd");
    SimuPlot.plot_xy(Plot_t, iq_d, "iqd");
    SimuPlot.plot_xy(Plot_t, did_d, "didd");
    SimuPlot.plot_xy(Plot_t, diq_d, "diqd");
    SimuPlot.plot_xy(Plot_t, vd_d, "vdd");
    SimuPlot.plot_xy(Plot_t, vq_d, "vqd");
  }
  else{
    for(i = 0; i < 20; i++){
      if(TagNamesToPlot[i] == "betad"){
	SimuPlot.plot_xy(Plot_t, beta_d, "betad");
      }
      else if(TagNamesToPlot[i] == "alphad"){
	SimuPlot.plot_xy(Plot_t, alpha_d, "alphad");
      }
      else if(TagNamesToPlot[i] == "omegad"){
	SimuPlot.plot_xy(Plot_t, omega_d, "omegad");
      }
      else if(TagNamesToPlot[i] == "thetad"){
	SimuPlot.plot_xy(Plot_t, theta_d, "thetad");
      }
      else if(TagNamesToPlot[i] == "zetad"){
	SimuPlot.plot_xy(Plot_t, zeta_d, "zetad");
      }
      else if(TagNamesToPlot[i] == "idd"){
	SimuPlot.plot_xy(Plot_t, id_d, "idd");
      }
      else if(TagNamesToPlot[i] == "iqd"){
	SimuPlot.plot_xy(Plot_t, iq_d, "iqd");
      }
      else if(TagNamesToPlot[i] == "didd"){
	SimuPlot.plot_xy(Plot_t, did_d, "didd");
      }
      else if(TagNamesToPlot[i] == "diqd"){
	SimuPlot.plot_xy(Plot_t, diq_d, "diqd");
      }
      else if(TagNamesToPlot[i] == "vdd"){
	SimuPlot.plot_xy(Plot_t, vd_d, "vdd");
      }
      else if(TagNamesToPlot[i] == "vqd"){
	SimuPlot.plot_xy(Plot_t, vq_d, "vqd");
      }
    }
  }


}

void RefGen::CtrlRValueUpdate(void)
{
  CtrlObjItem * pCurCtrlItem;

  //Update Rvalues
  pCurCtrlItem = pCtrlObjRValList;

  ((VDqCmd *) pCurCtrlItem->pCtrlObject)->vdd = vdd;
  pCurCtrlItem = pCurCtrlItem->pNextCtrlItem;
  ((VDqCmd *) pCurCtrlItem->pCtrlObject)->vqd = vqd;

  //!!!!!!!!!!!!!!!
  //
  //   Here is where we write the following R-values to "FSFCtrl" below
  //
  //   vdd, vqd, idd, iqd, omegad, thetad, zetad
  //
  //
  //
  //!!!!!!!!!!




}





double RefGen::sgn(double omegad)
{
  //code needs to be written here...
  return 0;
}

double RefGen::impulse(double sgn_omegad)
{

  //code needs to be written here...

  return 0;
}





// ---------------------------------------------------------------




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


  


// **** SimuObject ************************************************




SimuObject Simulation;

SimuObject::SimuObject(void)
{
  OdeObjItem * pCurOdeItem;
  SrcObjItem * pCurSrcItem;
  CtrlObjItem * pCurCtrlItem;
  CtrlObjGroup * pCurCtrlGroup; 
  int i;


  SimuTime = 1.0;        
  
  MinimumPlotTime = 0;
  MaximumPlotTime = 1;



  ExceptionTime = .05;

  //For this example the setting of "RelTol" is important. If it is set to large
  //the system will become unstable. 
  RelTol =  .0000000001;
  //Setting "AbsTol" too small will make a system with a decaying oscillation 
  //take too long to finish.
  AbsTol =  .0000000000001; 
  //typical error correction setting as per "RungeKutta_java.htm" (never set higher then "1.0")
  Safety = .98;
  h_start = .000000001; 

  h = h_start;

  //set to a value other then "0" to clamp maximum "h";
  h_max = .0000002;

  //set to store and plot "h" parameter.
  Do_h_Plot = 1;
  
  TimeQuantum = h;
  CtrlTimeQuantum = QUANTUM_PERIOD;

  //set tp force CTRL update on first ODE update.
  CtrlTimeAccumulator = 0;

  SrcPeriodQuantum = QUANTUM_PERIOD;
  SrcPeriodAccumulator = 0;
 

  //build the SRC equation list
  pSrcEquationList = new SrcObjItem;
  pCurSrcItem = pSrcEquationList;
  i = 0;
  while(SrcObjectList[i]){
    pCurSrcItem->pSrcObject = SrcObjectList[i];
    i++;
    if(!SrcObjectList[i])
      break;
    pCurSrcItem->pNextSrcItem = new SrcObjItem;
    pCurSrcItem = pCurSrcItem->pNextSrcItem;


  }

  //build the ODE equation list.
  pOdeEquationList = new OdeObjItem;
  pCurOdeItem = pOdeEquationList;
  i = 0;
  while(1){
    pCurOdeItem->pOdeObject = OdeObjectList[i];
    i++;
    if(!OdeObjectList[i])
      break;
    pCurOdeItem->pNextOdeItem = new OdeObjItem;
    pCurOdeItem = pCurOdeItem->pNextOdeItem;
  }

  //build the CTRL equation lists.

  //(NOTE: As of 6/12/08, "pTranslationList" and "pTrajectoryList" CTRL's have been 
  //       deprecated and replaced with a "group" structure.)

  pCtrlGroupList = new CtrlObjGroup;
  pCurCtrlGroup = pCtrlGroupList;

  pCurCtrlGroup->pCtrlEquationList = new CtrlObjItem;
  pCurCtrlItem = pCurCtrlGroup->pCtrlEquationList;
  //set tp force CTRL update on first ODE update.
  pCurCtrlGroup->QuantumCount = 1;
  pCurCtrlGroup->QuantumNum = CtrlObjectQuantum[0];

  i = 0;
  while(1){
    pCurCtrlItem->pCtrlObject = CtrlObjectList[i];   
    i++;
    if(!CtrlObjectList[i])                 
      break;

    if(CtrlObjectQuantum[i] == CtrlObjectQuantum[i-1]){
      pCurCtrlItem->pNextCtrlItem = new CtrlObjItem;
      pCurCtrlItem = pCurCtrlItem->pNextCtrlItem;
    }
    else{
      //create a new group...
      pCtrlGroupList->pNextCtrlGroup = new CtrlObjGroup;
      pCurCtrlGroup = pCtrlGroupList->pNextCtrlGroup;

      pCurCtrlGroup->pCtrlEquationList = new CtrlObjItem;
      pCurCtrlItem = pCurCtrlGroup->pCtrlEquationList;
      //set tp force CTRL update on first ODE update.
      pCurCtrlGroup->QuantumCount = 1;
      pCurCtrlGroup->QuantumNum = CtrlObjectQuantum[i];  
    }
  }



 

}


SimuObject::~SimuObject(void)
{

  //(ideally we should delete all make allocation make in the constructor, here)

}



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





bool ExecuteSimulation(void)
{

   

  Simulation.OdeSimuType = ODE_SIMU_56;

  while(Simulation.t < Simulation.SimuTime){               

    if(!Simulation.DoOneInteration())
      return FALSE;
    
  }
  if(Simulation.GotException){
    cout << Simulation.ExceptionMessageBuffer.str().c_str();
  }

  return TRUE;
}

void PlotResults(string TagNamesToPlot[], double ScaleFactors[], double MinPlotTimes[], double MaxPlotTimes[], 
		 double PlotTimeSteps[], double PlotTimeOffset)
{
  Simulation.PlotSimuResults(TagNamesToPlot, ScaleFactors, MinPlotTimes, MaxPlotTimes, PlotTimeSteps, PlotTimeOffset);


}
