/**
 *  FiltFilt - Zero-phase digital filtering
 *  From matlab documentation:
 *      y = filtfilt(b,a,x)
 *  Performs zero-phase digital filtering by processing the
 *  input data, x, in both the forward and reverse directions
 *  The valarray b provides the numerator coefficients of the
 *  filter and the valarray a provides the denominator coefficients.
 *  If you use an all-pole filter, enter 1 for b.
 *  If you use an all-zero filter (FIR), enter 1 for a.
 *  After filtering the data in the forward direction, filtfilt
 *  reverses the filtered sequence and runs it back through the filter.
 *  The result has the following characteristics:
 *      -   Zero-phase distortion
 *      -   A filter transfer function, which equals the squared
 *          magnitude of the original filter transfer function
 *      -   A filter order that is double the order of the filter
 *          specified by b and a
 *
 *  FiltFilt attempts to minimize start-up transients by adjusting the
 *  initial conditions to match the DC component of the signal
 *  The algorithm also prepends several filter lengths of a flipped,
 *  reflected copy of the input signal.
 */

#include <assert.h>
#include <iostream>
#include <math.h>
// #include <limits.h>
#include <iocsh.h>
#include <registryFunction.h>
#include <epicsExport.h>
#include <aSubRecord.h>

#include "FiltFilt.h"
#include "ContextTimer.h"

using   namespace   std;

#ifndef MAX
#define	MAX(a,b)	(((a)>(b))?(a):(b))
#define	MIN(a,b)	(((a)<(b))?(a):(b))
#endif

#undef          DEBUG
//	#define     DEBUG       1
int				DEBUG_FILT_FILT	= 0;


///	Number of times FiltFilt() has been called since bootup
uint32_t		nCalcFiltFilt		= 0;

///	Average FiltFilt() duration in ms
uint32_t		avgCalcFiltFiltms	= 0;

///	Last FiltFilt() duration in ms
uint32_t		lastCalcFiltFiltms	= 0;

///	Cumulative FiltFilt() times (double in sec)
double		cumCalcFiltFilt		= 0.0;

/// Show FiltFilt calculation statistics
extern "C" uint32_t	ShowCalcFiltFilt( )
{
	cout <<	"FiltFilt() called " << nCalcFiltFilt << " times." << endl;
	if ( nCalcFiltFilt > 0 )
		cout <<	"Average    duration = " << (cumCalcFiltFilt / nCalcFiltFilt) * 1000.0 << " ms" << endl;
	cout <<	"Cumulative duration = " << cumCalcFiltFilt * 1000.0 << " ms" << endl;
	return 0;
}


///	ProcessFilt
/// Process input waveform using a 3rd order
/// butterworth digital filter.
///
///	Inputs:
///	A	- Input Waveform
///     - Coef A0 is always 1.0000
///	B	- Coef A1
///	C	- Coef A2
///	D	- Coef A3
///	E	- Coef B0
///	F	- Coef B1
///	G	- Coef B2
///	H	- Coef B3
///
///	Outputs:
///	A	- Output Waveform
extern "C" long ProcessFilt( aSubRecord	* pSub)
{
	if ( DEBUG_FILT_FILT >= 2 )
		printf(	"ProcessFilt: Reading %d values from input A ...\n", pSub->noa );

	valarray<double>    inputWaveform;
	inputWaveform.resize( pSub->noa );
	double			*	pArray	= static_cast<double *>( pSub->a );
	for ( size_t i = 0; i < pSub->noa; i++ )
		inputWaveform[i] = *pArray++;

	valarray<double>    butterworthCoefA;
	butterworthCoefA.resize( 4 );
	butterworthCoefA[0] = 1.0;
	butterworthCoefA[1] = *static_cast<double *>( pSub->b );
	butterworthCoefA[2] = *static_cast<double *>( pSub->c );
	butterworthCoefA[3] = *static_cast<double *>( pSub->d );

	valarray<double>    butterworthCoefB;
	butterworthCoefB.resize( 4 );
	butterworthCoefB[0] = *static_cast<double *>( pSub->e );
	butterworthCoefB[1] = *static_cast<double *>( pSub->f );
	butterworthCoefB[2] = *static_cast<double *>( pSub->g );
	butterworthCoefB[3] = *static_cast<double *>( pSub->h );

	valarray<double>    outputWaveform;
	outputWaveform.resize( pSub->nova );

	// Do the filtering
	Filt(	butterworthCoefA, butterworthCoefB,
			inputWaveform, outputWaveform, false );

	// Output results
	double	*	pOut	= static_cast<double *>( pSub->vala );
	for ( size_t i = 0; i < pSub->noa && i < pSub->nova; i++ )
		*pOut++ = outputWaveform[i];

	if ( DEBUG_FILT_FILT >= 2 )
		printf(	"ProcessFilt: Wrote %d values to output A\n", pSub->nova );

	return 0;
}


///	ProcessFiltFilt
/// Process input waveform using a 3rd order
/// zero phase butterworth digital filter,
/// implemented by running a standard butterworth
/// filter in one direction, then reversing it
/// to zero the phase changes.
///
///	Inputs:
///	A	- Input Waveform
///     - Coef A0 is always 1.0000
///	B	- Coef A1
///	C	- Coef A2
///	D	- Coef A3
///	E	- Coef B0
///	F	- Coef B1
///	G	- Coef B2
///	H	- Coef B3
///
///	Outputs:
///	A	- Output Waveform
extern "C" long ProcessFiltFilt( aSubRecord	* pSub)
{
	if ( DEBUG_FILT_FILT >= 1 )
		printf(	"ProcessFiltFilt:\n" );

	valarray<double>    inputWaveform;
	inputWaveform.resize( pSub->noa );
	double			*	pArray	= static_cast<double *>( pSub->a );
	for ( size_t i = 0; i < pSub->noa; i++ )
		inputWaveform[i] = *pArray++;

	valarray<double>    butterworthCoefA;
	butterworthCoefA[0] = 1.0;
	butterworthCoefA[1] = *static_cast<double *>( pSub->b );
	butterworthCoefA[2] = *static_cast<double *>( pSub->c );
	butterworthCoefA[3] = *static_cast<double *>( pSub->d );

	valarray<double>    butterworthCoefB;
	butterworthCoefB[0] = *static_cast<double *>( pSub->e );
	butterworthCoefB[1] = *static_cast<double *>( pSub->f );
	butterworthCoefB[2] = *static_cast<double *>( pSub->g );
	butterworthCoefB[3] = *static_cast<double *>( pSub->h );

	valarray<double>    outputWaveform;
	outputWaveform.resize( pSub->nova );

	// Do the filtering
	FiltFilt(	butterworthCoefA, butterworthCoefB,
				inputWaveform, outputWaveform, false );

	// Output results
	double	*	pOut	= static_cast<double *>( pSub->vala );
	for ( size_t i = 0; i < pSub->noa && i < pSub->nova; i++ )
		*pOut++ = outputWaveform[i];

	// if ( DEBUG_FILT_FILT >= 1 )
	// 	printf( "QE = %e\n", QE );

	return 0;
}


inline void ApplyA(
    valarray<double>        &   y1,
    size_t                      iy1,
    valarray<double> const  &   a,
    size_t                      ia,
    valarray<double> const  &   y2,
    size_t                      iy2,
    char             const  *   pPrompt )
{
#ifdef  DEBUG
    if ( iy1 >= y1.size() )
        cout << string(pPrompt) << ": Accessing y1[" << iy1 << "]" << endl;
    if ( ia  >= a.size() )
        cout << string(pPrompt) << ": Accessing a["  << ia  << "]" << endl;
    if ( iy2 >= y2.size() )
        cout << string(pPrompt) << ": Accessing y2[" << iy2 << "]" << endl;

	if ( DEBUG_FILT_FILT > 2 )
		cout    << string(pPrompt)
				<< ": alg  y["  << iy1     << "] += - a[" << ia    << "] * y[" << iy2     << "]"
				<< ", "         << y1[iy1] <<  " += "     <<-a[ia] <<  " * "   << y2[iy2]
				<< " = "        <<(y1[iy1] + -a[ia] * y2[iy2] ) << endl;
#endif  //  DEBUG

    y1[iy1] +=  -a[ia] * y2[iy2];
}


inline void ApplyB(
    valarray<double>        &   y,
    size_t                      iy,
    valarray<double> const &    b,
    size_t                      ib,
    valarray<double> const &    x,
    size_t                      ix,
    char             const *    pPrompt )
{
#ifdef  DEBUG
    if ( iy >= y.size() )
        cout << string(pPrompt) << ": Accessing y[" << iy << "]" << endl;
    if ( ib >= b.size() )
        cout << string(pPrompt) << ": Accessing b[" << ib << "]" << endl;
    if ( ix >= x.size() )
        cout << string(pPrompt) << ": Accessing x[" << ix << "]" << endl;

	if ( DEBUG_FILT_FILT > 2 )
		cout    << string(pPrompt)
				<< ": alg  y["  << iy    << "] +=   b[" << ib    << "] * x[" << ix    << "]"
				<< ", "         << y[iy] << " += "      << b[ib] << " * "    << x[ix]
				<< " = "        <<(y[iy] + b[ib] * x[ix]) << endl;
#endif  //  DEBUG

    y[iy]   +=  b[ib] * x[ix];
}


int Filt(
	std::valarray<double>	const	&	a,
	std::valarray<double>	const	&	b,
	std::valarray<double>	const	&	x,
	std::valarray<double>			&	y,
	bool								zeroStartup	)
{
//	ContextTimer(   "Filt" );

    if ( a.size() != b.size() || 
         x.size() != y.size()   )
		return -1;

    uint32_t    np  = x.size();
#ifdef  DEBUG
	if ( DEBUG_FILT_FILT > 0 )
	{
		cout << "Filt: nCoef    = " << a.size() << endl;
		cout << "Filt: CoefA[0] = " << a[0] << endl;
		cout << "Filt: CoefA[1] = " << a[1] << endl;
		cout << "Filt: CoefA[2] = " << a[2] << endl;
		cout << "Filt: CoefA[3] = " << a[3] << endl;
		cout << "Filt: CoefB[0] = " << b[0] << endl;
		cout << "Filt: CoefB[1] = " << b[1] << endl;
		cout << "Filt: CoefB[2] = " << b[2] << endl;
		cout << "Filt: CoefB[3] = " << b[3] << endl;
		cout << "Filt: nPnts    = " << np   << endl;
	}
#endif  //  DEBUG

	if ( zeroStartup )
	{
		//  First loop handles initial startup transients
		//  by skipping terms that would reference values
		//  before the start of the array, in effect using
		//  zero for those values.
		//  This matches well for our phase cavity calculations,
		//	as the initial values are typically zero
		for ( uint32_t i = 0; i < a.size(); i++ )
		{
			y[i]    = 0.0;

			//  y = sum prior ord samples scaled by coef B
			for (   uint32_t j = 0; j < i + 1;  j++ )
			{
				ApplyB( y, i, b, j, x, i - j, "Filt pass 1B" );
				//  y[i]    +=  b[j] * x[ i - j ];
			}

			//  Add in prior samples scaled by coef A
			for (   uint32_t j = 0; j < i; j++ )
			{
				ApplyA( y, i, a, j + 1, y, i - j - 1, "Filt pass 1A" );
				//  y[i]    += -a[ j + 1 ] * y[ i - j - 1 ];
			}
		}

		//  This loop handles the normal points where all
		//  the prior data points we need are available.
		//  i.e.    x[i - j] and y[i - j - 1]
		for (       uint32_t i = a.size(); i < np; i++ )
		{
			y[i]    = 0.0;
			for (   uint32_t j = 0; j < b.size(); j++ )
			{
				ApplyB( y, i, b, j, x, i - j, "Filt pass 2B" );
				//  y[i]    +=  b[j] * x[i - j];
			}
			for (   uint32_t j = 0; j < b.size() - 1; j++ )
			{
				ApplyA( y, i, a, j + 1, y, i - j - 1, "Filt pass 2A" );
				//  y[i] += -a[j + 1] * y[i - j - 1];
			}
		}
	}
	else
	{
		//  Do the filter using the average of the first few values
		//	in place of the missing prior values
		double			initVal	= 0.0;
		unsigned int	nValues	= 0;
		for ( uint32_t i = 0; i < a.size() && i < np; i++ )
		{
			initVal	+= x[i];
			nValues++;
		}
		initVal /= nValues;

		for ( uint32_t i = 0; i < np; i++ )
		{
			if ( i < b.size() )
			{
				y[i]	= initVal;
				continue;
			}

			y[i]    = 0.0;
			for (   uint32_t j = 0; j < b.size(); j++ )
			{
				ApplyB( y, i, b, j, x, i-j, "Filt pass 2B" );
				//  y[i]    +=  b[j] * x[i-j];
			}
			for (   uint32_t j = 0; j < b.size() - 1; j++ )
			{
				ApplyA( y, i, a, j + 1, y, i - j - 1, "Filt pass 2A" );
				//  y[i] += -a[j + 1] * y[i - j - 1];
			}
		}

		if ( DEBUG_FILT_FILT > 1 )
		{
			for ( uint32_t i = 0; i < np; i++ )
			{
				printf( "y[%d] = %f = f( %f )\n", i, y[i], x[i] );
			}
		}
	}

    return 0;
}

 

int FiltFilt(
	std::valarray<double>	const	&	a,
	std::valarray<double>	const	&	b,
	std::valarray<double>	const	&	x,
	std::valarray<double>			&	y,
	bool								zeroStartup	)
{
	double	startTime	= ContextTimer::GetCurTime();

	if (a.size() != b.size() || 
		x.size() != y.size())
		return -1;

	Filt(a, b, x, y, zeroStartup );  // NOW y=filter(b,a,x);

	uint32_t np = x.size();
	std::valarray<double> tmp(np);
	for ( uint32_t i = 0; i < np; i++ )
		tmp[i]  = y[ np - i - 1 ]; // reverse the array for FILTFILT

	Filt(a, b, tmp, y, zeroStartup ); // do FILTER again 

	// Restore original order
	for ( uint32_t i = 0; i < np; i++ )
		tmp[i]  = y[ np - i - 1 ]; // finally reverses the array
	y = tmp;

	//	Update CalcFiltFilt statistics
	double	calcTime = ContextTimer::GetCurTime() - startTime;
	nCalcFiltFilt++;
	cumCalcFiltFilt		+=	calcTime;
	if ( nCalcFiltFilt > 0 )
		avgCalcFiltFiltms	= static_cast<uint32_t>( (cumCalcFiltFilt / nCalcFiltFilt) * 1000.0 );

	return 0;
}


int	arrayStats::calcArrayStats( std::valarray<double>	const	&	array )
{
	if ( array.size() == 0 )
		return -1;

	double			sumX	= 0.0;
	double			sumY	= 0.0;
	double			sumXX	= 0.0;
	double			sumXY	= 0.0;
	double			sumYY	= 0.0;

	// Start from defaults
	m_rms		= 0.0;
	m_min		= LONG_MAX;
	m_max		= LONG_MIN;
	m_avg		= 0.0;
	m_stdDev	= 0.0;
	m_slope		= 0.0;
	m_offset	= 0.0;

	//	First pass:
	//	Get min, max, and info for linear fit
	for ( size_t i = 0; i < array.size(); ++i )
	{
		double		dblVal	= array[i];
		m_min	= min( dblVal, m_min );
		m_max	= max( dblVal, m_max );

		// Sums needed for least squares regression
		sumX	+= i;
		sumXX	+= i * i;
		sumXY	+= i * dblVal;
		sumY	+= dblVal;
		sumYY	+= dblVal * dblVal;
	}
	m_rms	=	sqrt( sumYY / array.size() );
	m_avg	=	sumY / array.size();

	//	Calc stdDev relative to avg
	for ( size_t i = 0; i < array.size(); ++i )
	{
		double		dblVal	= array[i] - m_avg;
		m_stdDev += (dblVal * dblVal);
	}
	m_stdDev	=	sqrt( m_stdDev / array.size() );

	// Calculate the least squares regression
	//	http://en.wikipedia.org/wiki/Simple_linear_regression
	m_slope	=	(	(array.size() * sumXY - sumX * sumY)
				/	(array.size() * sumXX - sumX * sumX) );
	m_offset	= (	sumY - m_slope * sumX ) / array.size();
	return 0;
}


// Register ShowCalcFiltFilt
static const	iocshFuncDef	ShowCalcFiltFilt_FuncDef = { "ShowCalcFiltFilt", 0, NULL };
static void		ShowCalcFiltFilt_CallFunc( const iocshArgBuf * args )
{
	ShowCalcFiltFilt( );
}
static void ShowCalcFiltFilt_Register( void )
{
	iocshRegister( &ShowCalcFiltFilt_FuncDef, ShowCalcFiltFilt_CallFunc );
}
epicsExportRegistrar(	ShowCalcFiltFilt_Register	);
epicsRegisterFunction(	ShowCalcFiltFilt	);

// Register aSub functions
extern "C" {

epicsRegisterFunction( ProcessFilt );
epicsRegisterFunction( ProcessFiltFilt );

epicsExportAddress( int, DEBUG_FILT_FILT );
}

