#! /bin/bash

# Whizzy4Vim latex helper script
# Version 0.0.2
#
# This is a part of Whizzy4Vim and should not be invoked directly.
# Copyright (C) 2007 Yusuke Nakano <pakuchan@pakunet.jp>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

LATEX=$1
shift

if ! expr "$2" : '_whizzy_.*_nil.tex' > /dev/null 2>&1 \
	&& ! expr "$2" : '\\WhizzytexInput' > /dev/null 2>&1; then
	INPUT=`echo $2 | sed 's/_whizzy_//g'`

	DOCUMENT_START_LINE=`grep -n '^[^%]*\\\\begin{document}' "$INPUT" | cut -d':' -f1`
	let PREAMBLE_END_LINE=${DOCUMENT_START_LINE}-1

	sed -n "1,${PREAMBLE_END_LINE}p" "$INPUT" > "$2".tmp
	sed 's:\\WhizzySkip\\SourceFile{.*}\\WhizzyStart{}\\WhizzyLinePoint{.*}\\relax:\\makeatletter\\def\\texpreview@quote{\\string"}\\def\\texpreview@anchor{\\special{html\: <A name=\\texpreview@quote Start-Document\\texpreview@quote>}\\special{html\: </A>}}\\def\\texpreviewanchor{\\texpreview@anchor}\\makeatother:g' "$2" | sed 's/^\(.*\)\(.*\)/\\texpreviewanchor\1\2/g' >> "$2".tmp
	mv "$2".tmp "$2"

	shift		# drop the format file argument

	texfile=$1
	shift
	set -- "\\nonstopmode\\input{$texfile}" "$@"
fi

echo "$@" >> hogehoge
exec $LATEX "$@"

