#!/bin/sh
VERSION=1.4.7
NAME=`basename $0`
NV="$NAME $VERSION:"
LICENSE="Copyright (C) 1997, 2001, 2005, 2007, 2009, 2011 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."
#
################################################################################
#
# prefield - prepare input file for 'muplot' to plot 2-d fields by arrows
#
# 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/>.
#
################################################################################
#
sep=`echo |awk '{printf( "%080s", 0 )}' |tr 0 -`

if [ x$1 = x--version ]; then
     cat << !ver
$NAME $VERSION
$LICENSE
!ver
     exit
fi

[ x$1 = x--help ] && NV="$NAME" && sep=""

if [ $# != 6 ]; then

cat << EOH

$sep
$NV prepare input file for 'muplot' to plot 2-d fields by arrows
$sep

Usage: $NAME <file> <scale> x y F_x F_y

Example: 

On running "$NAME test.dat 20 1 2 5 6" the source file 'test.dat' will be
read, and a field-data file will be produced with the 1st and 2nd columns being
the x and y space-positions like in the source file, whereas the fields F_x
and F_y are calculated from the values in the 5th and 6th columns of the source
data multiplied by the second command line option, which means in this example
a 20-fold magnification.

Use '-' as file name to read from <stdin> and write to <stdout>.

EOH

exit 1
fi

### Main
trap 'rm -f "$ofile"; exit' 1 2 3 15

ofile="$1.$2_$3$4$5$6.fd"

[ "$1" != "-" ] && exec 3>&1 1>$ofile

cat $1 |egrep -v '(#|^$)' \
       |awk -v x=$3 -v y=$4 -v fx=$5 -v fy=$6 -v s=$2 -v cmd="# $0 $*" \
            'BEGIN { print cmd; }
             { printf("%g\t%g\tset arrow from %g,%g to %g,%g\n",
	                   $x, $y, $x, $y, $x+(s*$fx), $y+(s*$fy));
             }'

[ "$1" != "-" ] && exec 1>&3 && echo "Your output file is $ofile"

exit 0
