#!/usr/bin/python
import os, sys

try:
    folder = sys.argv[1]
    assert os.path.isdir(folder), "%r does not exist"%folder
    if folder.endswith('/'):
	folder = folder[:-1]
    
except IndexError:
    file_end = str(__file__).split('/')[-1]
    print "Usage: $ python %s <folder with .py files>"%file_end
    sys.exit(1)


cmd =  "grep -rn 'print ' %s/ "%folder
cmd += "| grep -vi utils"
cmd += "| grep '\.py:' "
cmd += "| grep -v 'pprint '"
    

lines_of_code = {}    


def processLine(line):
    try:
	path, lineno, code = line.split(':', 2)
    except:
	print "__________________________________"
	print line
	print "__________________________________"
    if not lines_of_code.has_key(path):
	lines_of_code[path] = open(path).read().splitlines()

    the_line = lines_of_code[path][int(lineno)-1]
	
    if the_line.find('#')>-1 and the_line.find('#') < the_line.find('print'):
	return

    print "-"*4+ " "+ path + ":%s "%lineno+"-"*(40-len(path))
    for delta in (-2, -1,0,1,2):
	try:
	    print lines_of_code[path][int(lineno)+delta]
	except IndexError:
	    pass

    print ""


for line in os.popen4(cmd)[1].read().splitlines():
    processLine(line)#; print "-"*46
    
