function [leftD, leftL, rightD, rightL, leftInd, rightInd] = ...
        splitLabeledDataTruncDistrib(D, L, ratio)
% Splits a labeled data set into two parts, making an even class
% distribution on the left split (intended to be your training set) by 
% truncating to ratio times the smallest class size.
%
% Input:
%
%   D - Vectors as a column array
%   L - Class labels as integers
%   ratio - how big portion of the data will be in the left returns (0-1) 
%
% Return:
%
%   leftD    - floor(ratio * NumInSmallestClass) leftmost columns of each class;
%              vectors are lumped to consecutive indices according to class
%              labels; original order is preserved within each class but
%              not overall
%   leftL    - Labels of the vectors in leftD
%   rightD   - the rest of columns from D
%   rightL   - the rest of labels from L
%   leftInd  - the original column indices that ended up in left splits
%   rightInd - the original indices that ended up in right splits
%

if size(D,2) ~= size(L,2)
    error('splitLabeledDataWDistrib must have a label for each data vector');
end;


for iC=1:max(L)
    inds{iC} = find(L == iC);
    nsamp(iC) = numel(inds{iC});
end

minNsamp = min(nsamp);
nLeft = floor(ratio*minNsamp);

leftInd  = [];
rightInd  = [];

for iC=1:max(L)
    leftInd  = [leftInd inds{iC}(1:nLeft)];
    rightInd = [rightInd inds{iC}(nLeft+1:end)];
end

leftD = D(:,leftInd);
leftL = L(:,leftInd);

rightD = D(:,rightInd);
rightL = L(:,rightInd);
