function [leftD, leftL, rightD, rightL, leftInd, rightInd] = ...
        splitLabeledDataWDistrib(D, L, ratio)
% Splits a labeled data set into two parts, keeping original class
% distributions (up to integer truncating error) by making the split 
% to each class separately.
%
% 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 * NumInClassX) 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 because of the lumping.
%   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
%
% TODO: More useful to return only indices? Easy enough for user to
% split using them?


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

leftInd  = [];
rightInd  = [];

for iC=1:max(L)
    inds = find(L == iC);
    nsamp(iC) = numel(inds);
    
    nLeft = floor(ratio*nsamp(iC));
    leftInd  = [leftInd inds(1:nLeft)];
    rightInd = [rightInd inds(nLeft+1:end)];
end

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

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