#! /bin/bash

# lsq output file with improved parameters
prm="lsq.log"

# lsq output file table : 2theta  observed  calculated
dat="lsq.xy"
out="lsq.jog"

# plot style for observed and calculated data
exp="2 Size NoLines Empty Circles"
cal="Lines"

# setup x and y scales
xmin="0"
xmax="50"
ymin="-500"
ymax="21000"

# top of table in points
h0="230"

# absolute x position of each column of table
x1="280"
x2="290"
x3="320"
x4="380"
x5="390"
x6="440"

# place legend of graph elements
xleg="110"
yleg="230"
#font="(Times-RomanF) 12 Font"
font="(HelveticaF) 12 Font"

# overwrite default by command line assignments
# to change on the fly plot styles or layout
for arg; do eval $arg; done

echo "
gsave
$font
[50 500 50 250] [$xmin $xmax $ymin $ymax] Axe2

[ (5) (10) (15) (20) (25) (30)] GradX
% [(0)(500)(1000)] GradY
(2\`q) GradX
% (a.u.) GradY

$exp
[
$( cat lsq.xy | awk ' { printf("%s\t%s\n",$1,$2) } ' )
] Plot

$cal
[
$(
  # trim data below maxy
  cat lsq.xy | awk -v ymax="$ymax" '$3<ymax { printf("%s\t%s\n",$1,$3) }'
)
] Plot
grestore

gsave
% jog's nasty bug use only once in a gsave grestore bracket
% TODO fix this !
10 Font

$xleg $yleg
($exp) ( Experimental) Label
($cal) ( Calculated) Label

$x1 $h0
$(head -n 51 $prm | awk ' NF==2 { if ($2==0) {print "()"} else {print "(*)"} }' | head -n 9 )
Wrt

$x2 $h0
(W_B) (W_C) (P_B_B)(P_B_C)(P_C_B)(P_C_C) (d_A) (d_B) (d_C) Wrt

$x3 $h0
$(head -n 51 $prm | awk ' NF==2 {printf("(%6.4f)\n",$1)}' | head -n 9)
Wrt

$x4 $h0
$(head -n 51 $prm | awk ' NF==2 { if ($2==0) {print "()"} else {print "(*)"} }' | tail -n 10 )
Wrt

$x5 $h0
(Sig. A)(Sig. B)(Sig. C)(Avg. n)(Sigma*)(Scale)(Div. Slit)(Soller 1)(Soller 2)(Sample L.)
Wrt

$x6 $h0
$(head -n 51 $prm | awk ' NF==2 {printf("(%6.4f)\n",$1)}' | tail -n 10)
Wrt
grestore
" > $out
ge $out

