#!/bin/bash

# Create a JPG from gnuplot. 

if [[ -z $1 ]] ; then
  echo "Usage: Gnu2jpg.sh <inputfile> [rect] [square] [size <x,y>]"
  exit 0
fi

if [[ ! -e $1 ]] ; then
  echo "$1 not found."
  exit 1
fi

SIZE="1024,768"
if [[ $2 = "rect" ]] ; then
  SIZE="1024,384"
elif [[ $2 = "square" ]] ; then
  SIZE="768,768"
elif [[ $2 = "size" ]] ; then
  if [[ -z $3 ]] ; then
    echo "Specify size as 3rd argument: x,y"
    exit 1
  fi
  SIZE=$3
fi

FILE=`basename $1`
PREFIX=${FILE%.gnu}
JPG=$PREFIX.jpg
echo $JPG

cat > temp.gnu <<EOF
set terminal jpeg size $SIZE 
set output "$JPG"
EOF
# Scan the gnuplot file and remove any pause statements
cat $1 | awk '{if ($1!="pause") print $0;}' >> temp.gnu

gnuplot temp.gnu

rm temp.gnu
