#!/usr/bin/env python 
# -*- coding: utf-8 -*-

import os
import getopt
import sys
import re

__doc__ = "apply ebb to all images (pdf, png, jpg) in a tex file"
__author__ = "Kota Mori"
__date__ = "Dec 17, 2012"




# -- functions -- #

def helpmessage():
    print ' '
    print '*** ebb-all.py ***'
    print 'Kota Mori (kota.mori@yale.edu)'
    print 'Dec 17, 2012'
    print ' '
    print 'apply ebb to all images (pdf, png, jpg) in a tex file'
    print ' '
    print 'syntax:'
    print '  ebb-all.py <tex file path>'
    print ' '
    

#------------------------------------------------------------#



# -- execution part -- #
if __name__ == '__main__':
    
    # get options/arguments
    opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
    
    
    # option handling
    for o, v in opts:
        if o in ['-h', '--help']:
            helpmessage()
            sys.exit()
    
    if len(args)==0:
        print '! you have to specify a tex source !'
        print ' '
        print 'syntax:'
        print '  ebb-all.py <tex file path>'
        print ' '
        sys.exit()
        
    else:
        srcname = args[0]
        srcname = os.path.join(os.getcwd(), srcname)
        srcdir = os.path.dirname(srcname)
    with open(srcname, "r") as f:
        x = f.read()
        
    lst = re.findall("\n[^%\n\\\]*\\\includegraphics[^{}]*{[^{}]+}", x)
    lst.sort()

    imgs = []
    for l in lst:
        tmp = l 
        rr = re.search("{[^{}]+}", tmp)
        
        ipath = tmp[(rr.start()+1):(rr.end()-1)]
        ipath = os.path.join(srcdir, ipath)
        imgs.append(ipath.strip())
       
    for img in imgs:
        tmp = os.path.splitext(img)
        if tmp[1].lower() in [".pdf", ".jpg", ".png"]:
            print img
            os.system("ebb " + '"' + img + '"')    
            
# ------------------------------------------------------------ #
    
    
