def read_folds(fname):
    """ Reads a list of fold index lists.
    
    Format: let the training set indices range from 0... n_samples-1. Each line
    in a fold file should contain a subset of these indices corresponding to a
    single fold. For example, let n_samples = 11, then:
    
    0 3 4 8
    1 5 9 10
    2 6 7
    
    would correspond to a fold-file with three folds, with first and second fold
    containing 4, and last one 3 instances. The reader would return the list
    
    [[0,3,4,8],[1,5,9,10],[2,6,7]]
    
    Parameters
    ----------
    fname : string
        input file name
        
    Returns
    -------
    folds : a list of lists, each containing the indices corresponding to a single fold
    """
    f = open(fname)
    folds = []
    for i, line in enumerate(f):
        #We allow comments starting with #
        cstart = line.find("#")
        if cstart != -1:
            line = line[:cstart]
        fold = []
        foldset = set([])
        line = line.strip().split()
        for x in line:
            try:
                index = int(x)
            except ValueError:
                raise Exception("Error when reading in fold file: malformed index on line %d in the fold file: %s" % (i + 1, x))
            if index < 0:
                raise Exception("Error when reading in fold file: negative index on line %d in the fold file: %d" % (i + 1, index))
            if index in foldset:
                raise Exception("Error when reading in fold file: duplicate index on line %d in the fold file: %d" % (i + 1, index + 1))
            fold.append(index)
            foldset.add(index)
        folds.append(fold)
    f.close()
    return folds