#!/bin/bash

error_fcn()
{
	echo "$1"
	echo "See help, try combine_data_1 -h."
}

# Block 1. Here we parse the input parameters and check for errors.
###############################################################################

# This converts a script into a proper pipe filter.
	declare -a A=("$@")
		[[ -p /dev/stdin ]] && { \
			mapfile -t -O ${#A[@]} A; set -- "${A[@]}"; \
					}

	options=" "
	for item in $@
	do
		if [[ ${item} == -* ]] || [[ ${item} == --* ]]; then
			option=${item}
			options="${options} ${item}"
			if [[ ${option} == -h ]]; then
echo
echo This script combines multiple convergence tables \(they are in the tex
echo files located in ./Data/somesubdirectory/\) generated by the main simulation
echo program into one tex file and feeds the result to pdflatex which, in turn,
echo generates a pdf file. The texlive package must be installed. The resultant
echo tex and pdf files are written into the Data/ directory.
echo
echo Example:
echo
echo ./combine_data_1 -d mms -f square -lb 12 -la 4 -p 0 -s main_table -a PHI
echo
echo where:
echo
echo -d  - the main directory of the experiment
echo
echo -f  - directory in ./Data/, i.e., ./Data/square/, that contains separate
echo       convergence tables generated by the main simulation  program.
echo
echo -lb - the number of the first line with data in the input tex file.
echo
echo -la - the amount of the lines with data in the input tex file.
echo
echo -p  - the lowermost value of the parameter p \(the degree of the finite elements\).
echo
echo -s  - stem of the names of the files that contain the convergence data.
echo       In this particular example the data is stored in files
echo       main_table_p1.tex, main_table_p2.tex, etc.
echo
echo -a  - the suffix to add to the name of the output file. In this
echo       particular example the aggregated data will be saved in files with
echo       names square_PHI.pdf and square_PHI.tex.
echo
echo or
echo
echo ./combine_data_1 -h
echo Prints this help.
echo
				exit 0
			fi
		else
			if [[ ${option} == -f ]]; then
				fname=${item}
			elif [[ ${option} == -d ]]; then
				dir=${item}
			elif [[ ${option} == -lb ]]; then
				line_begin=${item}
			elif [[ ${option} == -la ]]; then
				line_amount=${item}
			elif [[ ${option} == -p ]]; then
				p_min=${item}
			elif [[ ${option} == -s ]]; then
				fname_stem=${item}
			elif [[ ${option} == -a ]]; then
				fname_sfx=${item}
			else
				error_fcn "Illegal option: ${option}"
				exit 2
			fi
		fi
	done

	if [[ ! ${options} == *-d* ]]; then
		error_fcn "missing -d option."
		exit 3
	fi

	if [[ ! ${options} == *-f* ]]; then
		error_fcn "missing -f option."
		exit 4
	fi

	if [[ ! ${options} == *-lb* ]]; then
		error_fcn "Missing -lb option."
		exit 5
	fi

	if [[ ! ${options} == *-la* ]]; then
		error_fcn "Missing -la option. See help clone -h"
		exit 6
	fi

	if [[ ! ${options} == *-p* ]]; then
		error_fcn "Missing -p option. See help clone -h"
		exit 7
	fi

	if [[ ! ${options} == *-s* ]]; then
		error_fcn "Missing -s option. See help clone -h"
		exit 7
	fi

# End block 1. Now we have:
# 1) dir - Directory of the experiment.
# 2) fname - The name of the subdirectory where data are saved.
# 3) line_begin - The index of the first data line in the tex file.
# 4) line_amount - The amount of data lines in the tex file.
# 5) p_min - The lowermost degree of the finite elements used.
# 6) fname_stem - Stem of the names of the files that contain the convergence data.
# 7) fname_sfx - The suffix to add to the name of the output file.
# Uncomment the following lines to print them.
	echo "Directory of the experiment = ${dir}"
	echo "The name of the subdirectory = ${fname}"
	echo "The first data line = ${line_begin}"
	echo "The amount of data lines = ${line_amount}"
	echo "The lowermost degree of the finite elements used = ${p_min}"
	echo "Stem of the names of the input files = ${fname_stem}"
	echo "The suffix of the output file = ${fname_sfx}"
###############################################################################

the_header="\documentclass[a4paper, 12pt, openright]{book}
\usepackage{amsmath,amsfonts,amsthm} % Math packages

\begin{document}

\begin{table}
\begin{equation*}
\begin{array}{|c|c|c|c|c|c|c|c|}
\hline
p&r&\text{cells}&\text{dofs}&||e||_{L^2}&\alpha_{L^2}&||e||_{H^1}&\alpha_{H^1} \\\\
\hline \hline"

the_foot="\end{array}
\end{equation*}
\caption{Compound table composed of main\_table\_p?.tex tables.
The numerical experiment - ${dir}. The problem domain - @.}
\end{table}

\begin{itemize}
\item p - The degree of the interpolating Lagrange polynomials that constitute
the shape functions.
\item r - The number of nodes on the transfinite lines of the mesh.
\item cells - The total amount of active cells.
\item dofs - Degrees of freedom. The total amount of support points in active
cells.
\item $||e||_{L^2}$ - The $ L^2 $ error norm.
\item $||e||_{H^1}$ - The $ H^1 $ error norm.
\item $\alpha_{L^2}$ - The order of convergence of the $ L^2 $ error norm.
\item $\alpha_{H^1}$ - The order of convergence of the $ H^1 $ error norm.
\end{itemize}

\end{document}
"
fname_out="Data/${fname}_${fname_sfx}.tex"
rm -rf ${fname_out}
touch ${fname_out}
echo "${the_header}" >> ${fname_out}

for (( p=${p_min}; p<${p_min}+3; p++ ))
do
	fname_in="Data/${fname}/${fname_stem}_p${p}.tex"
	echo "${fname_in}"
		for (( l=0; l<line_amount; l++ ))
		do
			echo `sed -n $((line_begin+l))p ${fname_in}` >> ${fname_out}
		done
	echo "\hline" >> ${fname_out}
done

echo "${the_foot}" | sed s/@/${fname}/g >> ${fname_out}

cd Data

retval=`which pdflatex`
if [[ "${retval}" == "" ]];then
	echo Cannot find pdflatex. Exiting ...
else
	pdflatex ${fname}_${fname_sfx}.tex
fi

cd ..

rm Data/*.aux Data/*.log

