#!/usr/bin/perl -w

# Doesn't handle \documentstyle, because you should be able to replace
# that with \documentclass and \usepackage.
# Need separate \usepackage on it's own line for each package to be inlined.
# Also assumes that \input, \usepackage, \bibliography, and my own \incite and
# \inputnospell use only the root name of the relevant file in it's argument.
# Also assumes \bibliography command is used in the top-level file name.

$debug = 0;

($progname = $0) =~ s+.*/++;

#@searchpath = split(/:/,$ENV{'TEXINPUTS'}); if ($debug>1) {print "searchpath: @searchpath\n";};

#if ($#ARGV < 0) {print STDERR "usage: $progname jobname ext fileroot OR $progname file\n"; exit 1;}
if ($#ARGV < 0) {$fullfile="-";}
else{
$filename=$ARGV[0];
#$if ($#ARGV == 0) {$ext="tex"; ($jobname=$ARGV[0]) =~ s+\.[^.]*++}
#else {$jobname = $ARGV[0]; $ext = $ARGV[1]; shift; shift}
#if ($debug) {print "jobname: $jobname; ext: $ext\n";};
if ($debug) {print "filename: $filename\n";};
# @files = split(/,/,$ARGV[0]); if ($debug) {print "files: @files\n";};
# foreach $file (@files) { if ($debug) {print "file: $file...";};
$fullfile = `kpsewhich $filename`;
print $fullfile;
# foreach $dir (@searchpath) {
#   if ("$ext" eq "tex") {
#     if (-e "$dir/$file") {$fullfile = "$dir/$file"; last;}
#     if (-e "$dir/$file.tex") {$fullfile = "$dir/$file.tex"; last;}
#   }
#   else {
#     if (-e "$dir/$file.$ext") {$fullfile = "$dir/$file.$ext"; last;}
#   }
# }
if ("$fullfile" eq "") {print "${progname}: File $filename not found in TEXINPUTS\n"; exit (1)}
if ($debug) {print "fullfile: $fullfile\n";};
}
open(FH,"$fullfile") || die "Cannot open $fullfile: $!";

while (<FH>) {
  if (/^[ 	]*\\inputnospell\{([^}]*)}/) {print "%%% Inlined $1.tex follows\n"; system("$progname $1.tex"); print "%%% End of $1.tex\n$'"; next}
  if (/^[ 	]*\\input\{([^}]*)}/) {print "%%% Inlined $1.tex follows\n"; system("$progname $1.tex"); print "%%% End of $1.tex\n$'"; next}
  if (/^[ 	]*\\incite\{([^}]*)}/) {print "%%% Inlined $1.tex follows\n"; system("$progname $1.tex"); print "%%% End of $1.tex\n$'"; next}
  if (/^[ 	]*\\usepackage\{([^}]*)}/) {print "%%% Inlined $1.sty follows\n"; system("$progname $1.sty"); print "%%% End of $1.sty\n$'"; next}
  if (/^[ 	]*\\bibliography\{([^}]*)}/) {print "%%% Inlined $1.bbl follows\n"; system("$progname $1.bbl"); print "%%% End of $1.bbl\n$'"; next}
  print;
}
#}
