function [A ,B, C ,lambda]=getMergeData(old,new,X,fixed,lambda_2)
%Ekta Gujral,Ravdeep Pasricha , Vagelis Papalexakis 2017
%Computer Science and Engineering, University of California, Riverside
%Demonstrating the use of the SambaTen algorithm, using samplaing based
%approach for online tensors
    if(size(new{1},1)==size(old{1},1))
     new{1} = match_and_permute(new{1},old{1},fixed{1}); A=(old{1}+new{1})/2;
    else
        A=new{1};
    end
    if(size(new{2},1)==size(old{2},1))
     new{2} = match_and_permute(new{2},old{2},fixed{2});B=(old{2}+new{2})/2;
    else
     B=new{2};
    end
    if(size(new{3},1)==size(old{3},1))
     new{3} = match_and_permute(new{3},old{3},1:size(old{3},1));
    end
      
      C=[old{3};new{3}];
     [lambda]=getlambdascale(sptensor(X),A,B,C,lambda_2);
end

function A = match_and_permute(As,Ao,shared)
A = As;
F = size(Ao,2);
for i = 1:F
    try
    As(shared,i) = As(shared,i)/norm(As(shared,i));
    Ao(shared,i) = Ao(shared,i)/norm(Ao(shared,i));
    catch
    end
end
idx = [];
for i = 1:F
    c = As(shared,i);%take only the shared rows, and do the matching according to them
    newidxset = setdiff(1:F,idx);
    val = zeros(size(newidxset));
    for j = newidxset
       c2 = Ao(shared,j);
       val(find(j == newidxset)) = norm(c - c2);
    end
    [junk min_idx] = min(val);
    idx(i) = newidxset(min_idx);
end
A = A(:,idx);%permute

end

function [lambda,s]=getlambdascale(X,A,B,C,lambda_all)
    lambda=zeros(size(A,2),1);
    s = scalPoint(X,A*diag(lambda_all),B,C);
    Xinc=ktensor(lambda_all,A,B,C);
    errold=1-(norm(Xinc)/norm(X));
    if(errold<0);errold=9999999;end
    for i=1:2*ndims(X)
       Xinc=ktensor(i*lambda_all*s,A,B,C);
       err=  1-(norm(Xinc)/norm(X));
       if(err<0);errold=9999999;end
       if(err<errold && norm(Xinc)<norm(X))
           lambda=lambda_all*s*i;
       end
    end
   if(sum(abs(lambda)==0))
       lambda=lambda_all;
   end
end

%% I replaced with new code here , this is more algorithmic

function s = scalPoint(X,a,b,c)
 UA = (sptenmat(X,1,'bc')); UA = sparse(UA.subs(:,1), UA.subs(:,2),UA.vals,size(UA,1),size(UA,2));UA = UA';
 A= sparse(krp(b,c)*a');
x = UA(:);
a = A(:);
s = abs(x'*a/(a.'*a));
end
