#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "machdefs.h"
#include "fmath.h"

#include "transfost.h"

/* Nouvelle-Fonction */
void PrintTransfo(TRANSFO *tr)

/*  Impression des coefficients du 1er ordre  */
{
int k;
char sg[3],sgp[3],*st[2];

strcpy(sg,"XY"); strcpy(sgp,"xy");
st[0] = "Source";  st[1] = "Dest";

printf("PrintTransfo:  Degre = %d (Coeff d'ordre 1) \n", tr->DegPolxy); 
for(k=0; k<2; k++)
  printf(" T%c %c = %10.5f  + %10.5f x + %10.5f y \n", sgp[k], sg[k], 
         tr->Polxy[0][0][k], tr->Polxy[1][0][k], tr->Polxy[0][1][k]);

for(k=0; k<2; k++)
  {
  printf("Lim[%6s] MidX,Y= %10g %10g  LargX,Y= %10g %10g\n",
         st[k],tr->midx[k], tr->midy[k], tr->largx[k], tr->largy[k]);
  printf("   XMin,Max= %10g %10g   YMin,Max= %10g %10g \n",
         tr->xmin[k], tr->xmax[k], tr->ymin[k], tr->ymax[k]);
  }

return;
}


/* Nouvelle-Fonction */
void RedCord(double x, double y, double *xr, double *yr, TRANSFO *transf, int i)
{
  *xr = (x - transf->midx[i]) / transf->largx[i];
  *yr = (y - transf->midy[i]) / transf->largy[i];
}


/* Nouvelle-Fonction */
void ExpCord(double xr, double yr, double *x, double *y, TRANSFO *transf, int i)
{
  *x = transf->largx[i] * xr + transf->midx[i];
  *y = transf->largy[i] * yr + transf->midy[i];
}


/* Nouvelle-Fonction */
void CordTransf(double xS, double yS, double *xD, double *yD, TRANSFO *transf)
{
  double xi,yi,xo,yo,xk,yl;
  int k,l;

  RedCord(xS,yS,&xi,&yi,transf,0);
  if (transf->DegPolxy == 1) {
    xo = transf->Polxy[0][0][0] + transf->Polxy[1][0][0]*xi + transf->Polxy[0][1][0]*yi;
    yo = transf->Polxy[0][0][1] + transf->Polxy[1][0][1]*xi + transf->Polxy[0][1][1]*yi;
    }
  else {
    xo = yo = 0.0;
    xk = 1.0;
    for (k = 0; k<=transf->DegPolxy; k++) {
      yl = 1.0;
      for (l = 0; l<=transf->DegPolxy-k; l++) {
        xo += transf->Polxy[k][l][0]*xk*yl;
        yo += transf->Polxy[k][l][1]*xk*yl;
        yl *= yi;
      }
      xk *= xi;
    }
  }
  ExpCord(xo,yo,xD,yD,transf,1);
}


/* Nouvelle-Fonction */
void CordTransfEros2(double xS,double yS,double *xD,double *yD,TRANSFO *transf)
/*
Dans Eros2 les infos concernant les coordonnees reduites sont codees
dans TRANSFO mais la transformation est donnee pour les coordonnees normales
*/
{
  double xk,yl;
  int k,l;

  if (transf->DegPolxy == 1) {
    *xD = transf->Polxy[0][0][0] + transf->Polxy[1][0][0]*xS + transf->Polxy[0][1][0]*yS;
    *yD = transf->Polxy[0][0][1] + transf->Polxy[1][0][1]*xS + transf->Polxy[0][1][1]*yS;
    }
  else {
    *xD = *yD = 0.0;
    xk = 1.0;
    for (k = 0; k<=transf->DegPolxy; k++) {
      yl = 1.0;
      for (l = 0; l<=transf->DegPolxy-k; l++) {
        *xD += transf->Polxy[k][l][0]*xk*yl;
        *yD += transf->Polxy[k][l][1]*xk*yl;
        yl *= yS;
      }
      xk *= xS;
    }
  }
}
