#!/bin/bash

# generate directory, if necessary
if [ ! -d "jasa_submission" ]; then
	mkdir jasa_submission
fi
rm -r jasa_submission/*

# copy some files
cp latex/jasatex.cls jasa_submission
cp scripts/paper_results.* jasa_submission
cp latex/response_letter*.pdf jasa_submission
cp latex/author_cover_letter*.txt jasa_submission

# definitions
MANUSCRIPT=jasa_submission/manuscript.tex
TEMPTEX=jasa_submission/temp.tex
FIGURELIST=jasa_submission/figurelist.txt

# cat the relevant text together
awk '/documentclass/,/maketitle/' latex/intonation_paper.tex > $MANUSCRIPT
cat latex/section_introduction.tex >> $MANUSCRIPT
cat latex/section_method.tex >> $MANUSCRIPT
cat latex/section_accuracy.tex >> $MANUSCRIPT
cat latex/section_results.tex >> $MANUSCRIPT
cat latex/section_model.tex >> $MANUSCRIPT
cat latex/section_discussion.tex >> $MANUSCRIPT
cat latex/section_conclusions.tex >> $MANUSCRIPT
cat latex/section_appendix.tex >> $MANUSCRIPT
# echo '\section{References}' >> $MANUSCRIPT
cat latex/intonation_paper.bbl >> $MANUSCRIPT
awk '/end[{]document[}]/,0' latex/intonation_paper.tex >> $MANUSCRIPT

# remove commented lines
grep -v '^ *[%]' $MANUSCRIPT > $TEMPTEX

# list of figures
grep  -o 'figures[/][^}]*' $TEMPTEX > $FIGURELIST
while read f; do cp $f jasa_submission; done < $FIGURELIST

# make figure references relative to same directory as source file
sed 's|../figures/||g' $TEMPTEX > $MANUSCRIPT

# zip figures
cd jasa_submission
zip -r figures.zip *.pdf *.eps

# extract figure naturalheight and width
for g in *.pdf; do echo $g; rep=`grep --binary-files=text MediaBox $g | tail -1 | grep -o '[1-9][0-9]* [1-9][0-9]*' | sed 's/^/natwidth=/' | sed 's/ /,natheight=/'`; echo $rep; sed "s/.[^a-zA-Z]$g/,$rep]{$g/" manuscript.tex > temp.tex; mv temp.tex manuscript.tex; done
