% function [T Ti x X]=LoadWithLinearPoseEstimation(str,n,DO_OPT)
% str - string form variable data
% n - number of transformations to load
% DO_OPT - if is do use optimization or not

function [T Ti Xout K projERR ]=LoadWithLinearPoseEstimation(str,n)

DATA=load(str,'x_*','X_*','active_images','ind_active','fc','cc','kc','alpha_c');
NT=numel([DATA.active_images]);
N=min(numel([DATA.ind_active]),n);
T=zeros(4,4,N);
Ti=zeros(4,4,N);
Xout(N)=struct();
projERR(N)=struct();
K.fc=DATA.fc;K.cc=DATA.cc;K.kc=DATA.kc;K.alpha=DATA.alpha_c;
kk=[DATA.fc(1) 0 DATA.cc(1);0 DATA.fc(2) DATA.cc(2);0 0 1];

j=1;
for i=1:NT
 if DATA.active_images(i)
  eval(['Xout(j).sizePoints=size(DATA.x_' num2str(i) ',2);']);
  eval(['Xout(j).x_px=DATA.x_' num2str(i) ';']);
  x=[Xout(j).x_px;ones(1,Xout(j).sizePoints)];
  eval(['Xout(j).X=DATA.X_' num2str(i) ';']);
  X=[Xout(j).X(1:2,:);ones(1,Xout(j).sizePoints)];
  x=kk\x;
  for k=1:Xout(j).sizePoints
   r2=sum(x(1:2,k).^2);
   a=1+r2*DATA.kc(1)+r2.^2*DATA.kc(2)+r2.^3*DATA.kc(5);
   d=[2*DATA.kc(3)*x(1,k)*x(2,k)+DATA.kc(4)*(r2+2*x(1,k).^2);DATA.kc(3)*(r2+2*x(2,k).^2)+2*DATA.kc(4)*x(1,k)*x(2,k)];
   x(:,k)=[a 0 d(1);0 a d(2);0 0 1]\x(:,k);
  end
  [T(:,:,j) diff]=GetPlanePose(X,x);
  Ti(:,:,j)=T(:,:,j)/T(:,:,1);
  projERR(j).err=ProjectPoints(Xout(j).X,T(:,:,j),DATA.fc,DATA.cc,DATA.kc,DATA.alpha_c)-Xout(j).x_px;
  projERR(j).derr=sqrt(sum([projERR(j).err].^2));
  j=j+1;
  if j>N
   break;
  end
 end
end
  