#!/usr/bin/python

## GPL by Peter Bengtsson, www.peterbe.com
## April 2005

__version__='1.2'

import sys, re

def string_center(s, width, padding):
    # only python2.4 has 'hej'.center(80, '+')
    # python2.3 can only do 'hej'.center(80)
    try:
	return s.center(width, padding)
    except TypeError:
	pad_space = (width - len(s)) / 2
	return padding * pad_space + s + padding * pad_space

semicompiled_regex = re.compile("\.(py|cpy|vpy)c", re.I)
semicompiled = lambda line: semicompiled_regex.findall(line)

backupfile_regex = re.compile("\.\w+~|\.bak:", re.I)
backupfile = lambda line: backupfile_regex.findall(line)

result = sys.stdin.read()

LINES_EITHER_SIDE = 3

try:
    arged_lines_either_side = int(sys.argv[1])
    assert arged_lines_either_side >0
    LINES_EITHER_SIDE = arged_lines_either_side
except IndexError:
    pass
except:
    print >>sys.stderr, "First argument must be a positive integer"

previous_filename = None    
for line in result.splitlines():
    if semicompiled(line):
	continue
    if backupfile(line):
	continue
    if line.startswith('Binary file'):
	continue
    _either_side = LINES_EITHER_SIDE + 1
    try:
	file, lineno = line.split(':')[:2]
    except:
	print line
	continue
    lineno = int(lineno)
    if previous_filename == file:
	print ""
    else:
	print string_center(" %s " % file, 80, '-')
    previous_filename = file
    content = open(file).read().splitlines()
    for i in range(max(lineno-_either_side,0)+1,
                   min(lineno+_either_side, len(content)-1),
	           1):
#	print i, lineno
	star = " "
	if i == lineno:
	    star = "*"
	
	print "%s%s| %s" % (i, star, content[i-1])

