# This shows how to use the exceltex package with latexmk
#
# Exceltex is a package that enables LaTeX documents to use data from
# Excel spreadsheets.  It has two parts: a LaTeX package in a file
# named exceltex.sty and a (Perl) script named exceltex.  The custom
# dependency given below enables latexmk to call the exceltex script
# whenever appropriate.
#
# The functioning is as follows: The main tex file uses the package
# exceltex to specify the use of the contents of cells in an xls
# spreadsheet. It does this by writing a specification of the cells to
# a file with extension excltx. The script exceltex reads this,
# extracts the data from the spreadsheet(s), and writes them in files
# that are read during the next compilation of the main document. (The
# exceltex package, with its script, is part of the current version of
# TeXLive, as of 2012.)
#
# In addition to running the exceltex script, the subroutine defined
# below also reads the excltx file to find the names of the
# spreadsheet files used. It then uses an internal subroutine of
# latexmk to add these files to the source-file list of the custom
# dependency. Thus if the spreadsheet file (or files) changes, even
# without any other changes, latexmk will know to rerun exceltex and
# then recompile the main tex file if necessary.
#
# Notes:
#   1.  See
#      http://tex.stackexchange.com/questions/107764/exceltex-dependencies-in-latexmk 
#      for the motivation, and see the exceltex documentation for an
#      example of the use of the exceltex package.
#   2. You may find you need to install certain Perl modules in
#      order for the exceltex script to work; these modules are needed
#      for parsing excel spreadsheets.  You'll need to examine
#      documentation for Perl to find out how to do this.


add_cus_dep('excltx', 'tex', 0, 'excel2tex');
sub excel2tex {
    # This subroutine is a fudge, because it from latexmk's point of
    # view, it makes the main .tex file depend on the .excltx file.
    # But it doesn't actually make the .tex file, but is used for its
    # side effects in creating other files.  The dependence is a way
    # of triggering the rule to be run whenever the .excltx file
    # changes, and to do this before running latex/pdflatex again.

    # First find dependency/ies on .xls files, by parsing the .excltx file,
    my $Hsource = new FileHandle;
    my %xls = ();
    my $source = "$_[0].excltx";
    if (! open $Hsource, "<$source") {
        warn "excel2tex subroutine: Could not read '$source'\n";
        return 1;
    }
    while ( <$Hsource> ) {
        if ( /^\s*;/ ) { next; }
        if ( /^\s*[ct]:[^:]*\:([^!]*)!/ ) { $xls{$1} = 1; }
    }
    close $Hsource;
    foreach (keys %xls) {
        rdb_ensure_file( $rule, $_ );
    }
    return system("exceltex \"$_[0]\"") ;
}

