#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os

def get_max_col(dirname):
	with open( os.path.join(dirname, 'matrix_crs.mat'), 'r') as f:
		line = f.readline()
		tokens = line.strip().split()
		return int(tokens[1])

def load_boundaries(dirname):
	bounds = {}
	for line in open( os.path.join(dirname, 'boundary.txt'), 'r'):
		line = line.strip()
		if len(line):
			tokens = line.split(':=')
			bounds[ int(tokens[1].strip()) ] = tokens[0].strip()
	return bounds

def get_max_boundary(bounds):
	m = -1
	for val in bounds:
		if val > m:
			m = val
	return m

def write_plus(dirname,  bounds):
	print "+1 for", dirname
	with open( os.path.join(dirname, 'boundary.txt'), 'w') as f:
		for op in bounds:
			line = "%s := %d\n" % (bounds[op], op+1)
			f.write(line)

def write_plus_correct_max(dirname,  bounds, max_col):
	print "+1 for", dirname
	with open( os.path.join(dirname, 'boundary.txt'), 'w') as f:
		for op in bounds:
			if op > max_col:
				line = "%s := %d\n" % (bounds[op], max_col)
				print "Corrcting %s: %d -> %d " % (bounds[op], op, max_col)
			else:
				line = "%s := %d\n" % (bounds[op], op+1)	
			f.write(line)
		
def process_one(dirname):
	max_col = get_max_col(dirname)
	bounds = load_boundaries(dirname)
	max_bound = get_max_boundary(bounds)

	if max_bound > max_col:
		print "Maximum boundary is grater then number of columns in", dirname
		write_plus_correct_max(dirname, bounds, max_col)
	elif max_bound != max_col:
		write_plus(dirname, bounds)
	else:
		print "No need to change in", dirname


def main():
	path = sys.argv[1]
	all_paths = sorted([(r,d,f) for (r,d,f) in list(os.walk(path)) if len(f) and 'boundary.txt' in f] )
	for p in all_paths:
		root, dirs, files = p 
		process_one(root)

if __name__  == '__main__':
	main()
