// StarDelta.c: Implementation of StarDelta module

#include <math.h>
#include <stdio.h>
#include "StarDelta.h"


// data (members)

PRIVATE double dR1, dR2, dR3;
PRIVATE double dRa, dRb, dRc;

// Set and Get functions

void SetStarValues(double dR1New, double dR2New, double dR3New)
{ 
  dR1 = dR1New;
  dR2 = dR2New;
  dR3 = dR3New;
}


void SetDeltaValues(double dRaNew, double dRbNew, double dRcNew)
{
  dRa = dRaNew;
  dRb = dRbNew;
  dRc = dRcNew;
}


// Star to Delta conversation

void StarToDelta()
{
  dRa = (dR1*dR2 + dR2*dR3 + dR3*dR1) / dR3;
  dRb = (dR2*dR3 + dR3*dR1 + dR1*dR2) / dR1;
  dRc = (dR3*dR1 + dR1*dR2 + dR2*dR3) / dR2;
}

void DeltaToStar()
{
  dR1 = dRa*dRc / ( dRa + dRb + dRc );
  dR2 = dRb*dRa / ( dRa + dRb + dRc );
  dR3 = dRc*dRb / ( dRa + dRb + dRc );
}

void ShowValues()
{
    printf("Star - circuit          Delta - circuit\n");
    printf("--------------------------------------------------\n");
    printf("R1  = %8.2g Ohm      Ra  = %8.2g Ohm\n", dR1, dRa);
    printf("R2  = %8.2g Ohm      Rb  = %8.2g Ohm\n", dR2, dRb);
    printf("R3  = %8.2g Ohm      Rc  = %8.2g Ohm\n", dR3, dRc);
    printf("--------------------------------------------------\n");
    printf("R12 = %8.2g Ohm      R12 = %8.2g Ohm\n", RStar(1,2), RDelta(1,2));
    printf("R23 = %8.2g Ohm      R23 = %8.2g Ohm\n", RStar(2,3), RDelta(2,3));
    printf("R31 = %8.2g Ohm      R31 = %8.2g Ohm\n", RStar(3,1), RDelta(3,1));
    printf("\n\n");
}


PRIVATE double RStar(int nT1, int nT2)
{
  if ( (nT1 == 1 && nT2 == 2) || (nT1 == 2 && nT2 == 1) ) 
    return dR1 + dR2;
  if ( (nT1 == 2 && nT2 == 3) || (nT1 == 3 && nT2 == 2) ) 
    return dR2 + dR3;
  if ( (nT1 == 3 && nT2 == 1) || (nT1 == 1 && nT2 == 3) ) 
    return dR3 + dR1;

  printf("Error in function RStar: illegal terminal numbers!\n");
  return 0.0;
}


PRIVATE double RDelta(int nT1, int nT2)
{
  if ( (nT1 == 1 && nT2 == 2) || (nT1 == 2 && nT2 == 1) ) 
    return dRa * (dRb + dRc) / (dRa + dRb + dRc);
  if ( (nT1 == 2 && nT2 == 3) || (nT1 == 3 && nT2 == 2) ) 
    return dRb * (dRc + dRa) / (dRa + dRb + dRc);
  if ( (nT1 == 3 && nT2 == 1) || (nT1 == 1 && nT2 == 3) ) 
    return dRc * (dRa + dRb) / (dRa + dRb + dRc);

  printf("Error in function RDelta: illegal terminal numbers!\n");
  return 0.0;
}