function split(filename,times,size,bin)

%split filename into training/test
%times - partition times
%size - size of training data
%bin - number of ordinal scales

%using equal-frequency binning to map R to ordinal scale

if nargin < 3
    disp('') ;
    error(sprintf('\nsplit filename into training/test\ntimes - partition times\nsize - size of training data\nbin - number of ordinal scales')) ;    
end

data = load(filename) ;
[n,m] = size(data) ;
d = m-1 ;

disp(sprintf('%d samples with %d features',n,d)) ;

if (size>n)
    error(sprintf('%d greater the sample size %d.',size,n)) ;
end
if (bin<2)
    bin = 2 ;
end
if (times<1)
    times = 1 ;
end

target = data(:,m) ;
[ordinal,seq] = sort(target) ;
data = data(seq,:) ;

md = mean(data) 
sd = std(data) 

folds=ones(bin,1)*floor(n/bin) ;
temp=sum(folds) ;
for i=temp+1:n 
    folds(i-temp)=folds(i-temp)+1 ;
end
folds
if (sum(folds)~=n)
    error('fold error') ;
end
interval=zeros(bin+1,1) ;
for i=1:bin
    interval(i+1)=sum(folds(1:i));
end
for i=1:bin
    for k=interval(i)+1:interval(i+1)
        ordinal(k)=i;
    end
end


fid = fopen(sprintf('%s.ord',filename),'w+t') ;
for j=1:n
    for k=1:d
        fprintf(fid,'%.5f ',(data(j,k)-md(k))/sd(k)) ;
    end
    fprintf(fid,'%d\n',ordinal(j)) ;
end
fclose(fid) ;


cnts = zeros(bin,1) ;
for i=1:bin
    cnts(i) = sum(ordinal==i) ;
end
if (sum(cnts)~=n|sum(cnts<2))
    error('blank scale.') ;
end

% split times
rand('state',2005) ;
subset = floor(size/bin)*ones(bin,1) ;
temp = sum(subset) ;
for i=temp+1:size 
    subset(i-temp)=subset(i-temp)+1 ;
end
temp = sum(subset) ;

if (temp~=size)
    error('overflow samples.') ;
end
if (sum(subset)~=size|sum(subset<2)>0)
    error('sum of selected samples.') ;
end
disp(subset') ;
sum(subset)
temp = subset ;


for i = 1:times    
    disp(sprintf('generate partitioning %d...',i)) ;
    index = zeros(n,1) ;
    subset = temp ;
    while (sum(subset)>0)        
      rd = ceil(rand(1)*n) ;
      if (subset(ordinal(rd))>0&index(rd)==0)
          subset(ordinal(rd)) = subset(ordinal(rd)) - 1 ;
          index(rd) = 1 ;
      end
    end
    sum(index)
    % generate files
    fid1 = fopen(sprintf('%s_train_%d.%d',filename,bin,i),'w+t') ;
    fid2 = fopen(sprintf('%s_test_%d.%d',filename,bin,i),'w+t') ;
    for j=1:n
        if (index(j)>0)
            %training
            for k=1:d
                fprintf(fid1,'%.5f ',(data(j,k)-md(k))/sd(k)) ;
            end
            fprintf(fid1,'%d\n',ordinal(j)) ;            
        else
            %test
            for k=1:d
                fprintf(fid2,'%.5f ',(data(j,k)-md(k))/sd(k)) ;
            end
            fprintf(fid2,'%d\n',ordinal(j)) ;     
        end
    end
    fclose(fid1) ;    
    fclose(fid2) ;
end

