#!/usr/bin/python
################################################################
#
#              Renumber Propositions 
#
################################################################
#
import os, re, time
import argparse
from document import build_blocklist
import pattern
#
#
parser = argparse.ArgumentParser()

parser.add_argument("file",
		help = "name of the file with proof(s) to be checked")

parser.add_argument("-f", "--format", type=str,
		help = "numbering format")

parser.add_argument("-m", "--majorunit", type=str,
		help = "latex sectioning level used first in num.num" )

parser.add_argument("-r", "--renumfile", type=str,
		help = "use renum file")

parser.add_argument("-s", "--suffix", type=str,
		help = "use renum file to replace references with given suffix")

parser.add_argument("-z", "--zeroplus", action = "store_true", 
		help = "use renum file to do zero plus replacements")

args = parser.parse_args()

#
if args.file.endswith(".tex"):
	Arg_1 = args.file[:-4]
else:
	Arg_1 = args.file
filename = Arg_1 + ".tex" 
if not os.path.isfile(filename):
	raise SystemExit(filename + ' not found.')


if args.format :
		numformat = args.format 
else:
		numformat = '1.1'

if args.suffix or args.zeroplus:
		if not args.renumfile:
				raise SystemExit("Must specify the '.rnm' file")
		if args.suffix and args.zeroplus:
				raise SystemExit("Can't use zeroplus and suffix both on one renum file")

#
#  Setup up replacement patterns for propositions
#
numdotpat = re.compile("\d+(\.\d+)+")
if numdotpat.match(numformat):
	num_nums = numformat.count(".") + 1
else:
	raise SystemExist(numformat + " is not a valid numeration format")

numrepstr = "\.".join(num_nums * ["\d+"]) 
if args.suffix:
		s = args.suffix
		refpat = re.compile(numrepstr + "(?=" + s + "(?!\w))")
elif args.zeroplus:
		refpat = re.compile("(?<=(?<!\w)0)" + numrepstr)
else:
		refpat = re.compile(numrepstr + "(?!\w)")

onenumpat = re.compile("\+d")   # Used only with plain Tex \chap renumbering

latex_sectionings = ['chapter', 'section', 'subsection', 
											'subsubsection', 'paragraph','subparagraph']
if args.majorunit:
	if args.majorunit in latex_sectionings:
		major_level =  latex_sectionings.index(args.majorunit)
	else:
		raise SystemExit(args.majorunit + " is not a valid LaTeX sectioning unit")
elif os.path.isfile(Arg_1 + ".ldf"):
##########################################################
#
#  Check for Major Unit definition in .ldf file
#
##########################################################
	for r in open(Arg_1 + ".ldf","r"):
		directivem = pattern.directive.match(r)
		if directivem:
			if directivem.group(1)== "major_unit:":
					unit = directivem.group(3)
					if unit not in latex_sectionings:
						print(Arg_1 + ".ldf")
						print("Need one of ", latex_sectionings)
						raise SystemExit(unit + " is not a valid LaTeX sectioning unit")
					else:
						major_level =  latex_sectionings.index(unit)
						break
	else:
		major_level = latex_sectionings.index('section')
else:
	major_level = latex_sectionings.index('section')
	
latex_section = pattern.latex_unit_prefix + "("+ "|".join(latex_sectionings) +\
								")" + pattern.latex_unit_suffix
latex_section_unit = re.compile(latex_section)



##########################################################
#
# Define dictionary using function 
#
def changefun(x):
	y = x.group(0)
	return change_num.get(y,y)

##########################################################
#
# Get reference lists. 
#
##########################################################

f = open(filename,"r")
linelist = f.readlines()
f.close()

change_num = {}
outlist = []
inlist = []
if args.renumfile: 
	try:
		f = open(args.renumfile,"r")
	except:
		raise SystemExit("Can't open renum file: " + args.renumfile)
	lines = f.readlines()
	f.close()
	for x in lines:
		if x[0] == "#":
			pass
		else:
			y = x.split()
			if len(y) != 2:
				print("Error in ", args.renumfile) 
				print(x)
				raise SystemExit
			else:
				outlist.append(y[1])			
				inlist.append(y[0])
				change_num[y[1]] = y[0]
else:
	newlinelist = []
			
	new_ref = numformat
	new_refstrings = new_ref.split(".")
	init_ref = str(int(new_refstrings[0]) - 1)
	new_refstrings[0] = init_ref
	new_ref = ".".join(new_refstrings)
	reflist = []
	for r in linelist:
#				
		chaptheadm = pattern.chapthead.match(r)
		latex_sectionm = latex_section_unit.match(r)
		propnumm = pattern.propnum.match(r)
		if latex_sectionm:
				level = latex_sectionm.group(1)
				level_num = latex_sectionings.index(level)
				if level_num < major_level:
						print("Warning: No reset for new " + level)
				elif major_level <= level_num < major_level + num_nums -1:
								new_refstrings = new_ref.split(".")
								format_refstrings = numformat.split(".")
								new_refnums = [int(x) for x in new_refstrings]
								first = True
								for i in range(level_num - major_level, num_nums ):
										if first:
												new_refnums[i] = new_refnums[i] + 1
												first = False
										else:
												new_refnums[i] = int(format_refstrings[i])
								new_refstrings = [str(x) for x in new_refnums]
								new_ref = ".".join(new_refstrings)
		elif propnumm:
				old_ref = propnumm.group('refnum')
				if old_ref in reflist:
					print(old_ref + ' is a duplicate reference!')
					raise SystemExit
				else:
					reflist.append(old_ref)
				if new_ref != old_ref: 
					outlist.append(old_ref)
					inlist.append(new_ref)
					change_num[old_ref] = new_ref
				new_refstrings = new_ref.split(".")
				this_refnum = new_refstrings[-1]
				next_refnum = str(int(this_refnum) + 1)
				new_refstrings[-1] = next_refnum	
				new_ref = ".".join(new_refstrings)
#				
#
		if chaptheadm:   #Plain TeX \chap title renumbering
				old_num = chaptheadm.group(1)
				new_refstrings = new_ref.split(".")
				new_num = str(int(new_refstrings[0]) + 1)
				if old_num != new_num:
						r = re.sub(onenumpat,new_num,r, count = 1)
				new_refstrings = numformat.split(".")
				new_refstrings[0] = new_num
				new_ref = ".".join(new_refstrings)

		newlinelist.append(r)

	linelist = newlinelist

	if not outlist:
		print("No new numbering")
		raise SystemExit
#
# Create .rnm file for use renumbering files which reference this file.
#
	t = time.localtime()
	f = open(Arg_1 + "-" + str(t[1]) + "-" + str(t[0]) + ".rnm","w")
	f.write("# Renumbering of " + Arg_1 + ".tex\n")
	f.write("# " + time.asctime(time.localtime())+ "\n")
	f.write("#  New  Old\n")
	for j in range(len(inlist)):
		f.write("%s  %s\n" % (inlist[j],outlist[j]))
	f.close()
#
#
#
	print(inlist)
	print(outlist)

blocklist = build_blocklist(linelist)

f = open(Arg_1 + ".renumtmp","w")
for i, block in enumerate(blocklist):
	if i & 1:
		for pointedstring in block:
			f.write(pointedstring[0])
	else:
		for pointedstring in block:
			f.write(re.sub(refpat,changefun,pointedstring[0]))
f.close()
raise SystemExit
#
os.rename(Arg_1 + ".renumtmp", filename)
