if=$1 # the first argument is the input file
of=$2 # the second argument is the output file

# gets the names of the meteo statons from the name of the input file,
# that is assumed in the format like: ST1_ST2_.....dat
st1=`echo $if | awk -F \_ '{print $1}'`
st2=`echo $if | awk -F \_ '{print $2}'`


cat > plotta << EOF

set border 31 lw 2
set style line 1 lt 1 lw 2 lc rgb "blue" pt 1 ps 1

set terminal png large size 800,800 font "Helvetica,16"
set out 'spare.png'
plot '$if' u 3:4 w p 
set out '$of'
set title "External Temperature correlation plot, stations $st2 vs $st1"
set xlabel 'Temperature station $st1 (deg.C)'
set ylabel 'Temperature station $st2 (deg.C)'


set fit errorvariables
a=1
b=1
f(x)=a*x+b
fit f(x) '$if' u 3:4 via a, b
set label 1 "Fitting with f(x) = ax + b" at graph 0.05,0.95
set label 2 sprintf("a = %3.5g",a) at graph 0.1,0.9
set label 3 sprintf(" +/- %3.5g",a_err) at graph 0.28,0.9
set label 4 sprintf("b = %3.5g",b) at graph 0.1,0.85
set label 5 sprintf(" +/- %3.5g",b_err) at graph 0.28,0.85
set label 6 sprintf("RMS of residuals = %3.5g",FIT_STDFIT) at graph 0.1,0.8

m=5
mu=10
print GPVAL_DATA_X_MIN
print GPVAL_DATA_X_MAX
set yrange [GPVAL_DATA_X_MIN-m:GPVAL_DATA_X_MAX+mu]
set xrange [GPVAL_DATA_X_MIN-m:GPVAL_DATA_X_MAX+mu]
plot '$if' u 3:4 w p pt 7 ps 1 t'$st2 vs $st1', f(x) w l ls 1 not

EOF


gnuplot plotta
rm -f plotta spare.png

exit 0









