function U = unstack(values,types)
% unstack  Convert a pair of vector of values and types to a multicolumn matrix
%
% Synopsis: U = unstack(values,types)
%
% Input: D = two-column matrix where the first column is data and the
%            second column is an integer indicating the type
%
% Output: U = matrix where the values in each column are from the D
%             matrix and each column has the same type as indicated
%             by the second column in D
%             
% NOTE:  This is a simplistic un-stacking code and only works if there are
%        equal numbers of each type of data in the second column of D
%
% Example:  Given
%              values = [0.1; 0.2; 0.3; 0.4; 0.5; 0.6; 0.7; 0.8; 0.9];
%              types  = [ 1;   1;   1;   2;   2;   2;   3;   3;   3];
%           Then
%              U = unstack(values,types)
%           Creates
%              U = [0.1 0.4 0.7; 0.2 0.5 0.8; 0.3 0.6 0.9];

if length(values) ~= length(types)
  error('UNSTACK:lengthMismatch',...
        'length(values) = %d must equal length(types) = %d',...
        length(values),length(types));
end

% --- Find the list of unique types, which equals the number of columns in the
%     unstacked data set.
u = unique(types);   nu = length(u);
m = length(values);
mu = m/nu;
if rem(m,nu) ~= 0
  error('UNSTACK:shape',...
        'length(values) = %d does not allow reshaping as matrix with %d columns',...
        length(values),nu);
end
U = zeros(mu,nu);
for j=1:nu
  k = find( types == u(j) );
  if length(k) ~= mu
    error('UNSTACK:col_length',...
          'Data for column %d is not correct length: length(k), mu = %d, %d',...
          length(k),mu);
  end
  U(:,j) = values(k);
end