
A tricky algorithm for on-the-fly frequency calibration

This one runs much faster than calfreq and works
with low signal to noise ratio and/or a lot of noise.

The idea is to 

* have a capture, 
* wait a bit and find the location of the most intense pulse train inside
* have another capture
* measure elapsed time and
* again find the location of the most intense pulse train inside.

If freqeuncy is just right, the position will be steady, but if frequency is slightly wrong,
the position of the strongest pulse train will move. If your pulse trains have roughly same intensity,
then take master pulse trains into account only.


Derivation of frequency calculation:

Idea: Measure shift "dt" over time range "tau" to find crystal frequency.

(1) dt_real = tau_real * (1 - f / 1MHz)
    f : Sampling frequency with current tack correction

But dt itself is measured with f:

(2) dt_real * 1 MHz = dt_measured * f
<=> dt_real = dt_measured * f / 1MHz

And tau is measured with uncorrected crystal frequency q:

(3) tau_real * 1 MHz = tau_measured * q
<=> tau_real = tau_measured * q / 1MHz

All frequencies are locked over PLL and dividers with the actual crystal frequency,
so that all relative frequency errors have to be the same.
It doesn't matter that the Timer for dt measurement runs at an integer multiply of q.

Tack calibration causes a fixed (but not integer) relation between q and f:

(4) f = q / (1 + 1 / (60*tack))
    tack : signed frequency correction value
    Define k := (1 + 1 / (60*tack)
<=> f = q/k

  In case of exact-crystal handler is in action it follows f = q and k = 1.

Insert (2) and (3) into (1):

(5) dt_measured * f/1MHz = tau_measured * q/1MHz * (1 - f / 1 MHz)

Delete f in (5) by inserting (4):

(6) dt_measured * q / (k * 1MHz) = tau_measured * q/1MHz * (1 - q / (k * 1MHz))
<=> dt_measured * 1/k            = tau_measured          * (1 - q / (k * 1MHz))
<=> dt_measured / (tau_measured * k) = 1 - q / (k * 1MHz)
<=> q / (k * 1MHz) = 1 - dt_measured / (tau_measured * k)
<=> q / 1MHz = k - dt_measured / tau_measured
<=> q = 1MHz * (k - dt_measured / tau_measured)

Now we have accurately determined the crystal frequency q.
