#!/usr/bin/env python
#******************************************************************************\
#* Copyright (C) 2003-2006 Martin Blais <blais@furius.ca>
#*
#* This program is free software; you can redistribute it and/or modify
#* it under the terms of the GNU General Public License as published by
#* the Free Software Foundation; either version 2 of the License, or
#* (at your option) any later version.
#*
#* This program is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with this program; if not, write to the Free Software
#* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#*
#*****************************************************************************/

"""random-subset [<options>] [<file> ...]

Selects a subset of a set of random lines of a set of files.  The files are to
be read are specified on the cmdline, or the lines from stdin if no files are
specified on the cmdline.

See 'rl' for a C program that does something similar to this script:
http://tiefighter.et.tudelft.nl/~arthur/rl/

"""

__version__ = "Revision: 1.11 "
__author__ = "Martin Blais <blais@furius.ca>"

# stdlib imports
import sys, random


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__)

    parser.add_option('-n', '--count', action='store',
                      default=10, type='int',
                      help='Specifies the desired number of lines.')

    parser.add_option('-p', '--prepend', action='store',
                      help="Prepend the given string to the lines")

    opts, args = parser.parse_args()

    if len(args) > 0:
        lines = []
        for fn in args:
            try:
                lines += open(fn, 'r').readlines()
            except IOError, e:
                raise SystemExit("Error: reading file %s" % fn)
    else:
        lines = map(lambda x: x[:-1], sys.stdin.readlines())

    for i in xrange(0, opts.count):
        if len( lines ) == 0:
            break
        r = int(random.random() * len(lines))
        s = lines[r]
        if opts.prepend:
            s = opts.prepend + s
        print s
        del lines[r]

if __name__ == '__main__':
    main()

