function residuo = optfunc_RecPlane_withRot(x)


global X_g store_x fc1 cc1 kc1 alpha_c1 % RRparm

t_realPlane = x(1:3);
R_realPlane = rodrigues(x(4:6));


n=size(x(7:end),1)/6;


aux=reshape(x(7:end),3,2*n);
t_virtualPlane=aux(:,1:n);
R_virtualPlane_parmRod=aux(:,n+1:end);

X=[X_g;ones(1,size(X_g,2))];

K = [fc1(1) alpha_c1 cc1(1);
    0      fc1(2)   cc1(2);
    0       0       1];


residuo=[];
residuo_eq=[];

for ii=1:n
    

    
    % R'*[n_c/norm(n_c)]
	n_P=R_realPlane'*[(t_virtualPlane(:,ii)-t_realPlane)/norm( t_virtualPlane(:,ii)-t_realPlane )];
    % 1/2*n_c*[n_c/norm(n_c)]
    d_P=1/2*(t_virtualPlane(:,ii)-t_realPlane)'*[(t_virtualPlane(:,ii)-t_realPlane)/norm( t_virtualPlane(:,ii)-t_realPlane )];

    X_virtualPlane=[eye(3) [0;0;0]]*[eye(3)-2*n_P*n_P' 2*n_P*d_P;0 0 0 1]*X;
    
    x_r=project_points2(X_virtualPlane,rodrigues(R_realPlane),t_realPlane,fc1,cc1,kc1,alpha_c1);
 
    
%     err_proj(:,:,ii)=store_x(:,:,ii)-x_p(1:2,:);
    err_proj(:,:,ii)=store_x(:,:,ii)-x_r;
    
    
    residuo=[residuo ; reshape(err_proj(:,:,ii), 2*size(err_proj(:,:,ii),2),1)];

    
    % resolve (R+R')' * (C-C')
    
    R_virtualPlane=rodrigues(R_virtualPlane_parmRod(:,ii))*[1 0 0;0 1 0;0 0 -1];
    tempR=[R_realPlane+R_virtualPlane]';
    tempt=[t_virtualPlane(:,ii)-t_realPlane];
    
    residuo_eq=[residuo_eq; tempR*tempt ];

end



residuo=[residuo;residuo_eq];





%     % mirror plane pose ( n and d) - referenced in camera {C}
% 
%     n_C=(t_virtualPlane(:,ii)-t_realPlane)/norm( t_virtualPlane(:,ii)-t_realPlane );
%     d_C=1/2*n_C'*(t_realPlane+t_virtualPlane(:,ii));
%     
%     
%     Sim_C=[eye(3)-2*n_C*n_C' 2*n_C*d_C ; 0 0 0 1];
%     
%     % ------------------------------
%     % projection algorithm
%    
%     X_c=[eye(3) [0;0;0]]*Sim_C*[ R_realPlane t_realPlane ; 0 0 0 1]*X;
%    
%     x_n=X_c(1:2,:)./[X_c(3,:) ; X_c(3,:) ];
%     
%     r=sum(x_n.^2);
%     
%     dx=[ 2*kc1(3).*x_n(1,:).*x_n(2,:)+kc1(4)*(r+2*x_n(1,:).^2)
%         kc1(3)*(r+2*x_n(2,:).^2)+2*kc1(4).*x_n(1,:).*x_n(2,:) ];
%     
%     x_d=[(ones(size(r))+kc1(1)*r+kc1(2)*r.^2+kc1(5)*r.^3).*x_n(1,:)+dx(1,:)
%         (ones(size(r))+kc1(1)*r+kc1(2)*r.^2+kc1(5)*r.^3).*x_n(2,:)+dx(2,:) ];
%     
%     x_p=K*[x_d;ones(1,size(x_d,2))];

