void BaselineDialog::createBaseline()
{
	ApplicationWindow *app = (ApplicationWindow *)parent();
	QPen pen = QPen(Qt::red);

	if (d_baseline){
		pen = d_baseline->pen();
		graph->removeCurve(d_baseline->title().text());
		delete d_baseline;
		d_baseline = NULL;

		if (d_table){
			d_table->askOnCloseEvent(false);
			app->closeWindow(d_table);
			d_table = NULL;
		}
	}

	disableBaselineTool();

	if (btnAutomatic->isChecked()){
		Interpolation *i = new Interpolation(app, graph, boxInputName->currentText(), boxInterpolationMethod->currentIndex());
		i->setOutputPoints(boxPoints->value());
		i->run();
		delete i;
		d_baseline = graph->dataCurve(graph->curveCount() - 1);
		d_table = ((DataCurve *)d_baseline)->table();
	} else if (btnEquation->isChecked()){
		double start = graph->axisScaleDiv(QwtPlot::xBottom)->lowerBound();
		double end = graph->axisScaleDiv(QwtPlot::xBottom)->upperBound();
		DataCurve *c = graph->dataCurve(graph->curveIndex(boxInputName->currentText()));
		if (c){
			start = c->minXValue();
			end = c->maxXValue();
		}
		d_baseline = graph->addFunction(QStringList() << boxEquation->text(), start, end, boxPoints->value(), "x", FunctionCurve::Normal, tr("Baseline"));
	} else if (btnDataset->isChecked()){
		Table *t = app->table(boxTableName->currentText());
		if (t){
			int rows = t->numRows();
			d_table = app->newTable(rows, 2);
			app->setWindowName(d_table, tr("Baseline"));
			app->hideWindow(d_table);
			int ycol = t->colIndex(boxColumnName->currentText());
			int xcol = t->colX(ycol);
			for (int i = 0; i < rows; i++){
				d_table->setText(i, 0, t->text(i, xcol));
				d_table->setText(i, 1, t->text(i, ycol));
			}
			d_baseline = graph->insertCurve(d_table, d_table->objectName() + "_2", Graph::Line, 0, -1);
			graph->setAutoScale();
		}
	}

	if (d_baseline){
		d_baseline->setPen(pen);
		graph->replot();
	}
}