function [C iter] = ctm(z, v);
% C = ctmest(z, v) 
% Computes the complex t_v M-estimator of scatter
%
% INPUT:
% z    :  data matrix with n rows (observations) and k columns (variables).
% v    :  used defined interger of the weight function. Default v=1.  
% Output:
% C    :  t_v M-estimator of scatter
% 
% Esa Ollila, esollila@wooster.hut.fi. 

if nargin == 1
   v = 1;
end

[n k] = size(z);
MAX_ITER = 250; % Max number of iteration
EPS = 1.0e-4;   % Iteration accuracy

invC0 = inv(z.'*conj(z)/n); % inverse of the initial estimate 
iter=1;
while (iter<MAX_ITER)
      s = real(sum(conj(z)*invC0.*z,2));
      w = (v+2*k)./(v+2*s);
      C = z.'*(conj(z).*repmat(w,1,k))/n;
      d = norm(eye(k)-invC0*C,1);
      if (d<=EPS) break; end
      invC0 = inv(C);
      iter = iter+1;     
end

C(1:(k+1):k^2) = real(C(1:(k+1):k^2)); 

if (iter==MAX_ITER) 
     fprintf(1,'WARNING! Slow convergence: the error of the solution is %f\n',d);  
     fprintf(1,'after %d iterations\n',iter);
end      
           
   
