#!/usr/bin/env python
"""
seq - partially compliant Python version of well-known `seq' tool.

Created by Michal Chruszcz <mchruszcz (at) gmail.com>.
Released under public domain licence.
Latest version is available at http://github.com/mchruszcz/misc/blob/master/seq
"""

import sys
from optparse import OptionParser

def seq(stop, start=1, step=1, leading_zeroes=False, separator='\n'):
    """Produces formatted sequence according to the parameters."""
    separator = separator.replace(r'%', r'%%')
    if leading_zeroes:
        width = max(len(str(start)), len(str(stop)))
        chunk = '%%0%dd%s' % (width, separator)
    else:
        chunk = '%%d%s' % separator

    if start <= stop:
        stop += 1
    else:
        stop -= 1
        if step == 1:
            step = -1

    for i in xrange(start, stop, step):
        sys.stdout.write(chunk % i)
    if separator != '\n':
        sys.stdout.write('\n')

def parse_input():
    """Parses seq input and parameters."""
    usage = 'usage: %prog [options]... [FIRST [STEP]] LAST'
    parser = OptionParser(usage)
    parser.add_option('-w', '--equal-width', dest='leading_zeroes', action='store_true',
        default=False, help='insert leading zeroes to output')
    parser.add_option('-s', '--separator', dest='separator', metavar='STRING',
        default='\n', help='separate numbers with STRING; default is a newline')
    opts, args = parser.parse_args()

    if len(args) < 1 or len(args) > 3:
        parser.print_help()
        return 1
    try:
        args = map(int, args)
    except ValueError:
        parser.print_help()
        return 1

    first = step = 1
    try:
        first, step, last = args
    except ValueError:
        try:
            first, last = args
        except ValueError:
            last = args[0]
    seq(last, first, step, opts.leading_zeroes, opts.separator)
    return 0

if __name__ == '__main__':
    sys.exit(parse_input())
