#!/usr/bin/env python
#
#    Copyright (c) 2016 Timothy Savannah All Rights Reserved
#  under terms of the GPL version 2. You should have recieved a copy of this with distribution,
#  as LICENSE. You may also find the full text at https://github.com/kata198/popLines/LICENSE
#

#  This program turns files into queues. You can pop off specific lines to stdout.
#   So your file can contain a list of items to process, and you can use this to pop off that queue.

#vim: set ts=4 sw=4 expandtab
import os
import sys

from PopLines import popThese

def printUsage():
    sys.stderr.write('''Usage: popThese [line number] (next line numer...) [filename]

Removes the given lines (1-origin) from filename, returning on stdout.

You can use negative numbers to mean from-the-end (-1 is last line, -2 is second-to-last)

Example: popThese 1 4 7 myfile.txt > linesOneFourAndSeven.txt
''')

if __name__ == '__main__':

    if '--help' in sys.argv:
        printUsage()
        sys.exit(1)

    args = sys.argv[1:]

    if len(args) < 2:
        sys.stderr.write('Not enough arguments.\n\n')
        printUsage()
        sys.exit(1)

    try:
        numLines = [int(x) for x in args[:-1]]
    except Exception as e:
        sys.stderr.write('Line numbers must be integers.\n\n')
        printUsage()
        sys.exit(1)

    filename = args[-1]
    if not os.path.exists(filename):
        sys.stderr.write('No such file: %s\n' %(filename,))
        sys.exit(2)
    if not os.path.isfile(filename):
        sys.stderr.write('Not a file: %s\n' %(filename,))
        sys.exit(2)

    try:
        output = popThese(numLines, filename)
    except Exception as e:
        sys.stderr.write('Error: %s\n' %(str(e,)))
        sys.exit(2)

    if len(output) > 0:
        sys.stdout.write('\n'.join(output))
        sys.stdout.write('\n')

