#!/bin/sh
version=5.6.2
license="Copyright (C) 1996-2009, 2011-2014 Dimitar Ivanov

License: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."
#set -vx
################################################################################
#
# muplot - gnuplot-wrapper for non-interactive plotting of multiple data files
#
# This program allows multiple data files to be viewed or printed by 'gnuplot'
# on a single multi-curve plot.
#
################################################################################
#
# 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/>.
#
################################################################################
#
# Variables
#
progname=`basename $0`
cmdstr="$progname $*"
bfname="$progname"                       # Default output-base-file-name
set_file=".${progname}set"               # External file with gnuplot commands
comm_file="$set_file"
comm_file_ignore="$comm_file.noglobal"   # Ignore global command file if touched
gdevice_def=x11                          # Output graphics device (default X11)
gdevice="$gdevice_def"                   # Init Output graphics device
gstyle=linespoints                       # Plot style (default lines and points)
out_form="unknown"                       # PS, PNG, JPG ok - for PDF see help
pscolor=color                            # PS/PDF color
psfont="'Times-Roman' 18"                # PS font type + size
pdfsize="size 29.7cm,21cm"               # PDF plot size (a4 landscape)
pdffont="font 'Arial,14'"                # PDF font + size
stdout=no                                # Do not send PS file to stdout
quiet=no                                 # Don't suppress info messages
opt_landscape=""                         # Landscape option for a plot viewer
file_list_sort=yes                       # Sort the list of files
reload_data=disabled                     # Reload data flag for quasi real-time
reload_conf="8640:10"                    # Default data reload config values

################################################################################
#
# Functions
#

### Define names of temporary/working files
#
_define_output_tmpfile_names_()
{
  [ $MUPLOT_DIR_TMP ] || MUPLOT_DIR_TMP=.
tmpfile="$MUPLOT_DIR_TMP/$progname.$$"   # Temporary work file
tmpstdin="$tmpfile.stdin"                # Temporary stdin
gpout="$tmpfile.gpt"                     # Temporary gnuplot-script output file
gperr="$tmpfile.err"                     # Temporary gnuplot-script error file
gpsty="$tmpfile.sty"                     # Temporary gnuplot-script style file
}

### Read gnuplot commands from file
#
_gnuplot_commands_read_file_()
{
  test ! -f "$comm_file_ignore" \
     && _guplot_command_print_blocks_ $1 "$HOME/$2" "$3"
  test "`pwd`" != "$HOME" \
     && test "$ignore_local_comm" != "yes" \
     && _guplot_command_print_blocks_ $1 "$2" "$3"
}

### Read external file with gnuplot commands and print out used blocks
#
_guplot_command_print_blocks_()
{
   _mode=$1 ; _comm_file="$2" ; _out_file="$3" ;

   if [ -f $_comm_file ]; then
       if   [ $_mode -gt 0 ]; then
            cat "$_comm_file" |sed -n '/^#BEGIN/,/^#END/!p'
       elif [ -n "`grep '^#BEGIN' $comm_file`" ]; then
              # print everything btw. BEGIN and END
            echo "set out $_out_file"
            cat "$_comm_file" |sed -n '/^#BEGIN/,/^#END/p'
            echo "replot"
       fi
  fi
}

### Prepare list of files to be plotted
#
_prepare_list_of_files_to_plot_()
{
   test -z "$1"  && return 1

      # Last sanity check of the cmdline file-list string syntax:
   if [ "`echo $1 |sed 's/^-..*/BAD/'`" = BAD ]; then
        echo "Error: your file name can't start with '-'"
        _clean_up_ 9
   fi
      # If input is not defined as the stdin, then evaluate file list
   if [ "x$1" = "x-" ]; then
        files_data="-"
        LIST_FILES="ls -1 $tmpstdin"
   elif [ $file_list_sort = yes ]; then
        files_data=`eval ls "$1"` || _clean_up_ 10
   else
        files_data="$1"
   fi
      # If a single file, then basename is defined using it
   if   [ `ls -1 "$files_data" 2>/dev/null |wc -l` -eq 1 ]; then
          LIST_FILES="echo $files_data"
             # Define bfname only once
          if [ x$list_nr = x ]; then
               bfname="$files_data"
                  # Remove extension from name
               bfname=`$LIST_FILES |sed "s/\.[^\.]*$//"`
          fi
   elif [ "x$files_data" != "x-" ]; then
          LIST_FILES="_do_echo_file_name_from_list_ $files_data"
   fi
   list_nr=`expr $list_nr + 1`

   if [ "$files_data" = "-" -a $reload_data = "enabled" ]; then
        echo "Error: not possible to plot data from <stdin> when using '-r'"
        _clean_up_ 15
   fi

   return 0
}

### Just print each file name from in the list of files
#
_do_echo_file_name_from_list_()
{
  for f in $*; do echo $f; done
}

### Define output file names
#
_define_output_file_names_()
{
  _ofname="$1"

  [ "x$_ofname" != x ] && bfname="$_ofname"
  if   [ $out_form != "unknown" ]; then
       ofile="$bfname.$out_form"          # Output file name
       ofile_nstr="'$bfname.$out_form'"   # Gnuplot file name string
  fi
  if [ $stdout = yes ]; then
       bfname=$tmpfile                    # Write to STDOUT - use tmp file
       ofile="$bfname.ps"
       ofile_nstr="'$bfname.ps'"
  fi
}

### Define output driver
#
_define_output_driver_()
{
  case $1 in
      ps) gdevice="postscript enh landscape $pscolor $psfont"
             # Define DIN A4 ratio of the plot relative to the canvas size
          echo "set size ratio 0.71"
       ;;
     png) gdevice="png notransparent $termopt"
       ;;
     jpg) gdevice="jpeg $termopt"
       ;;
     pdf) gdevice="pdfcairo $pscolor $pdffont $pdfsize"
       ;;
       *) [ "$gdevice" ] && gdevice="$gdevice_def"
       ;;
  esac
}

### Determine the plot style
#
_define_plot_style_()
{
  _files_data="$1" ; shift 

  while [ 1 ]; do
     case $1 in
        g) gstyle=lines
           echo "set grid"
        ;;
        d) gstyle=dots
        ;;
        p) gstyle=points
        ;;
        l) gstyle=lines
        ;;
       lp) gstyle=linespoints
        ;;
       nn) gstyle="points pt %d"
        ;;
       pp) gstyle="points pt 6"
        ;;
        b) gstyle=boxes
        ;;
        e) gstyle=errorlines
           sample=1:2:3
        ;;
        a) gstyle=dots
              # In this case $files_data must be set before further processing
           [ -z "$_files_data" ] \
           && _prepare_list_of_files_to_plot_ "$2" bfname files_data
           if [ "x$files_data" != "x-" ]; then # Input from file(s)
                cut -f3- $files_data # Data by 'prefield' - delimiter is a TAB
           else                                # Make a copy of stdin
                tee $tmpstdin |cut -f3-
           fi
        ;;
       nk) echo "unset key"
        ;;
      s=*) echo "set `echo $1 |cut -f2- -d=`"
        ;;
      u=*) gstyle="`echo $1 |cut -f2- -d=`"
        ;;
     dt=*) test -z "$gstyle" && gstyle=linespoints
              # Format in case of date/time data
           if [ x"`echo $1 |grep 'dt='`" != x ]; then
              echo "set xdata time"
              fmt="`echo $1  |cut -f2 -d= |cut -f1 -d@`"
              fmtx="`echo $1 |cut -f2 -d= |cut -f2 -d@`"
              echo "set timefmt '$fmt'"
              echo "set format x '$fmtx'"
              sample=1:2
           fi
        ;;
       3d) _plot=splot
           sample=1:2:3
        ;;
        *)
           break
        ;;
     esac
  shift
  _ns=`expr $_ns + 1`
  done

return $_ns
}

### Print gnuplot command(s) if specified from command line option
#
_print_gnuplot_cmdl_command_()
{
  _gpcmd="$1" ; _gpdev="$2" ; _gpfn="$3" ;

  if [ "$_gpdev" ]; then
  cat << EOC0
set term $_gpdev
set out $_gpfn
EOC0
  fi

  cat << EOC1
$_gpcmd
EOC1

return 0
}

### Find out samples to plot
#
_tell_me_samples_to_plot_()
{
  if [ -n "$1" ]; then
       lsample="$1"
       lsample=`echo $lsample |tr ',' '\040'` # Separate ranges by blanks
       rc=0
  else
       if [ -z "$sample" ]; then
            lsample="0:1-0"
       else
            lsample="$sample"
       fi
       rc=1
  fi
  echo $lsample
return $rc
}

### Loop for multiple data ranges applied to the current set of files and
#   print out plot statements
#
_plot_various_data_ranges_()
{
  _sample=$1
  [ "$files_data" = "-" ] && _gtitle="stdin"

  test -z "$_plot" && _plot=plot
  lastabsc=`echo $_sample |cut -f1 -d:`

  i=1; I=1;
  for j in $_sample
  do   # DATA_RANGE begin
     absc=`echo $j |cut -f1-2 -d:`                           # 3-d
     [ "$absc" = "$j" ] && absc=`echo $absc |cut -f1 -d:`    # 2-d
     first=`echo $j |cut -f1 -d- |$AWK -F: '{print $NF}'`
     last=`echo $j |cut -f2 -d-`
     [ "$last" = "$j" ] && last=$first
     [ "$absc" = "$j" -a "$i" -eq 1 ] && absc=0
     [ "$absc" = "$j" -o "$absc" = "$first" ] && absc=$lastabsc
     lastabsc=$absc
        # In case of styles that need 3 data columns
     echo $j |egrep "^[0-9]+:[0-9]+:[0-9]+$" >/dev/null 2>&1 && absc=$j

        # FILE_LOOP: prepare and print plot statements for all files in the list
     $LIST_FILES \
     |$AWK -v pl=$_plot -v _s="$gstyle" -v _nrs=$I -v _t=$_gtitle \
           -v _a=$absc -v _f=$first -v _l=$last \
             'BEGIN { printf("%s ", pl) }
                {
                  if( _t ~ /^stdin$/ )
                      tkey=" title \"<stdin>\""
                  else
                      tkey=""

                  tsty=sprintf(_s, _nrs)
                  for( i=_f; i<=_l; i++ )
                  {
                        # plot with 3-data columns
                     if( _a ~ /^[0-9]+:[0-9]+:[0-9]+$/ )
                         axes=_a
                     else
                         axes=sprintf("%s:%d", _a, i)
                     if( _t ~ /^stdin$/ )
                         tkey=sprintf(" title \"<stdin> %s\"", axes)
                     else
                         tkey=sprintf(" title \"%s %s\"", $0, axes)

                     tsty=sprintf(_s, _nrs)
                     _nrs++
                     printf("\"%s\" using %s with %s%s, ", $0, axes, tsty, tkey)
                  }

                  if( _l == 0 && _l != _f )
                      printf("\"%s\" with %s%s, ", $0, tsty, tkey)
                }
              END { printf "\n" }' > $tmpfile

     if [ "$gdevice" ]; then
       echo "set term $gdevice"
       echo "set out $ofile_nstr"
     fi

        # Paste the script saved in the tmpfile - remove last coma followed
        # by blank before end of line (have been excessively produced in the
        # FILE_LOOP)
     cat $tmpfile |sed 's/\, $//'

        # Plots after the first one must be re-plotted
     _plot=replot
     i=`expr $i + 1`
     I=`expr $I + 1`
  done # DATA_RANGE end
}

### Print gnuplot script file with on terminal
#
_gnuplot_script_print_to_terminal_()
{
  if [ $stdout != yes -a $quiet != yes -a $reload_data = "disabled" ]; then
       echo "### Your gnuplot script:"
       cat "$1" |grep -v "\#"
       echo ""
  fi
}

### Print gnuplot script errors
#
_gnuplot_errors_print_to_terminal_()
{
  echo "" 1>&2
  echo "### Gnuplot ERRORS:" 1>&2
  cat "$1" 1>&2
}

### Ask to display plot
#
_ask_to_display_plot_()
{
   _ofile="$1" ; _viewer="$2" ;

   [ $reload_data = "enabled" ] \
     && return 0

   echo "# Show picture? [y/N]"
   read answer
   if [ "$answer" = y -o "$answer" = Y ]; then
           # Consider the first word in the string to be the executable,
           # the rest are options
        viewer=`echo $_viewer |cut -f1 -d' '`
        if [ ! "`_find_exec_in_path_ $viewer`" ]; then
             echo "Warn: '$viewer' is not installed or is not in your \$PATH"
        else
             $_viewer $opt_landscape "$_ofile" &
        fi
   fi
}

### Check whether an executable program is in the path
#
_find_exec_in_path_()
{
  which $1 2>&1 |grep "^/"
}

### Verify that an input filename is provided
#
_exit_on_empty_filename_()
{
  if [ -z "$files_data" ]; then
       echo "Error: please provide a file name(s) of use '-' for <stdin>"
       _clean_up_ 14
  fi
}

### Look for GhostView installation
#
_look_for_ghostview_()
{
  _err=/tmp/.$progname.$$

  MUPLOT_VIEWER="`_find_exec_in_path_ gv`"
  if [ ! "$MUPLOT_VIEWER" ]; then
       MUPLOT_VIEWER=ghostview
  fi

     # For better view, show PS-plots in landscape orientation
  opt_landscape="-landscape"

  if [ "`_find_exec_in_path_ $MUPLOT_VIEWER`" ]; then
       test -n "$opt_landscape" \
            && $MUPLOT_VIEWER $opt_landscape /dev/null 2>&1 \
               |grep "orientation=" > $_err
       test -s $_err && opt_landscape="--orientation=landscape"
       rm -f $_err
  fi
}

### Print the raw plot to stdout
#
_print_raw_plot_()
{
   _ofile="$1"

   [ $out_form = ps ] \
     && cat $_ofile |sed "s;%%Title:.*;%%Title: $cmdstr;" \
     || cat $_ofile
}

### Append gnuplot commands for data reload to the end of the gpt-script
#
_initialize_data_reload_()
{
   reload_so_many=`echo $reload_conf |$AWK -F: '{print $1}'`
   reload_int=`echo $reload_conf |$AWK -F: '{print $2}'`
   [ "$reload_int" ] \
      || reload_int=1
   if [ "$gdevice" = x11 ]; then
        set_output=""
   else
        set_output="set out $ofile_nstr;"
   fi

   echo |($AWK "{ 
                  for( i=1; i<$reload_so_many; i++ ) print \
                       \"pause $reload_int; $set_output replot;\"
                }"
         ) >> $gpout
   _clean_up_before_reload_started_
}

### Partial cleanup in case of continuous data reload
#
_clean_up_before_reload_started_()
{
   [ ! -s "$ofile" -o $stdout = yes ] && rm -f "$ofile"
   rm -f $gpsty $tmpfile
}

### Prepare to remove various files after work finished and set a clean trap
#
_clean_up_()
{
   [ ! -s "$ofile" -o $stdout = yes ] && rm -f "$ofile" # Remove if zero size
   rm -f $gpout $gperr $gpsty $tmpfile $tmpstdin
   exit $1
}
trap '_clean_up_ $1' 1 2 3 6 15

### Show usage
#
_show_usage_()
{
d=$2
cat << END_HELP
$separator
$1
$separator

Usage: $progname [OPTION]... [STYLE] [FILE] [AXES] [FILE] [AXES] ...

Options:
   --help|-H $d display help

   -h        $d display short help
   -V        $d print program version number
   -s        $d create PostScript-file
   -S        $d send PostScript output to STDOUT (the same as '-s -o -')
   -n        $d create PNG-file
   -j        $d create JPEG-file
   -p        $d create PDF-file (requires the gnuplot "pdfcairo" driver)
   -X        $d don't set the terminal to '$gdevice_def' (use gnuplot's default instead)
   -r0       $d reload data files continuously (default $reload_conf)
   -r <N:dt> $d reload data files continuously by the specified config values
   -c <cmd>  $d execute gnuplot command(s) (using the default plot style)
   -m        $d monochrome plot (valid for PostScript or PDF)
   -l        $d set plot size to 800x600 (valid for PNG and JPEG)
   -o        $d base name of the output file
   -q        $d quiet mode (all messages except errors to be suppressed)
   -F <str>  $d input-data field separator (default is a single space character)
   -i        $d ignore local command file './$comm_file'
   -I <file> $d specify an alternative command file instead of './$comm_file'
   -U        $d do not sort the file list
   -T <dir>  $d use this directory for temporary/working output files

Styles/Settings:
   lp        $d lines and points
   l         $d lines
   p         $d points
   pp        $d circle points
   nn        $d various points (types)
   d         $d dots
   b         $d boxes
   g         $d grid
   nk        $d do not plot keys (skip file names lables)
   e         $d errorbars - default used columns are 1:2:3 (x:y:yerror)
   a         $d fields with arrows;
               The data file has a special format in this case. Use 'prefield'
               to prepare such data files.
   dt=<fmt>  $d date/time series with the specified format;
               For example: dt="%H:%M.%S@%H:%M" where the first part, in front
               of "@", defines the data format, and the second part defines the
               format that will be used for tic labels. Here, hours and minutes
               are separated by \`:', respectively minutes and seconds by \`.'
               Another example is date and time stamp: dt="%Y-%m-%d %H:%M:%S"
   3d        $d plot 3-d data using 1:2:3
   u=<fmt>   $d user specified plot style format (as defined in Gnuplot);
               For example: u="points pointtype 2 pointsize 3"; To see the
               present terminal and palette capabilities of gnuplot use the
               command '$progname -c test'.
   s=<opt>   $d user specified setting (as defined in Gnuplot);
               For example: s="logscale x"
   
Axes:
   x:y,x:y-z $d columns in the file defining the x/y-axes of the curve(s);
               Default are 1:2 or 1:2:3 for data with errors. In case that only
               one column is provided the default axes are 0:1 - the x-axis
               will be a simple index then.


File(s) could be a single file name whereas '-' means <stdin>, many files
enclosed in '' or "" like "file1 file2 file3", or any valid shell pattern
as for example "*.dat". The files '\$HOME/$comm_file' and './$comm_file', if
existing, will be included at the beginning of the gnuplot script. The command
block between "#BEGIN" and "#END" in those files will be pasted to the end of
the script. If you want that the global '\$HOME/$comm_file' is ignored, create
in your local directory a file named '$comm_file_ignore'. In case you want
to view the output, define the env variable MUPLOT_VIEWER and export it,
for example:

   MUPLOT_VIEWER="xpdf -z page"; export MUPLOT_VIEWER

Then the program will prompt you to view the plot, and after confirmation the
viewer will present the graphics. If the postscript file format is chosen
('-s' option), and MUPLOT_VIEWER is not defined, the viewer is preset to 'gv',
and per default you are prompted to view the output. To disable this behavior
use the command "unset MUPLOT_VIEWER".


Examples:

1) On X-terminal view a multi-curve plot of all data-files with extension 'dat'

   $progname "*.dat"

2) Print a sinus curve in black-and-white color on a PostScript-printer

   $progname -m -S -c "set title 'Function f(x)=sin(x)'; plot sin(x);" | lpr

3) Plot data from file "example.dat" using columns 1:2, 3:4, and 3:5 as x/y-axes in the multi-curve plot; a PostScript-file with the name "example.ps" is automatically created.

   $progname -s example.dat 1:2,3:4-5

4) Create graphics in PDF-format reading data from file "example.1.dat" (columns 1:2), and from file "example.2.dat" (columns 3:4)

   $progname -p lp example.1.dat 1:2 example.2.dat 3:4

5) View file where the first column is data, and the third and forth columns are date of the form 'yyyy-mm-dd' and time in the form 'hh:mm:ss'

   cat example_counts_per_second.dat | $progname dt="%Y-%m-%d %H:%M:%S" - 3:1

6) Plot 3-dimensional data from file "example_3d.dat" using the 1,3, and 5-th data columns with dots-plot-style, enabling grid, setting the xrange to [0:10], disabling keys and defining a plot-title

   muplot nk g d 3d s="xrange [0:10]" s="title 'This is a 3-d plot'" example_3d.dat 1:3:5

7) Replot data 1000 times every 5 seconds and write temporary created files in the '/tmp' directory; This scenario is useful in case of growing or otherwise changing over time data-file

   muplot -T /tmp -r 1000:5 example.dat


Report bugs to <gnu@mirendom.net>

END_HELP

}

### Print out license
#
print_licence_version()
{
  cat << _VERSION_
$progname $version
$license
_VERSION_
}

### Print out usage (short help)
#
print_usage()
{
  separator=`echo |$AWK '{printf( "%080d", 0 )}' |tr 0 -`
  header_text="$progname $version: plot a multi-curve figure from multiple data by using Gnuplot"
  _show_usage_ "$header_text" "-" \
       |egrep "^($progname|Usage:|Options:|Styles.*:|Axes:|.*--|.*[\ >]\ -\ |.*\,x:y-z)"
}

### Print out Help (long help)
#
print_help()
{
  separator=""
  header_text="Muplot is a simple, non-interactive gnuplot-wrapper to plot a multi-curve figure from multiple data (files). It can produce PostScript, PDF, PNG or JPEG output file formats."
  _show_usage_ "$header_text" " "
}

################################################################################
#
# MAIN

   # We need an AWK supporting assignments
if [ x"$AWK" = x ]; then
     exec 3>&2 2>&-
     for a in gawk nawk awk
     do
        [ "`set +x; echo |$a -v a=a '{}' 2>&1`" = "" ] && AWK=$a
     done
     exec 2>&3
fi
[ x"$AWK" = x ] && \
  echo "Error: can't find 'awk' programm supporting assignments" && \
  exit 12

[ $# -eq 0 ] && set -- "-h"

   # Process cmdline options
while [ 0 ]
do
case $1 in
    -h)           # Print usage (short help) and exit
        print_usage
        exit 0
     ;;
    -H|--help)    # Print help and exit
        print_help
        exit 0
     ;;
    -V)           # Print version and exit
        echo $version
        exit 0
     ;;
    -v|--version) # Print version and license and exit
        print_licence_version
        exit 0
     ;;
    -s) out_form=ps
        [ "`env |grep ^MUPLOT_VIEWER`" ] || _look_for_ghostview_
     ;;
    -S) out_form=ps
        stdout=yes
     ;;
    -n) out_form=png
     ;;
    -j) out_form=jpg
     ;;
    -p) out_form=pdf
     ;;
    -X) gdevice=""
     ;;
    -r) reload_data=enabled
        reload_conf="$2"
        shift
     ;;
   -r0) reload_data=enabled
     ;;
    -c) gpt_cmd="$2"
        shift
     ;;
    -l) termopt="large size 800,600"
     ;;
    -m) pscolor=monochrome
     ;;
    -o) [ "x$2" != "x-" ] \
           && ofname=$2 \
           || { stdout=yes; quiet=yes ;}
        shift
     ;;
    -q) quiet=yes
     ;;
    -i) ignore_local_comm=yes
     ;;
    -I) set_file="$2"
        shift
        [ ! -e "$set_file" ] \
          && echo "$progname: no such file '$set_file'" \
          && exit 13
     ;;
    -F) data_FS="$2"
        shift
     ;;
    -T) MUPLOT_DIR_TMP="$2"
        shift
     ;;
    -U) file_list_sort=no
     ;;
   -|*) break
     ;;
    -*) exec 1>&2
        echo "$progname: invalid option '$1'"
        echo "Try \`$progname -H' for help."
        exit 8
     ;;
esac
shift
done

   # Setup names for working files
_define_output_tmpfile_names_

   # Check whether gnuplot is available
[ ! `which gnuplot 2>&1 |grep "^/"` ] \
    && echo 'Gnuplot is not installed or is not in your $PATH' \
    && _clean_up_ 7

   # Create script file for gnuplot
echo "unset time" > $gpout

   # Set data-field separator if defined
[ "$data_FS" ] \
&& echo "set datafile separator \"$data_FS\"" >> $gpout

   # Define output driver
_define_output_driver_ $out_form >> $gpout

   # Read gnuplot commands from file - OUTSide #BEGIN ... #END block
_gnuplot_commands_read_file_ 1 "$set_file" dummy >> $gpout

   # Check for gnuplot command(s) specified by '-c'
if [ -n "$gpt_cmd" ]; then
     _define_output_file_names_ "$ofname" bfname ofile ofile_nstr
     _print_gnuplot_cmdl_command_ "$gpt_cmd" "$gdevice" "$ofile_nstr" >> $gpout

   # Process the list of files
else 
        # Determine the plot style and send the output to the style-file;
        # More than one style can be specified this way
     _define_plot_style_ "$files_data" "$@" >> $gpsty
     shift $?

        # Check for files specified
     _prepare_list_of_files_to_plot_ "$1" bfname files_data \
     && data_file_set=defined

        # Exit if no filename provided
      _exit_on_empty_filename_ "$files_data"

        # Define output file names
     _define_output_file_names_ "$ofname" bfname ofile ofile_nstr

        # Add the style file to the output script
     cat $gpsty >> $gpout

        # Loop over multiple file sets
     while [ $data_file_set ]
     do    # FILE_SET begin
        shift
           # If input is piped in, then start using the temporary file
        [ "x$files_data" = "x-" ] && cat ->> $tmpstdin && exec <&1
   
           # Check for samples and ranges
        sample=`_tell_me_samples_to_plot_ "$1"` \
        && shift

           # Look for multiple data ranges and print out plot commands
        _plot_various_data_ranges_ "$sample" files_data gdevice ofile_nstr >> $gpout

           # Look for next data file set and prepare a list
        _prepare_list_of_files_to_plot_ "$1" bfname files_data \
        || data_file_set=""

     done  # FILE_SET end
fi

   # Read gnuplot commands from file - INSide #BEGIN ... #END block
_gnuplot_commands_read_file_ 0 "$set_file" "$ofile_nstr" >> $gpout

   # "pause" if the terminal is X11 or is not defined explicitely
if [ "$gdevice" = x11 -o "$gdevice" = "" ]; then
   [ $reload_data = "disabled" ] \
     && echo "pause -1" >> $gpout
fi

   # In case of continues data reload for "real-time" data observation
[ $reload_data = "enabled" ] \
  && _initialize_data_reload_ reload_conf ofile_nstr gpout files_data

   # Execute GNUPLOT
gnuplot $gpout > $gperr 2>&1

   # Print out the gnuplot script
_gnuplot_script_print_to_terminal_ $gpout

   # If gnuplot failed with errors, report them and exit
if [ -s $gperr ]; then
     _gnuplot_errors_print_to_terminal_ $gperr
     _clean_up_ 11
fi

if [ $stdout = yes ]; then
        # Print the raw plot to STDOUT if chosen
     _print_raw_plot_ "$ofile"
else
        # Print the name of the output file
     if [ -n "$ofile_nstr" -a $quiet != yes ]; then
          echo "# Your plot file is $ofile_nstr."
     fi
        # Ask user whether he wants to view the plot
     if [ $quiet != yes -a "$gdevice" != x11 ]; then
          if [ -n "$MUPLOT_VIEWER" ] ;then
               _ask_to_display_plot_ "$ofile" "$MUPLOT_VIEWER"
          fi
     fi
fi

_clean_up_ 0
