public static final Instances stratify(Instances data, int folds, Random rand){
    if(!data.classAttribute().isNominal())
      return data;
	
    Instances result = new Instances(data, 0);
    Instances[] bagsByClasses = new Instances[data.numClasses()];
	
    for(int i=0; i < bagsByClasses.length; i++)
      bagsByClasses[i] = new Instances(data, 0);
	
    // Sort by class	
    for(int j=0; j < data.numInstances(); j++){
      Instance datum = data.instance(j);
      bagsByClasses[(int)datum.classValue()].add(datum);
    }
	
    // Randomize each class
    for(int j=0; j < bagsByClasses.length; j++)
      bagsByClasses[j].randomize(rand);
	
    for(int k=0; k < folds; k++){
      int offset = k, bag = 0;
    oneFold:
      while (true){	
	while(offset >= bagsByClasses[bag].numInstances()){
	  offset -= bagsByClasses[bag].numInstances();
	  if (++bag >= bagsByClasses.length)// Next bag
	    break oneFold;      	   
	}	
	    
	result.add(bagsByClasses[bag].instance(offset));
	offset += folds;				
      }
    }
	
    return result;
  }