
function [L,S] = PALM(X,L0,S0,r,sk,tol,iterlimit,opts)

verbose=opts.verbose;
m = size(X,1);
n = size(X,2);
gamma1 = 2;
gamma2 = 2;
L = L0;
S = S0;
A = X;
err1 = 1;
errold = 1;
derr = 1;
k = 0;
startwhiletime=cputime;
retol = opts.palmretol;
while err1 >=tol && k<= iterlimit && derr >=retol
   c =  gamma1;
   U = L - 1/c*(L+S-A);
   %%%%%%%%%%%%
   [mu,~]=size(U);
   if mu>=n,
         [u,s,v] = svd(U,0);
    %uu = u(:,1:r);
    %vv = v(:,1:r);
    %ss = s(1:r,1:r);
    %UU = uu*ss*vv';
          UU =  u(:,1:r)*s(1:r,1:r)*v(:,1:r)';
    %err1 = norm_nuc(UU-U);
          err1 = sum(diag(s))-sum(diag(s(1:r,1:r)));
    else
         [v,s,u] = svd(U',0);
	 s=s';
         UU =  u(:,1:r)*s(1:r,1:r)*v(:,1:r)';
         err1 = sum(diag(s))-sum(diag(s(1:r,1:r)));
    end
    L = UU;
   %%%%%%%%%%%%
   %%%%%%%%%%%%
    d = gamma2;
      V = S - 1/d*(L+S-A);
     [~,ind]= sort(abs(V(:)),'ascend');
     mm =floor(m*n*(1-sk));  % integer for correct sparsity percentage
     indsz = abs(V)<=abs(V(ind(mm)));  % indices to set to zero
     err2 = norm(V(indsz),1);
     S = V;
     S(indsz)=0;
   %%%%%%%%%%%%%%  
      k = k + 1;
     %if mod(k,100) ==0
        derr = abs((err1-errold)/errold);
         errold = err1;
    % fprintf('noiter %i, error rank %14.4g error sparsity  %14.4g  \n',...
     %    k,err1,err2);
    % end

end
  L = X-S;
  if verbose ==1
     fprintf('noiter %i, error rank %14.4g error sparsity  %14.4g  \n',...
         k,err1,err2);
     fprintf('time for iterations/while loop is  %g   \n',cputime-startwhiletime);
  end
   %

end
