function [M2,N2,co,si,xbarref,ybarref,xbardef,ybardef]=transformation_image(xg1,yg1,xd1,yd1,img,imd,nbpoints,correc)
%correction rigide%
%%%%%%%%%%%%%%%%%%%
if correc==1
    disp('correction rigide')
    xbarref = sum(xd1)/nbpoints; % moyenne des valeurs
    ybarref = sum(yd1)/nbpoints;
    xbardef = sum(xg1)/nbpoints; 
    ybardef = sum(yg1)/nbpoints;

    Xcor = xg1-xbardef; %on centre sur 0
    Ycor = yg1-ybardef;
    x2 = xd1-xbarref;
    y2 = yd1-ybarref;

    tantheta = (Ycor'.*x2'-y2'.*Xcor')/(Xcor'.*x2'+Ycor'.*y2');
    t = -atan(tantheta);
    co = cos(t);
    si = sin(t);
    [haut long] = size(img);
    [m n] = meshgrid(1:long,1:haut);

    M2 = (m-xbardef)*co-(n-ybardef)*si+xbarref;
    N2 = (m-xbardef)*si+(n-ybardef)*co+ybarref;
    

    %correction affine%
    %%%%%%%%%%%%%%%%%%%
elseif correc==2
    co = 0; si = 0; xbarref = 0, ybarref = 0, xbardef = 0; ybardef = 0;
    A = [sum(xd1.*xd1) sum(xd1.*yd1) sum(xd1) ;
         sum(yd1.*xd1) sum(yd1.*yd1) sum(yd1) ;
         sum(xd1) sum(yd1) nbpoints];
    B = [sum(xd1.*xg1);
         sum(yd1.*xg1);
         sum(xg1)];
    coeffabc = inv(A)*B;

    C = [sum(xd1.*xd1) sum(xd1.*yd1) sum(xd1) ;
         sum(yd1.*xd1) sum(yd1.*yd1) sum(yd1) ;
         sum(xd1) sum(yd1) nbpoints];
    D = [sum(xd1.*yg1);
         sum(yd1.*yg1);
         sum(yg1)];
    coeffdef = inv(C)*D;
    a = coeffabc(1,1);
    b = coeffabc(2,1);
    c = coeffabc(3,1);
    d = coeffdef(1,1);
    e = coeffdef(2,1);
    f = coeffdef(3,1);
    [haut long] = size(img);
    [m n] = meshgrid(1:long,1:haut);

    M2 = (e*(m-c)-b*(n-f))/(e*a-d*b);
    N2 = (d*(m-c)-a*(n-f))/(d*b-a*e);

    %correction quadratique%
    %%%%%%%%%%%%%%%%%%%%%%%%
else
    if nbpoints<6
        disp('pas assez de points, 6 minimum ')
        correc=2
    end
    co = 0; si = 0; xbarref = 0, ybarref = 0, xbardef = 0; ybardef = 0;
    tata=[ones(size(xg1)) xg1 yg1 xg1.*yg1 xg1.^2 yg1.^2];
    a = tata\xd1;
    b = tata\yd1;
    [haut long] = size(img);
    [m n] = meshgrid(1:long,1:haut);
    M2 = a(1,1)+a(2,1)*m+a(3,1)*n+a(4,1)*m.*n+a(5,1)*m.*m+a(6,1)*n.*n;
    N2 = b(1,1)+b(2,1)*m+b(3,1)*n+b(4,1)*m.*n+b(5,1)*m.*m+b(6,1)*n.*n;
end
