#!/usr/bin/env bash

tex_file=$(mktemp) ## Random temp file name

cat<<EOF >$tex_file   ## Print the tex file header
\documentclass{book}
\usepackage{fontspec}
\setmainfont{Bitstream Vera Sans}
\usepackage{listings}
\usepackage[usenames,dvipsnames]{color}  %% Allow color names
\lstdefinestyle{customasm}{
  belowcaptionskip=1\baselineskip,
  xleftmargin=\parindent,
  language=C++,   %% Change this to whatever you write in
  breaklines=true, %% Wrap long lines
  basicstyle=\footnotesize\ttfamily,
  commentstyle=\itshape\color{Gray},
  stringstyle=\color{Black},
  keywordstyle=\bfseries\color{OliveGreen},
  identifierstyle=\color{blue},
  xleftmargin=-8em,
}        
\usepackage[colorlinks=true,linkcolor=blue]{hyperref}
\begin{document}
\tableofcontents

EOF

while read  i; do                ## Loop through each file
    name=${i/\\_}             ## escape underscores
    echo "\newpage" >> $tex_file   ## start each section on a new page
    echo "\section{$name}" >> $tex_file  ## Create a section for each filename
    echo "\lstinputlisting[style=customasm]{$i}" >>$tex_file
done <filestoprint 
   echo "\end{document}" >> $tex_file &&   
   xelatex $tex_file -output-directory . && 
   xelatex $tex_file -output-directory .  ## This needs to be run twice 
                                           ## for the TOC to be generated