function [R,CC,prior] = reestimate(D,postprob,option)
% Usage
% [R,CC,prior] = reestimate(D,postprob,option)
%
% input:
%   D(N,M) - data matrix containing N vectors of length M
%   posterprob(N,K) - posterior probabilities for each data vector and
%   option:
%     option ==1 => treat first cluster as centered about 0
%     option ==0 => treat first cluster the same as others
% output:
%   R(K,M,M) - covariance matrix for each of the K clusters
%   CC(M,K) - values for K cluster component vectors, each of length M
%   prior(K) - prior probabilities corresponding to K clustered components


% Determine sizes of arrays
[N,M,S] = size(D);
[N,K] = size(postprob);

% Allocate memory
R = zeros(K,M,M);
CC = zeros(M,K);

% Compute covariance matrix for each class
for k = 1:K
  probk =  postprob(:,k);
  DD = D.*repmat(probk,[1,M]);
  R(k,:,:) = DD'*D;

  [U,S,V] = svd(squeeze(R(k,:,:)));

  % Use principal component, but choose sign using data
  CC(:,k) = U(:,1)*sign( sum( (D*U(:,1)).*probk ) );
end

% if option is 1, zero out first class
if option==1
  CC(:,1) = 0*CC(:,1);
end

% Compute prior probabilities
prior = sum(postprob,1)/N;

