#include <string>
#include <cstring>
#include <iostream>
#include <sstream>
#include <valarray>

#include <epicsTypes.h>
#include <epicsThread.h>
#include <epicsExport.h>
#include <iocsh.h>
//#include <dbAccess.h>
//#include <dbAddr.h>
//#include <dbFldTypes.h>
#include <registryFunction.h>
#include <recGbl.h>
#include <alarm.h>
#include <aSubRecord.h>

#include "interp.h"
#include "gmd_data.h"


using namespace std;

#ifndef		MAX_PATH
#define		MAX_PATH	100
#endif	//	MAX_PATH

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

///Tables to interpolate cross section and mean charge values from photon energy

vector<tableEntry>	MeanChargeTableAr;
vector<tableEntry>	MeanChargeTableNe;
vector<tableEntry>	MeanChargeTableKr;
vector<tableEntry>	MeanChargeTableXe;
vector<tableEntry>	CrossSectionTableAr;
vector<tableEntry>	CrossSectionTableNe;
vector<tableEntry>	CrossSectionTableKr;
vector<tableEntry>	CrossSectionTableXe;


GasMonitorDetectorData gmdData;


int	DEBUG_GMD_SUBRECORD	= 1;

#define GMD_STS_OK 0


/// Constructor
GasMonitorDetectorData::GasMonitorDetectorData( )
	: m_rawData(		      ),
    	m_normalizedDataEvenOdd(      ),
    	m_normalizedDataRawBkgd(      ),
    	m_normalizedFilteredData(     ),
	m_dataSetNumber(	0     ),
	m_bgPerSampleEven(	0.0   ),
	m_bgPerSampleOdd(	0.0   ),
	m_Charge_Q( 		0.0   ),
	m_PhotonsPerPulse(	0.0   ),
	m_SumFiltBkgd(		0.0   ),
	m_SumRawBkgd(		0.0   ),
	m_multiplier(		0.0   ),
	m_energy(		0.0   ),
	m_meanCharge(		0.0   ),
	m_crossSection(		0.0   ),
	m_temp(			0.0   ),
	m_pressure(		0.0   ),
        m_effectiveLen(         0.0   ),
	m_K_Edge(		false ),
	m_L1_Edge(		false ),
	m_L2_Edge(		false ),
	m_L3_Edge(		false ),
	m_M1_Edge(		false ),
	m_M5_Edge(		false )
{
	return;
}

extern "C" long GMD_Init(	aSubRecord	* pSub)
{
	static	bool	isInitialized	= false;

	if ( isInitialized )
		return GMD_STS_OK;
	isInitialized	= true;

	if ( DEBUG_GMD_SUBRECORD >= 1 )
		cout	<< endl << "GMD_Init:  " << endl;

	readTable( MeanChargeTableAr,	"gasTables/Ar_mean_charge.dat" );
	readTable( CrossSectionTableAr,	"gasTables/Ar_cross_section.dat" );

	readTable( MeanChargeTableKr,	"gasTables/Kr_mean_charge.dat" );
	readTable( CrossSectionTableKr,	"gasTables/Kr_cross_section.dat" );

	readTable( MeanChargeTableNe,	"gasTables/Ne_mean_charge.dat" );
	readTable( CrossSectionTableNe,	"gasTables/Ne_cross_section.dat" );

	readTable( MeanChargeTableXe,	"gasTables/Xe_mean_charge.dat" );
	readTable( CrossSectionTableXe,	"gasTables/Xe_cross_section.dat" );

	return 0;
}

//	aSub process routine
//	ProcessWaveform monitors and processes each acqiris waveform
//	Inputs:
//	A	- Acqiris waveform (array of doubles)
//	B	- Left  index for background sample range
//	C	- Right index for background sample range
//	D	- Dig IIR Filter Smoothing factor (0 is no filtering, 1.0 never changes)
//	E	- Left  index for signal interval
//	F	- Right index for signal interval
//	Outputs:
//	A	- Raw Average background in this sample (bgPerSample)
//	B	- Filtered bgPerSample for Even Sample numbers
//	C	- Filtered bgPerSample for Odd Sample numbers
//	D	- Entire waveform normalized with even/odd filtered bkgd
//	E	- Entire waveform normalized and filtered w/ IIR for peak detection
//	F	- Left  bkgd   index waveform for gui
//	G	- Right bkgd   index waveform for gui
//	H	- Left  signal index waveform for gui
//	I	- Right signal index waveform for gui
//	J	- Max value in this waveform
//	K	- Min value in this waveform
//	NOT USED - Waveform Normalized waveform with this sample's avg bkgd
extern "C" long ProcessWaveform( aSubRecord	* pSub)
{
	int16_t	*	pRawData	= static_cast<int16_t *>(	pSub->a );
	size_t		bg_left		= *static_cast<int32_t *>(	pSub->b );
	size_t		bg_right	= *static_cast<int32_t *>(	pSub->c );
	double		smooth		= *static_cast<double *>(	pSub->d );
	size_t		sig_left	= *static_cast<int32_t *>(	pSub->e );
	size_t		sig_right	= *static_cast<int32_t *>(	pSub->f );
	int16_t		dataMax		= -32768;
	int16_t		dataMin		=  32767;

	// Increment the data set number
	gmdData.m_dataSetNumber++;

	if ( DEBUG_GMD_SUBRECORD >= 3 )
		cout	<< "ProcessWaveform:"
				<< " bg_left  = "	<<	bg_left
				<< " bg_right = "	<<	bg_right
				<< " smooth   = "	<<	smooth
				<< " sig_left  = "	<<	sig_left
				<< " sig_right = "	<<	sig_right
				<< endl;

	// Validate limits
	if (	bg_left		>= bg_right
		||	sig_left	>= sig_right
		||	(	sig_left	>= bg_left
			&&	sig_left	<= bg_right	)
		||	(	sig_right	>= bg_left
			&&	sig_right	<= bg_right	) )
	{
		static	unsigned int		throttle	= 0;
		if ( ( throttle++ % 2000 ) == 0 )
			cout	<< "ProcessWaveform Limit Overlap: "
					<< " bg_left  = "	<<	bg_left
					<< " bg_right = "	<<	bg_right
					<< " sig_left = "	<<	sig_left
					<< " sig_right = "	<<	sig_right
					<< endl;
		return 1;
	}

	//	Get Acqiris data; RAW WAVEFORM
	if( gmdData.m_rawData.size() != pSub->noa )
		gmdData.m_rawData.resize( pSub->noa );
	for ( size_t i = 0; i < pSub->noa; ++i )
		gmdData.m_rawData[i]= *pRawData++;

	// Compute a background value per sample by integrating over
	// a non-peak interval and dividing by the number of samples
	double	btotal		= 0;
	for ( size_t i = bg_left; i < bg_right; ++i )
		btotal += gmdData.m_rawData[i];
	double	bgPerSample		= btotal;
	if ( bg_right > bg_left )
		bgPerSample	/= (bg_right - bg_left);

	double	*	pFilteredBkgd;
	if ( gmdData.m_dataSetNumber & 1 )
		pFilteredBkgd = &gmdData.m_bgPerSampleOdd;
	else
		pFilteredBkgd = &gmdData.m_bgPerSampleEven;

	// Update the average background level using the smoothing filter
	double	bgPerSampleAvg	= *pFilteredBkgd;
	if( bgPerSampleAvg == 0.0 )
		bgPerSampleAvg	=	bgPerSample;	// startup shortcut
	bgPerSampleAvg	=	(	bgPerSampleAvg	* smooth
						+	bgPerSample		* (1.0 - smooth) );
	*pFilteredBkgd	= bgPerSampleAvg;

	// Normalize the waveform data by subtracting the avg background
	// and inverting it.
	if( gmdData.m_normalizedDataEvenOdd.size() != gmdData.m_rawData.size() )
	{
		gmdData.m_normalizedDataEvenOdd.resize(	gmdData.m_rawData.size() );
		gmdData.m_normalizedDataRawBkgd.resize(	gmdData.m_rawData.size() );
		gmdData.m_normalizedFilteredData.resize(gmdData.m_rawData.size() );
	}
	for ( size_t i = 0; i < gmdData.m_rawData.size(); ++i )
	{
		int16_t	dataVal						= 	gmdData.m_rawData[i];
		double	normalizedSampleRawBkgd		=	bgPerSample		- dataVal;
		gmdData.m_normalizedDataRawBkgd[i]	=	normalizedSampleRawBkgd;

		double	normalizedSampleEvenOdd		=	*pFilteredBkgd	- dataVal;
		gmdData.m_normalizedDataEvenOdd[i]	=	normalizedSampleEvenOdd;

		gmdData.m_normalizedFilteredData[i]	=	(	gmdData.m_normalizedFilteredData[i]	* smooth
												+	normalizedSampleEvenOdd		* (1.0 - smooth) );

		// Keep track of raw max and min
		if( dataMax < dataVal )
			dataMax = dataVal;
		if( dataMin > dataVal )
			dataMin = dataVal;
	}
	gmdData.m_signalLeft = sig_left;

	// Clear the integration sum in preparation for
	// processing one or more peaks
	gmdData.m_SumFiltBkgd	= 0.0;
	gmdData.m_SumRawBkgd	= 0.0;

	// Write scalar results to outputs
	*static_cast<double *>(	pSub->vala )= bgPerSample;
	*static_cast<double *>(	pSub->valb )= gmdData.m_bgPerSampleEven;
	*static_cast<double *>(	pSub->valc )= gmdData.m_bgPerSampleOdd;
	*static_cast<int32_t*>(	pSub->valj )= dataMax;
	*static_cast<int32_t*>(	pSub->valk )= dataMin;

	// Write array results to outputs
	size_t	sDataOut = MIN( pSub->novd, gmdData.m_normalizedDataEvenOdd.size() );
        memcpy( pSub->vald, &gmdData.m_normalizedDataEvenOdd[0],	sDataOut * sizeof(double) );
        memcpy( pSub->vale, &gmdData.m_normalizedFilteredData[0],  	sDataOut * sizeof(double) );
//	memcpy( pSub->val?, &gmdData.m_normalizedDataRawBkgd[0],	sDataOut * sizeof(double) );

	// Create waveforms for background and signal index traces on gui
	int16_t	*	pIndexOut;
	pIndexOut = static_cast<int16_t *>( pSub->valf );
	for ( size_t i = 0; i < pSub->novf; ++i )
		 *pIndexOut++ = i == bg_left ? 32767 : -32768;
	pIndexOut = static_cast<int16_t *>( pSub->valg );
	for ( size_t i = 0; i < pSub->novg; ++i )
		 *pIndexOut++ = i == bg_right ? 32767 : -32768;

	pIndexOut = static_cast<int16_t *>( pSub->valh );
	for ( size_t i = 0; i < pSub->novh; ++i )
		 *pIndexOut++ = i == sig_left ? 32767 : -32768;
	pIndexOut = static_cast<int16_t *>( pSub->vali );
	for ( size_t i = 0; i < pSub->novi; ++i )
		 *pIndexOut++ = i == sig_right ? 32767 : -32768;

	if ( DEBUG_GMD_SUBRECORD >= 3 )
		printf( "ProcessWaveform: avg bg = %f\n", *pFilteredBkgd );
	return 0;
}


//	ProcessPeak
//	Inputs:
//	A	- Left  index for peak
//	B	- Right index for peak
//	C	- Peak Enabled, Disabled=0, Enabled=1
//	Outputs:
//	A	- Sum of this peak normalized w/ filtered bkgd
//	B	- Cum sum of all peaks normalized w/ filtered bkgd
//	C	- Cum sum of all peaks normalized w/ un-filtered bkgd
//	D	- Left  bkgd   index waveform for gui
//	E	- Right bkgd   index waveform for gui
//	D	- Left  signal index waveform for gui
//	E	- Right signal index waveform for gui
extern "C" long ProcessPeak( aSubRecord	* pSub )
{
	size_t	left	= *static_cast<int32_t *> ( pSub->a );
	size_t	right	= *static_cast<int32_t *> ( pSub->b );
	size_t	enabled	= *static_cast<int32_t *> ( pSub->c );

	// Adjust by offset of signalLeft index in data set
	// as users select peak limits based on signalInterval.
	size_t	sig_left	= left  + gmdData.m_signalLeft;
	size_t	sig_right	= right + gmdData.m_signalLeft;

	// Clip to size of data set
	if( sig_left < 0 || sig_left >= gmdData.m_normalizedDataEvenOdd.size() )
		sig_left =  0;
	if( sig_right >= gmdData.m_normalizedDataEvenOdd.size() )
		sig_right =  gmdData.m_normalizedDataEvenOdd.size() - 1;

	double		dtotalFilt	= 0.0;
	double		dtotalRaw	= 0.0;

	if ( enabled )
	{
		// Compute the intergrated sum over the selected peak
		// If sig_left >= sig_right, peak is in use
		for ( size_t i = sig_left; i < sig_right; ++i )
		{
			dtotalFilt	+= gmdData.m_normalizedDataEvenOdd[i];
			dtotalRaw	+= gmdData.m_normalizedDataRawBkgd[i];
		}

		// Add in the contribution from this peak
		gmdData.m_SumFiltBkgd	+= dtotalFilt;
		gmdData.m_SumRawBkgd	+= dtotalRaw;
	}

	// Write results to outputs
	*static_cast<double *>(	pSub->vala ) = dtotalFilt;
	*static_cast<double *>(	pSub->valb ) = gmdData.m_SumFiltBkgd;
	*static_cast<double *>(	pSub->valc ) = gmdData.m_SumRawBkgd;

	// Create waveforms for peak index traces on gui
	int32_t	*	pDataOut;
	pDataOut = static_cast<int32_t *>( pSub->vald );
	for ( size_t i = 0; i < pSub->novd; ++i )
		 *pDataOut++ = ( enabled && i == left ) ? 65535 : 0;
	pDataOut = static_cast<int32_t *>( pSub->vale );
	for ( size_t i = 0; i < pSub->nove; ++i )
		 *pDataOut++ = ( enabled && i == right ) ? 65535 : 0;

	if ( DEBUG_GMD_SUBRECORD >= 5 )
		printf( "ProcessPeak: sum[%zu, %zu] = %e, cum %e\n",
				left, right, dtotalFilt, gmdData.m_SumFiltBkgd );
	return 0;
}


///	ProcessPulse
/// Calculate charge Q
///	Inputs:
///	A	- Sample interval for waveform
///	B	- Full scale voltage for 16 bit waveform
///	Outputs:
///	A	- Relative Pulse Charge Q
///	B	- Relative Pulse Intensity
///	C	- Est number of electrons collected by multiplier for this pulse
extern "C" long ProcessPulse( aSubRecord	* pSub)
{
	//	dt is sample interval of acqiris
	double		dt	 = *static_cast<double *> ( pSub->a );
	double		fullVolt = *static_cast<double *> ( pSub->b );
	const double 	R	 = 50.0; // Input resistance of acqiris
	double	crossSection	 = gmdData.m_crossSection;
	double	meanCharge	 = gmdData.m_meanCharge;
	double	temp		 = gmdData.m_temp;
	double	pressure	 = gmdData.m_pressure;
        double  effectiveLen     = gmdData.m_effectiveLen;

	gmdData.m_Charge_Q	= 0.0;
	gmdData.m_multiplier	= 0.0;
	double	numMultElec	= 0.0;

	if ( meanCharge != 0.0 && crossSection != 0.0 && pressure != 0.0 )
	{
		// Compute the charge Q using:
		// 		m_SumFiltBkgd, sum of peaks using filtered background level
		//		R, acqiris input resistance
		//		dt, acqiris sample interval
		double	fullCount	= 65536;
		double	cumVoltage	= gmdData.m_SumFiltBkgd * fullVolt / fullCount;
		gmdData.m_Charge_Q	= ( cumVoltage / R ) * dt;	// A * sec = coloumbs

		// Convert from columbs to number of electrons through the multiplier
		const double	elecCharge		= 1.602176487e-19;	// Standard Electron Charge
		numMultElec		= gmdData.m_Charge_Q / elecCharge;
		//	TODO:	Export numMultElec to a PV and add hist, archiving and autosaved limits
		//	TODO:	Add a normalized filtered version of m_SumFiltBkgd (sumAllPeaksFiltBkgd) to normalization screen
		//	TODO:	Move all multiplier limit related values (min,max, and numMultElec) to peak anal screen

		// Calc relative pulse intensity derived from acqiris waveform
		gmdData.m_multiplier =	(  ( 0.862 * gmdData.m_Charge_Q * temp )
					 / ( meanCharge * crossSection
					     * effectiveLen * pressure * 1e3 )); //formula 3
	}

	*static_cast<double *>(	pSub->vala )	= gmdData.m_Charge_Q;
	*static_cast<double *>( pSub->valb )	= gmdData.m_multiplier;
	*static_cast<double *>( pSub->valc )	= numMultElec;

	if ( DEBUG_GMD_SUBRECORD >= 4 )
		printf( "ProcessPulse: Mult Q = %.3g C, # Mult e = %.3g\n ", gmdData.m_Charge_Q, numMultElec );
	return 0;
}


///	ProcessKeithley
/// Calculate average pulse intensity from Keithley current reading
///	Inputs:
///	A	- Keithley current reading
///	B	- Detector temperature
///	C	- Detector pressure
///	D	- Pulse Rep Rate
///	E	- Effective length
///	F	- Seed factor for pulse-by-pulse calculation
///	Outputs:
///	A	- Average Photons Per Pulse
///	B	- Average Photons in mJ
///	C	- QE
///	D	- Pulse-by-pulse scaling factor
extern "C" long ProcessKeithley( aSubRecord	* pSub)
{
	double ion_current      = *static_cast<double *> ( pSub->a );	// Keithley current (A)
	double temp	        = *static_cast<double *> ( pSub->b );	// temp (C)
	double pressure	        = *static_cast<double *> ( pSub->c );	// pressure (mbar)
	double rep_rate	        = *static_cast<double *> ( pSub->d );	// LCLS rep rate
	double effectiveLen     = *static_cast<double *> ( pSub->e );	// Effective length (cm)
        double pulseScalingSeed = *static_cast<double *> ( pSub->f );   // See explanation about this by the end of the function
    // TODO: Make smoothing an input, even if init as a constant

	temp			+= 273.15; // Convert to Kelvin
	gmdData.m_temp		= temp;
        gmdData.m_effectiveLen  = effectiveLen;
	if ( isnan( pressure ) )
	{
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	// Smoothing factor for pressure
	double	smooth		= 0.00;
	gmdData.m_pressure	= gmdData.m_pressure * smooth + pressure * (1.0 - smooth);

	double	crossSection	= gmdData.m_crossSection;
	double	meanCharge	= gmdData.m_meanCharge;
	if ( DEBUG_GMD_SUBRECORD >= 2 )
		printf(	"ProcessKeithley: temp = %f, pressure = %g, energy = %g, effective length = %g, crossSection = %g, meanCharge = %g\n",
				gmdData.m_temp, gmdData.m_pressure, 
                                gmdData.m_energy, gmdData.m_effectiveLen,
                                crossSection, meanCharge );

	// Check for invalid values
	if ( meanCharge == 0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2 )
			printf( "Error: meanCharge = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	if ( crossSection == 0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2 )
			printf( "Error: crossSection = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	if ( pressure == 0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2)
			printf( "Error: pressure = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	if ( effectiveLen == 0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2)
			printf( "Error: effective length = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	if ( rep_rate==0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2)
			printf( "Error, rep rate = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	if ( isnan( ion_current ) )
	{
		if( DEBUG_GMD_SUBRECORD >= 2)
			printf( "Error, ion current is nan!\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	// Calc avg # of photons per pulse derived from Keithley
	gmdData.m_PhotonsPerPulse = (  ( 0.862 * ion_current * temp )
				     / ( meanCharge * crossSection
					 * effectiveLen * pressure * rep_rate ) );

	// Calc avg pulse energy in mJ
	const double elecCharge	= 1.602176487e-19; // Standard Electron Charge
	double	     photons_mJ	= ( gmdData.m_PhotonsPerPulse
				    * 1000 * elecCharge * gmdData.m_energy );

        gmdData.m_photons_mJ = photons_mJ;

	// Calculate quantum efficiency from Keithley
	double	QE	=	(	ion_current
					/	elecCharge
					/	rep_rate
					/	gmdData.m_PhotonsPerPulse	);

        // Calculation of the scaling factor for the pulse-by-pulse energy.
        // This will be used by the ATCA firmware. For the pulse-by-pulse we
        // don't use repetition rate, neither the ion_current, so we "remove"
        // them from the value of the photons_mj.
        double pulseScalingFactor = photons_mJ * rep_rate / ion_current;
        // The ATCA returns a number between 0 and 16, way different from the
        // Keithley current of e-12 current. We need this Seed factor that
        // will compensate for this difference.
        pulseScalingFactor *= pulseScalingSeed;

	*static_cast<double *>(pSub->vala) = gmdData.m_PhotonsPerPulse;
	*static_cast<double *>(pSub->valb) = photons_mJ;
	*static_cast<double *>(pSub->valc) = QE;
	*static_cast<double *>(pSub->vald) = pulseScalingFactor;

	if ( DEBUG_GMD_SUBRECORD >= 3 )
	{
		printf( "ProcessKeithley: sum = %e\n ", gmdData.m_PhotonsPerPulse );
		printf( "photons in mJ = %e\n", photons_mJ );
		printf( "QE = %e\n", QE );
	}

	recGblResetAlarms( pSub );
	return 0;
}


///	ProcessEnergy
/// Use beam energy to compute meanCharge, crossSection,
/// and edge flags
///
///	Inputs:
///	A	- Beam Energy
///	B	- Gas Type
///	C	- Manually entered Mean Charge
///	D	- Manually entered Cross Section
///	Outputs:
///	A	- Non-zero if near K_Edge
///	B	- Non-zero if near L1_Edge
///	C	- Non-zero if near L2_Edge
///	D	- Non-zero if near L3_Edge
///	E	- Non-zero if near M1_Edge
///	F	- Non-zero if near M5_Edge
///	G	- MeanCharge 
///	H	- Non-zero if MeanCharge derived from table
///	I	- CrossSection
///	J	- Non-zero if CrossSection derived from table
extern "C" long ProcessEnergy( aSubRecord	* pSub)
{
	double		energy	= *static_cast<double  *> (pSub->a);
	int32_t		gasType	= *static_cast<int32_t *> (pSub->b);

	if ( isnan( energy ) )
	{
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return 0;
	}

	if ( DEBUG_GMD_SUBRECORD >= 2 )
		printf( "ProcessEnergy: energy = %g\n", energy );

	gmdData.m_K_Edge	= false;
	gmdData.m_L1_Edge	= false;
	gmdData.m_L2_Edge	= false;
	gmdData.m_L3_Edge	= false;
	gmdData.m_M1_Edge	= false;
	gmdData.m_M5_Edge	= false;

	/// determine which tables to use based on gas type (read from SRG PV)
	vector <tableEntry> *pCrossSectionTable	= NULL;
	vector <tableEntry> *pMeanChargeTable	= NULL;
	switch (gasType)
	{
	case 19:
		if ( DEBUG_GMD_SUBRECORD >= 3 )
			printf ("Nitrogen %d\n", gasType);
		// Nitrogen has no gas table
		break;

	case 10:
		pCrossSectionTable	= &CrossSectionTableAr;
		pMeanChargeTable	= &MeanChargeTableAr;
		if ( DEBUG_GMD_SUBRECORD >= 3 )
			printf ("Argon %d\n", gasType);

		if (energy > 28.9 && energy < 30)
			gmdData.m_M1_Edge = true;
		if (energy > 244.9 && energy < 246)
			gmdData.m_L3_Edge = true;
		if (energy > 247 && energy < 248)
			gmdData.m_L2_Edge = true;
		if (energy > 319 && energy < 321)
			gmdData.m_L1_Edge = true;
		if (energy > 3201 && energy < 3203)
			gmdData.m_K_Edge = true;
		break;

	case 3:
		pCrossSectionTable	= &CrossSectionTableKr;
		pMeanChargeTable	= &MeanChargeTableKr;
		if ( DEBUG_GMD_SUBRECORD >= 3 )
			printf ("Krypton %d\n", gasType);

		if (energy > 93 && energy < 95)
			gmdData.m_M5_Edge = true;
		if (energy > 292 && energy < 294)
			gmdData.m_M1_Edge = true;
		if (energy > 1674 && energy < 1676)
			gmdData.m_L3_Edge = true;
		if (energy > 1726 && energy < 1728)
			gmdData.m_L2_Edge = true;
		if (energy > 8200 && energy < 8225)
			gmdData.m_L1_Edge = true;
		if (energy > 14324 && energy < 14327)
			gmdData.m_K_Edge = true;
		break;
	
	case 21:
		pCrossSectionTable	= &CrossSectionTableNe;
		pMeanChargeTable	= &MeanChargeTableNe;
		if ( DEBUG_GMD_SUBRECORD >= 3 )
			printf ("Neon %d\n", gasType);

		if (energy > 17.5 && energy < 20)
			gmdData.m_L3_Edge = true;
		if (energy > 20.5 && energy < 22)
			gmdData.m_L2_Edge = true;
		if (energy > 44 && energy < 46)
			gmdData.m_L1_Edge = true;
		if (energy > 865 && energy < 868)
			gmdData.m_K_Edge = true;
		break;

	case 25:
		pCrossSectionTable	= &CrossSectionTableXe;
		pMeanChargeTable	= &MeanChargeTableXe;
		if ( DEBUG_GMD_SUBRECORD >= 3 )
			printf("Xenon %d\n", gasType);

		if (energy > 675 && energy < 678)
			gmdData.m_M5_Edge = true;
		if (energy > 1146 && energy < 1150)
			gmdData.m_M1_Edge = true;
		if (energy > 4780 && energy < 4784)
			gmdData.m_L3_Edge = true;
		if (energy > 5100 && energy < 5105)
			gmdData.m_L2_Edge = true;
		if (energy > 5450 && energy < 5454)
			gmdData.m_L1_Edge = true;
		if (energy > 34560 && energy < 34563)
			gmdData.m_K_Edge = true;
		break;

	default:
		if ( DEBUG_GMD_SUBRECORD >= 2 )
			printf ("unknown gas type %d\n", gasType);
		// Unknown gas table
		break;
	}

	double	crossSection		= 0.0;
	double	meanCharge		= 0.0;
	bool	meanChargeFromTable	= true;
	bool	crossFromTable		= true;
	if ( pCrossSectionTable != NULL )
		interp( pCrossSectionTable, energy, crossSection );
	if ( pMeanChargeTable != NULL )
		interp( pMeanChargeTable,	energy, meanCharge );

	if ( meanCharge == 0.0 )
	{
		meanCharge          = *static_cast<double *>( pSub->c );
		meanChargeFromTable = false;
	}

	if ( crossSection == 0.0 )
	{
		crossSection	= *static_cast<double *>( pSub->d );
		crossFromTable	= false;
	}
	else
	{
		// CrossSection table is in megaBarns
		// Converting to cm**2
		crossSection	*= 1e-18;
	}

	// Smoothing factor for energy, meanCharge, and crossSection
	// TODO: Make smoothing an input, even if init as a constant
	double		smooth		= 0.0;
	gmdData.m_energy		= gmdData.m_energy		 * smooth + energy		 * (1.0 - smooth);
	gmdData.m_meanCharge	= gmdData.m_meanCharge	 * smooth + meanCharge	 * (1.0 - smooth);
	gmdData.m_crossSection	= gmdData.m_crossSection * smooth + crossSection * (1.0 - smooth);

	*static_cast<int32_t *>( pSub->vala) = gmdData.m_K_Edge;
	*static_cast<int32_t *>( pSub->valb) = gmdData.m_L1_Edge;
	*static_cast<int32_t *>( pSub->valc) = gmdData.m_L2_Edge;
	*static_cast<int32_t *>( pSub->vald) = gmdData.m_L3_Edge;
	*static_cast<int32_t *>( pSub->vale) = gmdData.m_M1_Edge;
	*static_cast<int32_t *>( pSub->valf) = gmdData.m_M5_Edge;

	*static_cast<double  *>( pSub->valg) = gmdData.m_meanCharge;
	*static_cast<int32_t *>( pSub->valh) = meanChargeFromTable;

	*static_cast<double  *>( pSub->vali) = gmdData.m_crossSection;
	*static_cast<int32_t *>( pSub->valj) = crossFromTable;

	if ( gmdData.m_meanCharge == 0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2)
			printf( "Error: meanCharge = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return -1;
	}
	if ( gmdData.m_crossSection == 0.0 )
	{
		if( DEBUG_GMD_SUBRECORD >= 2)
			printf( "Error: crossSection = 0\n");
		recGblSetSevr( pSub, CALC_ALARM, INVALID_ALARM );
		return -1;
	}

	if ( DEBUG_GMD_SUBRECORD >= 2 )
		printf( "ProcessEnergy: meanCharge = %g, crossSection = %g\n",
				gmdData.m_meanCharge, gmdData.m_crossSection );
	recGblResetAlarms( pSub );
	return 0;
}

extern "C" long SplitWaveform( aSubRecord * pSub )
{
    int16_t* pRawData = static_cast<int16_t*>( pSub->a );
    unsigned int* numSamples = static_cast<unsigned int*>( pSub->b );
    int16_t* pOutputA = static_cast<int16_t*>( pSub->vala );
    int16_t* pOutputB = static_cast<int16_t*>( pSub->valb );
    int16_t* pOutputC = static_cast<int16_t*>( pSub->valc );
    int16_t* pOutputD = static_cast<int16_t*>( pSub->vald );
    unsigned int iii;

    for (iii=0; iii < *numSamples; ++iii) {
        //printf("pRawData[%d] = %d\n", iii*4, pRawData[iii*4]);
        pOutputA[iii] = pRawData[iii*4];
        pOutputB[iii] = pRawData[iii*4+1];
        pOutputC[iii] = pRawData[iii*4+2];
        pOutputD[iii] = pRawData[iii*4+3];
        //printf("pOutputA[%d] = %d\n", iii, pOutputA[iii]);
        //printf("pSub->vala[%d] = %d\n", iii, static_cast<int16_t*>(pSub->vala)[iii]);
    }

    pSub->neva = pSub->nevb = pSub->nevc = pSub->nevd = *numSamples;

    return 0;
}

// Register aSub functions
extern "C" {

epicsRegisterFunction( GMD_Init );
epicsRegisterFunction( ProcessWaveform );
epicsRegisterFunction( ProcessPeak );
epicsRegisterFunction( ProcessPulse );
epicsRegisterFunction( ProcessKeithley );
epicsRegisterFunction( ProcessEnergy );
epicsRegisterFunction( SplitWaveform );

epicsExportAddress( int, DEBUG_GMD_SUBRECORD );
}

