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

import sys
import os

def main(fp):
    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()
    if os.path.exists(body_path):
        body = file(body_path).read()
        phrase1 = '\\include{%s}' % body_name
        out = out.replace(phrase1, body)

    bbl = file(bbl_path).read()
    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()
    print 'Merged file written to: %s' % new_name

if __name__ == '__main__':
    usage = '''%prog {file-path}
    
A script for merging several latex files together for submission to a journal.

@output: file name is input file name with '_consolidated' appended.

NB: assumes built files (such as bbl) are in subdirectory named build of
directory where file is.'''
    import optparse
    parser = optparse.OptionParser(usage)
    options, args = parser.parse_args()
    if len(args) < 1:
        parser.print_help()
    else:
        fp = args[0]
        print 'Processing: ', fp
        main(fp)


