#!/usr/bin/env python

import re

fname = 'build/latex/tesis.tex'

bib_re = re.compile(r'(\\begin{thebibliography}{[^}]+})'
		r'(.*)'
		r'(\\end{thebibliography})',
		re.S)

text = file(fname).read()

head, body, foot = bib_re.findall(text)[0]

body = '\n'.join(
		sorted(
			body
				.replace('\n', '')
				.replace('\\bibitem', '\n\\bibitem')
				.splitlines()
		)
	)

text = bib_re.sub('\n'.join((head, body, foot)).replace('\\', '\\\\'), text)

#print text
file(fname, 'w').write(text)

