#include <iostream>
#include <locale>
#include <fstream>
#include <string>
#include <vector>
#include <assert.h>
#include <epicsExport.h>

#include "interp.h"

using namespace std;

int		DEBUG_GMD_INTERP	= 0;

/// reads mean charge and cross section tables
int	readTable(
	vector<tableEntry>	&	table,
	const char			*	filename,
	bool					useGermanLocale )
{
	string		nextLine;
	ifstream	tableStream;
	int			linecount = 0;

	tableStream.open(filename);
	if ( useGermanLocale )
		tableStream.imbue( std::locale( "german" ) );

	while ( tableStream.good() )
	{
		if ( ++linecount <= 3 )
		{	// Skip first 3 lines
			getline( tableStream, nextLine );
			if ( DEBUG_GMD_INTERP >= 3 )
				cout << "Skipping line: " << nextLine << endl;
			continue;
		}

		// Parse the next entry
		tableEntry currentEntry( 0.0, 0.0, 0.0 );
		tableStream	>> currentEntry.wavelength
					>> currentEntry.energy
					>> currentEntry.value;
		if ( tableStream.eof() )
			break;

		if ( tableStream.fail() )
		{
			// Check for comment lines
			tableStream.clear();
			getline( tableStream, nextLine );
			size_t	firstNonSpace = nextLine.find_first_not_of( " \t\r\n" );
			if ( nextLine[firstNonSpace] == '#' )
			{
				if ( DEBUG_GMD_INTERP >= 3 )
					printf( "Skipping comments: %s\n", nextLine.c_str() );
				continue;
			}

			// Not a comment line, so generate an error message
			cout	<< "file: "					<< string(filename)
					<< ", Error parsing line "	<< linecount			<< endl;
			cout	<< "Bad line: '"	<<	nextLine	<< "'" << endl;
			continue;
		}

		// Arguments parsed successfully
		// Add entry to table
		table.push_back( currentEntry );

		if ( DEBUG_GMD_INTERP >= 3 )
		{
			cout	<< "file: "				<< string(filename)
					<< ", line "			<< linecount			<< endl;
			cout	<< "	wavelength = "	<< currentEntry.wavelength;
			cout	<< ", energy = "		<< currentEntry.energy;
			cout	<< ", value ="			<< currentEntry.value	<< endl;
		}
	}

	if ( DEBUG_GMD_INTERP >= 1 )
		cout	<< "readTable: Read " << table.size() << " entries from file: " << string(filename) << endl;
	return 0;
}

int  interp(
	vector<tableEntry>	*	pTable,
	double					energy,
	double				&	valueRet	)
{
	valueRet	 = 0.0;
	if ( pTable == NULL || pTable->size() <= 2 )
	{
		if ( DEBUG_GMD_INTERP >= 1 )
			printf( "interp error: Invalid table\n" );
		return -1;
	}

	// Table is assumed to be in ascending order, so the
	// target energy should be >= the first table entry.
	if ( energy < (*pTable)[0].energy )
	{
		if ( DEBUG_GMD_INTERP >= 1 )
			printf( "interp error: target energy %10.5f is less than first table entry %10.5f\n",
					energy, (*pTable)[0].energy );
		return -1;
	}

	for ( unsigned int i = 0; i < pTable->size(); i++ )
	{
		if ( energy > (*pTable)[i].energy )
			continue;

		if ( energy == (*pTable)[i].energy )
		{
			valueRet = (*pTable)[i].value;
			return 0;
		}

		double	energyBelow	= (*pTable)[i-1].energy;
		double	energyAbove	= (*pTable)[i].energy;
		double	valueBelow	= (*pTable)[i-1].value;
		double	valueAbove	= (*pTable)[i].value;

		//linear interpolation from table
		valueRet	=	valueBelow +
					(	(	energy		-	energyBelow	)
					*	(	valueAbove	-	valueBelow	)
					/	(	energyAbove	-	energyBelow	)	);

		if ( DEBUG_GMD_INTERP >= 4 )
		{
			printf( "interp: energyBelow = %10.5f, energyTarget = %10.5f, energyAbove = %10.5f\n",
				energyBelow, energy, 	energyAbove );
			printf( "interp: valueBelow  = %10.5f, valueTarget  = %10.5f, valueAbove  = %10.5f\n",
				valueBelow,  valueRet,  valueAbove );
		}
		assert( valueRet != 0.0 );
		return 0;
	}

	if ( DEBUG_GMD_INTERP >= 1 )
		printf ("interp error: energy %10.5f > table[MAX] %10.5f\n", energy, (*pTable)[pTable->size()-1].energy );
	return -1;
}


// Register Debug variable
extern "C" {
epicsExportAddress( int, DEBUG_GMD_INTERP );
}
