#!/bin/bash

# define default project parameters.
prj=null
ver=1
rev=0

# source the project parameter file.
source proj

# check if the raw output file exists.
if [ ! -e ${prj}.raw ]; then
  # it does not. run ngspice to create it.
  ngspice -b ${prj}.spi -r ${prj}.raw
fi

# check if the simulation output file exists.
if [ ! -e ${prj}-sim.txt ]; then
  # it does not. run ngnutmeg to create it.
  ngnutmeg ${prj}.raw < ${prj}.nut

  # rip all numbers from the raw output file.
  awk '/^[0-9]/' tmp > tmp2 && mv tmp2 tmp
  f1=$(awk '/^\.ac/ {print $4}' ${prj}.spi)
  f2=$(awk '/^\.ac/ {print $5}' ${prj}.spi)
  n=$(wc -l < tmp)

  # if a frequency analysis was performed, re-output the analysis with a
  # correctly formed frequency axis.
  if [ ! "${f1}" == "" -a ! "${f2}" == "" -a ! "${n}" == "" ]; then
    cat | octave -qf > tmp2 << EOF
idx = [0 : (${n} - 1)]';
frq = logspace(log10(${f1}), log10(${f2}), ${n})';
for i = [1 : ${n}]
  printf('%d %e\n', idx(i), frq(i));
end
EOF

    # join the frequency analysis results with the computed frequency axis.
    join -j 1 tmp2 tmp > ${prj}-sim.txt
    rm -f tmp*
  else
    # load the analysis results and run a fourier transform.
    cat | octave -qf > tmp2 << EOF
x = load('tmp');
t = x(:, 2);
s = x(:, 3);
n = length(s);
dt = t(2) - t(1);
fmin = 1 / (n * dt);
fmax = 1 / dt;
f = linspace(fmin, fmax, n)';
S = 20 * log10(abs(fft(s .* blackman(length(s)))));
out = [f(1 : round(n / 2)), S(1 : round(n / 2))];
save -ascii '${prj}-sim.txt' out
EOF
    rm -f tmp*
  fi
fi

# check if measured results are available for comparison.
if [ -e ${prj}-meas.txt -a ! -e ${prj}.png ]; then
  # yes, they are. plot the two sets of results together.
  gnuplot ${prj}.plt
fi

