
// mup.cpp  -  This code uses the math parser library muParser v1.07c        //
// from SourceForge Project: muParser - a fast math parser library           //
// http://sourceforge.net/projects/muparser/                                 //

#include <string.h>
//#include <math.h>
#include "muParser.h"

//double Milli(double n) {return n / 1000.0;}
//double Rnd(double n) {return n * rand() / (RAND_MAX + 1.0);}
//double Sign(double n) {return -n;}
//parser.AddPostfixOp("m", Milli); // Add user defined unary operator
//parser.AddPrefixOp("-", Sign); // Add user defined unary operator
//parser.AddFun("rnd", Rnd, false); // Add an unoptimizeable function
//parser.EnableOptimizer(true); // Set optimizer state (defaults to true)

MathUtils::Parser parser; // Parser class
char parser_error[128] = ""; // Error string buffer

// muParser DLL Exported Functions

#define EXPORT __declspec(dllexport) __stdcall

int EXPORT GetErrorPointer(void){
	// Retrieves the error string pointer
	
	return (int) &parser_error[0];
	
	}

int EXPORT GetError(char *Buffer, int Length){
	// Copies the error string to a buffer or returns the length of the error string
	
	if(!Length || !Buffer)
		return strlen(&parser_error[0]);
	strncpy(Buffer, &parser_error[0], Length);
	return Length;
	
	}

void EXPORT ClearError(void){
	// Clears the error string
	
	parser_error[0] = 0;
	
	}

int EXPORT IsError(void){
	// Returns 0 if there is no error or -1 if there is an error
	
	if(parser_error[0])
		return -1;
	return 0;
	
	}

void EXPORT AddVariable(const char *Name, double *Var){
	// Assigns a variable name and binds it to a double type variable
	
    try{
		parser.AddVar(Name, Var);
	}catch(MathUtils::ParserException &e){
		strcpy(parser_error, e.what());
		}
	
	}

void EXPORT Parse(const char *Formula){
	// Parses a formula
	
    try{
		parser.SetFormula(Formula);
	}catch(MathUtils::ParserException &e){
		strcpy(parser_error, e.what());
		}
	
	}

double EXPORT Calculate(){
	// Calculates the formula
	
    try{
		return parser.Calc();
	}catch(MathUtils::ParserException &e){
		strcpy(parser_error, e.what());
		}
	return 0;

	}
