#!/bin/bash
#
#
# Plot Euler angle distributions described by Frealign par file
#
# Alexis Rohou, February 2015
#
#help
#help frealign_plot_angular_distribution - plot hostograms of angular parameters
#help Usage: frealign_plot_angular_distribution <cycle> <class>
#help Control parameters must be set in local mparameters file
#help Requires gnuplot
#
if [ "${1}" == "" ]; then
  echo ""
  echo "ERROR: no cycle number given."
  echo "Terminating..."
  echo ""
  exit
fi

if [ "${2}" == "" ]; then
  echo ""
  echo "ERROR: no class number given."
  echo "Terminating..."
  echo ""
  exit
fi

working_directory=`pwd`

if [ ! -e mparameters ]; then
  echo ""
  echo "ERROR: no mparameters file."
  echo "Terminating..."
  echo ""
  exit
fi

SCRATCH=`grep scratch_dir mparameters | awk '{print $2}'`

if ( $status || "$SCRATCH" == "" ); then
  SCRATCH=${working_directory}/scratch
fi

if [ ! -d $SCRATCH ]; then
  mkdir $SCRATCH
fi
#
if [ ! -d $SCRATCH ]; then
  echo "ERROR: cannot create scratch directory"
  exit
fi

data_input=`grep data_input mparameters | awk '{print $2}'`

input_fn=${data_input}_${1}_r${2}.par

# Set output filename
output_fn=${input_fn%%.*}_angdist.pdf
output_fn=${output_fn##*/}

#
# Grab data from the par file
#
awk '$1 !~ /C/' $input_fn > $SCRATCH/tmp.txt


#
# Plots
#
cat << EOF > $SCRATCH/tmp.gnu
set border linewidth 1.5
set terminal pdfcairo dashed enhanced font 'Arial,9' size 12.0cm,4.0cm

set size 1,1
set output "${output_fn}"
set tics out nomirror
set style line 2 lc rgb "black" lt 1 lw 1.5 
set style fill solid 0.5 border rgb "black"
unset key

set multiplot layout 1,3

# Theta (out-of-plane tilt)
max=360.0
min=0.0
n=90
width=(max-min)/n
set xlabel 'Theta'
set ylabel 'Number of particles'
set xrange [min:max]
set yrange [0:]
set xtics min,(max-min)/4,max
set boxwidth width*1.0
bin(x,width)=width*floor(x/width)+width/2.0

plot "$SCRATCH/tmp.txt" using (bin(\$3,width)):(1.0) smooth freq with boxes ls 2 lc rgb "blue"

set xlabel 'Psi'
plot "$SCRATCH/tmp.txt" using (bin(\$2,width)):(1.0) smooth freq with boxes ls 2 lc rgb "blue"

set xlabel 'Phi'
plot "$SCRATCH/tmp.txt" using (bin(\$4,width)):(1.0) smooth freq with boxes ls 2 lc rgb "blue"

unset multiplot

EOF
gnuplot < $SCRATCH/tmp.gnu |& tee $SCRATCH/fig_lengths.log

echo "Output plot figure: $output_fn"
