#include "CreateSignalThread.h"

// Public
CreateSignalThread::CreateSignalThread(QString fu, double fr, double t, double s, QObject * parent) 
 : QThread(parent) {
	error="";
	func=fu;
	from=fr;
	to=t;
	step=s;
}

CreateSignalThread::~CreateSignalThread(){
	//??
}

Signal CreateSignalThread::getSignal() {return sig;}
bool CreateSignalThread::isOK(){return (error == "");}
QString CreateSignalThread::getErrorMsg(){return error;} 

// Protected
void CreateSignalThread::run(){

	// Init parser and define pi
	FunctionParser fparser;
	fparser.AddConstant("pi", 3.1415926535897932);
	fparser.AddFunction("u",u,1);
	fparser.AddFunction("d",d,1);
	
	// Parse Function (-1 is success)
	int res = fparser.Parse(func.toStdString().c_str(), "x");

	if(res > -1) {
		QString message=fparser.ErrorMsg();
		error=message+"\n(on character "+QString::number(res+1)+")";
		return;
	}

	// Eval
	
	double vals[1];
	
	// Create First Result
	vals[0] = from;

	for(vals[0] = from; vals[0] <= to; vals[0] += step){
		
		double result=fparser.Eval(vals);
		
		// Check for error
		if (fparser.EvalError()>0){
			//QString evalError="";
			switch (fparser.EvalError()){
			case 1: 
				error="division by zero";
				break;
			case 2: 
				error="sqrt error (sqrt of a negative value)";
				break;
			case 3: 
				error="log error (logarithm of a negative value)";
				break;
			case 4: 
				error="trigonometric error (asin or acos of illegal value)";
				break;
			case 5: 
				error="maximum recursion level in eval() reached";
				break;
			default: 
				error="UnKnown Eval Error... Nothing to do... Sorry";
				break;
			}
			return;
		}
		
		
		sig+=Point(vals[0],result);

	}
	
	if (sig.size()<2) {
		error="Input results a single Point...\nNothing to draw.. Sorry.";
		return;
	}
} 
