#!/usr/bin/perl
#
# Create foo.pdf togehter with many intermediate files 
# from gnuplot file foo.txt
# 
# Please use the naming convention, that in a 
# gnuplot file foo.txt  the output is set to: 
# set output 'foo-input.tex' 
#
# Janine Glänzel, Roman Unger ... 06/2014 
#
###############################################################
#
#   Copyright (C) 2014  Janine Glänzel, Roman Unger
#
#   janine.glaenzel@mathematik.tu-chemnitz.de
#   roman.unger@mathematik.tu-chemnitz.de
#
#   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 3 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, see <http://www.gnu.org/licenses/>.
#
###############################################################

use strict;


if (@ARGV != 1) { die "usage: $0 gnuplotfile.txt\n";}

my $f=$ARGV[0];

my $stem=$f;
$stem =~ s/\.txt$//;
my $res;

# STEP 1 gnuplot, it creates stem-input.tex and stem-input.eps
$res = system("gnuplot $stem.txt");
die "gnuplot error res=$res\n" until ($res==0);

# STEP 2 create the latexfile stem.tex
open (TEX,">$stem.tex") || die "Cant write $stem.tex\n";
print TEX "\\documentclass[12pt]{article}\n";
print TEX "\\usepackage{german,indentfirst,graphicx,color}\n";
print TEX "\\usepackage{SIunits}\n";
print TEX "\\usepackage{amsmath}\n";
#print TEX "\\usepackage{amssymb}\n";
print TEX "\\pagestyle{empty}\n";
print TEX "\\begin{document}\n";
print TEX "\\begin{center}  {   \\sffamily   ";
print TEX "\\input{$stem-input.tex}  } \\end{center}\n";
print TEX "\\end{document}\n";
close TEX;

# STEP 3, run latex to get stem.dvi
$res = system("latex $stem.tex");
die "latex error res=$res\n" until ($res==0);

# STEP 4, run dvips -E to get stem.ps
$res = system("dvips -E $stem.dvi");
die "dvips error res=$res\n" until ($res==0);

# STEP 5, run epstopdf to get stem.pdf
$res = system("epstopdf $stem.ps");
die "epstopdf error res=$res\n" until ($res==0);

# STEP 6, run epstopdf on stem-input.eps  to get stem-input.pdf
# which allows direct including of the stem-input.tex
$res = system("epstopdf $stem-input.eps");
die "epstopdf error res=$res\n" until ($res==0);


