#!/usr/bin/env python
# A script for merging several latex files together for submission to a Journal

import sys
import os

fp = sys.argv[1]
print 'Processing: ', fp
# sys.exit(1)

fn = os.path.basename(fp)
dir = os.path.dirname(fp)
name, ext = os.path.splitext(fn)
new_name = name + '_consolidated' + ext
body_name = name + '_body'
bbl_name = name + '.bbl'
body_path = os.path.join(dir, body_name + ext)
bbl_path = os.path.join(dir, 'build', bbl_name)

out = file(fp).read()
body = file(body_path).read()
bbl = file(bbl_path).read()
phrase1 = '\\include{%s}' % body_name
out = out.replace(phrase1, body)
out = out.replace('\\bibliography{econ}', bbl)
# TODO: make this an option rather compulsory
# out = out.replace('.png', '.jpg')
error_msg = '(NB: ELSEVIER BUILD SYSTEM REFUSED TO INCLUDE IMAGES. Please see http://rufuspollock.org/economics/papers/innovation\_and\_imitation.pdf for a version of this paper including the images).'
out = out.replace('\\caption{', '\\caption{' + error_msg)

out_fo = file(new_name, 'w')
out_fo.write(out)
out_fo.close()

