/*
 * Remote Laboratory Oscilloscope Part
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (c) 2012-2019 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

#include "define.h"
#include "part.h"

#ifdef HAVE_FFTS
#define ENABLE_FFT 1
#endif // HAVE_FFTS

#include <tdeaboutdata.h>   //::createAboutData()
#include <tdeaction.h>
#include <tdelocale.h>
#include <tdemessagebox.h>  //::start()
#include <tdefiledialog.h>
#include <tdeparts/genericfactory.h>
#include <kstatusbar.h>
#include <ktextedit.h>
#include <kstdaction.h>
#include <tqfile.h>        //encodeName()
#include <tqtimer.h>
#include <tqvbox.h>
#include <tqsocket.h>
#include <tqmutex.h>
#include <tqgroupbox.h>
#include <tqlayout.h>
#include <tqcombobox.h>
#include <tqcheckbox.h>
#include <tqpushbutton.h>
#include <tqeventloop.h>
#include <tqapplication.h>
#include <unistd.h>       //access()
#include <stdint.h>
#include <cmath>

#ifdef ENABLE_FFT
#include <ffts/ffts.h>
#endif // ENABLE_FFT

#include "tracewidget.h"
#include "floatspinbox.h"
#include "layout.h"

#define NETWORK_COMM_TIMEOUT_MS 15000

/* exception handling */
struct exit_exception {
	int c;
	exit_exception(int c):c(c) { }
};

enum connectionStates {
	ScopeState_InitialRequest			= 0,
	ScopeState_ResetRequest				= 2,
	ScopeState_HorizontalDivCountRequest		= 4,
	ScopeState_VerticalDivCountRequest		= 6,
	ScopeState_PermittedSecondsDivRequest		= 8,
	ScopeState_ChannelCountRequest			= 10,
	ScopeState_ChannelActiveStateRequest		= 12,
	ScopeState_TraceSampleCountRequest		= 14,
	ScopeState_TracePermittedVoltsDivRequest	= 16,
	ScopeState_TraceVoltsDivRequest			= 18,
	ScopeState_TraceSecondsDivRequest		= 20,
	ScopeState_HorizontalTimebaseRequest		= 22,
	ScopeState_TriggerChannelRequest		= 24,
	ScopeState_TriggerLevelRequest			= 26,
	ScopeState_RunningRequest			= 28,
	ScopeState_TraceRequest				= 50,
	ScopeState_ChannelActiveStateUpdate		= 100,
	ScopeState_TraceVoltsDivUpdate			= 102,
	ScopeState_TriggerChannelUpdate			= 104,
	ScopeState_TriggerLevelUpdate			= 106,
	ScopeState_HorizontalTimebaseUpdate		= 108,
	ScopeState_RunningUpdate			= 110,
	ScopeState_ExternalCommandRequest		= 255
};

#define ScopeState_ReloadSettings ScopeState_ChannelActiveStateRequest

namespace RemoteLab {

typedef KParts::GenericFactory<RemoteLab::ScopePart> Factory;
#define CLIENT_LIBRARY "libremotelab_scope"
K_EXPORT_COMPONENT_FACTORY( libremotelab_scope, RemoteLab::Factory )

TraceControlWidget::TraceControlWidget(TQWidget *parent, const char *name)
	: TQWidget(parent, name)
{
	TQGridLayout *topGrid = new TQGridLayout(this);
	m_groupBox = new TQGroupBox(this);
	m_groupBox->setColumnLayout(0, TQt::Vertical);
	topGrid->addMultiCellWidget(m_groupBox, 0, 0, 0, 0);
	m_groupBox->setTitle(i18n("Unknown Channel"));
	m_primaryLayout = new TQGridLayout(m_groupBox->layout(), 1, 1, KDialog::spacingHint());

	m_channelEnabledCheckBox = new TQCheckBox(m_groupBox);
	connect(m_channelEnabledCheckBox, SIGNAL(clicked()), this, SLOT(enableClicked()));
	m_channelEnabledCheckBox->setText(i18n("Enable"));
	m_primaryLayout->addMultiCellWidget(m_channelEnabledCheckBox, 0, 0, 0, 0);

	m_voltsDivComboBox = new TQComboBox(m_groupBox);
	connect(m_voltsDivComboBox, SIGNAL(activated(int)), this, SLOT(vdivChanged(int)));
	m_primaryLayout->addMultiCellWidget(m_voltsDivComboBox, 0, 0, 1, 1);

	TQLabel* label = new TQLabel(m_groupBox);
	label->setText(i18n("V/div"));
	m_primaryLayout->addMultiCellWidget(label, 0, 0, 2, 2);

	m_setTriggerChannelButton = new TQPushButton(m_groupBox);
	m_setTriggerChannelButton->setText(i18n("TRIG"));
	connect(m_setTriggerChannelButton, SIGNAL(clicked()), this, SLOT(triggerRequested()));
	m_primaryLayout->addMultiCellWidget(m_setTriggerChannelButton, 0, 0, 3, 3);
}

TraceControlWidget::~TraceControlWidget() {
	//
}

void TraceControlWidget::setVoltsPerDivList(TQDoubleList list) {
	m_voltsDivList = list;

	// Update drop down list
	double prevValue = m_voltsDivComboBox->currentText().toDouble();
	m_voltsDivComboBox->clear();
	TQDoubleList::iterator it;
	int i = 0;
	for (it = m_voltsDivList.begin(); it != m_voltsDivList.end(); ++it) {
		m_voltsDivComboBox->insertItem(TQString("%1").arg(*it), i);
		if (prevValue == (*it)) {
			m_voltsDivComboBox->setCurrentItem(i);
		}
		i++;
	}
}

void TraceControlWidget::setSelectedVoltsPerDiv(double vdiv) {
	int i = 0;
	for (i=0;i<m_voltsDivComboBox->count();i++) {
		if (m_voltsDivComboBox->text(i).toDouble() == vdiv) {
			m_voltsDivComboBox->setCurrentItem(i);
		}
	}
}

void TraceControlWidget::setTraceEnabled(bool enabled) {
	m_channelEnabledCheckBox->setChecked(enabled);
	m_voltsDivComboBox->setEnabled(enabled);
}

void TraceControlWidget::setTraceName(TQString name) {
	m_groupBox->setTitle(name);
}

void TraceControlWidget::setTriggerChannel(bool isTrigger) {
// 	m_setTriggerChannelButton->setEnabled(!isTrigger);
	m_setTriggerChannelButton->setDown(isTrigger);
}

void TraceControlWidget::enableClicked() {
	bool enabled = m_channelEnabledCheckBox->isOn();
	m_voltsDivComboBox->setEnabled(enabled);
	emit(enableChanged(enabled));
}

void TraceControlWidget::vdivChanged(int index) {
	Q_UNUSED(index)
	double value = m_voltsDivComboBox->currentText().toDouble();
	emit(voltsPerDivChanged(value));
}

void TraceControlWidget::triggerRequested() {
	emit(triggerChannelChangeRequested());
}

MathTraceControlWidget::MathTraceControlWidget(TQWidget *parent, const char *name)
	: TQWidget(parent, name)
{
	TQGridLayout *topGrid = new TQGridLayout(this);
	m_groupBox = new TQGroupBox(this);
	m_groupBox->setColumnLayout(0, TQt::Vertical);
	topGrid->addMultiCellWidget(m_groupBox, 0, 0, 0, 0);
	m_groupBox->setTitle(i18n("Unknown Math Channel"));
	m_primaryLayout = new TQGridLayout(m_groupBox->layout(), 1, 1, KDialog::spacingHint());

	m_channelEnabledCheckBox = new TQCheckBox(m_groupBox);
	connect(m_channelEnabledCheckBox, SIGNAL(clicked()), this, SLOT(enableClicked()));
	m_channelEnabledCheckBox->setText(i18n("Enable"));
	m_primaryLayout->addMultiCellWidget(m_channelEnabledCheckBox, 0, 0, 0, 0);

	m_voltsDivComboBox = new TQComboBox(m_groupBox);
	connect(m_voltsDivComboBox, SIGNAL(activated(int)), this, SLOT(vdivChanged(int)));
	m_primaryLayout->addMultiCellWidget(m_voltsDivComboBox, 0, 0, 1, 1);

	m_verticalUnitsLabel = new TQLabel(m_groupBox);
	m_verticalUnitsLabel->setText(i18n("V/div"));
	m_primaryLayout->addMultiCellWidget(m_verticalUnitsLabel, 0, 0, 2, 2);

	m_operandFirstComboBox = new TQComboBox(m_groupBox);
	connect(m_operandFirstComboBox, SIGNAL(activated(int)), this, SLOT(operandFirstChanged(int)));
	m_primaryLayout->addMultiCellWidget(m_operandFirstComboBox, 1, 1, 0, 0);

	m_operandSecondComboBox = new TQComboBox(m_groupBox);
	connect(m_operandSecondComboBox, SIGNAL(activated(int)), this, SLOT(operandSecondChanged(int)));
	m_primaryLayout->addMultiCellWidget(m_operandSecondComboBox, 1, 1, 2, 2);

	m_operatorComboBox = new TQComboBox(m_groupBox);
	connect(m_operatorComboBox, SIGNAL(activated(int)), this, SLOT(operatorChanged(int)));
	m_primaryLayout->addMultiCellWidget(m_operatorComboBox, 1, 1, 1, 1);
}

MathTraceControlWidget::~MathTraceControlWidget() {
	//
}

void MathTraceControlWidget::setVoltsPerDivList(TQDoubleList list) {
	m_voltsDivList = list;

	// Update drop down list
	double prevValue = m_voltsDivComboBox->currentText().toDouble();
	m_voltsDivComboBox->clear();
	TQDoubleList::iterator it;
	int i = 0;
	for (it = m_voltsDivList.begin(); it != m_voltsDivList.end(); ++it) {
		m_voltsDivComboBox->insertItem(TQString("%1").arg(*it), i);
		if (prevValue == (*it)) {
			m_voltsDivComboBox->setCurrentItem(i);
		}
		i++;
	}
}

void MathTraceControlWidget::setSelectedVoltsPerDiv(double vdiv) {
	int i = 0;
	for (i=0;i<m_voltsDivComboBox->count();i++) {
		if (m_voltsDivComboBox->text(i).toDouble() == vdiv) {
			m_voltsDivComboBox->setCurrentItem(i);
		}
	}
}

void MathTraceControlWidget::setFirstMathOperandList(TQInt16List list) {
	m_firstMathOperandList = list;

	// Update drop down list
	int prevValue = (m_operandFirstComboBox->currentText().replace("Ch", "")).toInt();
	m_operandFirstComboBox->clear();
	TQInt16List::iterator it;
	int i = 0;
	for (it = m_firstMathOperandList.begin(); it != m_firstMathOperandList.end(); ++it) {
		m_operandFirstComboBox->insertItem(TQString("Ch%1").arg(*it), i);
		if (prevValue == (*it)) {
			m_operandFirstComboBox->setCurrentItem(i);
		}
		i++;
	}
}

void MathTraceControlWidget::setSelectedFirstMathOperand(int channel) {
	int i = 0;
	for (i=0;i<m_operandFirstComboBox->count();i++) {
		if ((m_operandFirstComboBox->text(i).replace("Ch", "")).toInt() == channel) {
			m_operandFirstComboBox->setCurrentItem(i);
		}
	}
}

void MathTraceControlWidget::setSecondMathOperandList(TQInt16List list) {
	m_secondMathOperandList = list;

	// Update drop down list
	int prevValue = (m_operandSecondComboBox->currentText().replace("Ch", "")).toInt();
	m_operandSecondComboBox->clear();
	TQInt16List::iterator it;
	int i = 0;
	for (it = m_secondMathOperandList.begin(); it != m_secondMathOperandList.end(); ++it) {
		m_operandSecondComboBox->insertItem(TQString("Ch%1").arg(*it), i);
		if (prevValue == (*it)) {
			m_operandSecondComboBox->setCurrentItem(i);
		}
		i++;
	}
}

void MathTraceControlWidget::setSelectedSecondMathOperand(int channel) {
	int i = 0;
	for (i=0;i<m_operandSecondComboBox->count();i++) {
		if ((m_operandSecondComboBox->text(i).replace("Ch", "")).toInt() == channel) {
			m_operandSecondComboBox->setCurrentItem(i);
		}
	}
}

void MathTraceControlWidget::setMathOperatorList(MathOperatorList list) {
	m_mathOperatorList = list;

	// Update drop down list
	TQString prevValue = m_operatorComboBox->currentText();
	m_operatorComboBox->clear();
	MathOperatorList::iterator it;
	int i = 0;
	for (it = m_mathOperatorList.begin(); it != m_mathOperatorList.end(); ++it) {
		m_operatorComboBox->insertItem((*it).first, i);
		if (prevValue == (*it).first) {
			m_operatorComboBox->setCurrentItem(i);
		}
		i++;
	}
}

void MathTraceControlWidget::setSelectedMathOperator(TQString op) {
	int i = 0;
	for (i=0;i<m_operatorComboBox->count();i++) {
		if (m_operatorComboBox->text(i) == op) {
			m_operatorComboBox->setCurrentItem(i);
		}
	}

	updateMathOperatorOperandVisibility();
}

void MathTraceControlWidget::setTraceEnabled(bool enabled) {
	m_channelEnabledCheckBox->setChecked(enabled);
	m_voltsDivComboBox->setEnabled(enabled);
	m_operandFirstComboBox->setEnabled(enabled);
	m_operandSecondComboBox->setEnabled(enabled);
	m_operatorComboBox->setEnabled(enabled);
}

void MathTraceControlWidget::setTraceName(TQString name) {
	m_groupBox->setTitle(name);
}

void MathTraceControlWidget::setVerticalUnits(TQString units) {
	m_verticalUnitsLabel->setText(i18n("%1/div").arg(units));
}

void MathTraceControlWidget::enableClicked() {
	bool enabled = m_channelEnabledCheckBox->isOn();
	m_voltsDivComboBox->setEnabled(enabled);
	emit(enableChanged(enabled));
}

void MathTraceControlWidget::vdivChanged(int index) {
	Q_UNUSED(index)
	double value = m_voltsDivComboBox->currentText().toDouble();
	emit(voltsPerDivChanged(value));
}

void MathTraceControlWidget::operandFirstChanged(int index) {
	Q_UNUSED(index)
	double value = (m_operandFirstComboBox->currentText().replace("Ch", "")).toInt();
	emit(firstMathOperandChanged(value));
}

void MathTraceControlWidget::operandSecondChanged(int index) {
	Q_UNUSED(index)
	double value = (m_operandSecondComboBox->currentText().replace("Ch", "")).toInt();
	emit(secondMathOperandChanged(value));
}

void MathTraceControlWidget::operatorChanged(int index) {
	Q_UNUSED(index)
	updateMathOperatorOperandVisibility();
	emit(mathOperatorChanged(m_operatorComboBox->currentText()));
}

void MathTraceControlWidget::updateMathOperatorOperandVisibility() {
	TQString value = m_operatorComboBox->currentText();
	MathOperatorList::iterator it;
	for (it = m_mathOperatorList.begin(); it != m_mathOperatorList.end(); ++it) {
		if (value == (*it).first) {
			if ((*it).second < 2) {
				m_operandSecondComboBox->hide();
			}
			else {
				m_operandSecondComboBox->show();
			}
		}
	}
}

TimebaseControlWidget::TimebaseControlWidget(TQWidget *parent, const char *name)
	: TQWidget(parent, name)
{
	TQGridLayout *topGrid = new TQGridLayout(this);
	m_groupBox = new TQGroupBox(this);
	m_groupBox->setColumnLayout(0, TQt::Vertical);
	topGrid->addMultiCellWidget(m_groupBox, 0, 0, 0, 0);
	m_groupBox->setTitle(i18n("Timebase"));
	m_primaryLayout = new TQGridLayout(m_groupBox->layout(), 1, 1, KDialog::spacingHint());

	m_secondsDivComboBox = new TQComboBox(m_groupBox);
	connect(m_secondsDivComboBox, SIGNAL(activated(int)), this, SLOT(sdivChanged(int)));
	m_primaryLayout->addMultiCellWidget(m_secondsDivComboBox, 0, 0, 0, 0);

	TQLabel* label = new TQLabel(m_groupBox);
	label->setText(i18n("/div"));
	m_primaryLayout->addMultiCellWidget(label, 0, 0, 1, 1);
}

TimebaseControlWidget::~TimebaseControlWidget() {
	//
}

void TimebaseControlWidget::setSecondsPerDivList(TQDoubleList list) {
	m_secondsDivList = list;

	// Update drop down list
	double prevValue = m_secondsDivComboBox->currentText().toDouble();
	m_secondsDivComboBox->clear();
	TQDoubleList::iterator it;
	int i = 0;
	for (it = m_secondsDivList.begin(); it != m_secondsDivList.end(); ++it) {
		m_secondsDivComboBox->insertItem(TQString("%1").arg(TraceWidget::prettyFormat(*it, *it, "s", 3)), i);
		if (prevValue == (*it)) {
			m_secondsDivComboBox->setCurrentItem(i);
		}
		i++;
	}
}

void TimebaseControlWidget::setSelectedSecondsPerDiv(double sdiv) {
	int i = 0;
	for (i=0;i<m_secondsDivComboBox->count();i++) {
		if (m_secondsDivComboBox->text(i) == TraceWidget::prettyFormat(sdiv, sdiv, "s", 3)) {
			m_secondsDivComboBox->setCurrentItem(i);
		}
	}
}

void TimebaseControlWidget::sdivChanged(int index) {
	Q_UNUSED(index)
	double value = m_secondsDivList[m_secondsDivComboBox->currentItem()];
	emit(secondsPerDivChanged(value));
}

ScopePart::ScopePart( TQWidget *parentWidget, const char *widgetName, TQObject *parent, const char *name, const TQStringList& )
	: RemoteInstrumentPart( parent, name ), m_traceWidget(0), m_commHandlerState(-1), m_commHandlerMode(0), m_commHandlerCommandState(0), m_connectionActiveAndValid(false),
	m_tickerState(0), m_triggerChannel(-1), m_running(false), m_triggerLevel(0), m_settingsChanged(false), m_base(0), m_stopTraceUpdate(false)
{
	// Initialize important base class variables
	m_clientLibraryName = CLIENT_LIBRARY;

	// Initialize mutex
	m_instrumentMutex = new TQMutex(false);

	// Initialize kpart
	setInstance(Factory::instance());
	setWidget(new TQVBox(parentWidget, widgetName));

	// Create timers
	m_forcedUpdateTimer = new TQTimer(this);
	connect(m_forcedUpdateTimer, SIGNAL(timeout()), this, SLOT(mainEventLoop()));
	m_updateTimeoutTimer = new TQTimer(this);
	connect(m_updateTimeoutTimer, SIGNAL(timeout()), this, SLOT(mainEventLoop()));

	// Initialize data
	m_hdivs = 0;
	m_vdivs = 0;
	m_maxNumberOfTraces = 0;
	m_maxNumberOfMathTraces = 1;
	m_availableMathOperators.append(MathOperator("+", 2));
	m_availableMathOperators.append(MathOperator("-", 2));
	m_availableMathOperators.append(MathOperator("*", 2));
	m_availableMathOperators.append(MathOperator("/", 2));
#ifdef ENABLE_FFT
	m_availableMathOperators.append(MathOperator("FFT", 1));
#endif // ENABLE_FFT
	for (int traceno=0; traceno<=MAXTRACES; traceno++) {
		m_samplesInTrace[traceno] = 0;
		m_channelActive[traceno] = false;
		m_traceAllowedVoltsDiv[traceno].clear();
		m_voltsDiv[traceno] = 0;
		m_secsDiv[traceno] = 0;
		m_traceControlWidgetList[traceno] = NULL;

		m_voltsDivSet[traceno] = false;
		m_channelActiveSet[traceno] = false;
	}
	for (int traceno=0; traceno<=MAXMATHTRACES; traceno++) {
		m_samplesInMathTrace[traceno] = 0;
		m_mathChannelActive[traceno] = false;
		m_mathTraceAllowedVoltsDiv[traceno].clear();
		m_mathVoltsDiv[traceno] = 0;
		m_mathSecsDiv[traceno] = 0;
		m_mathFirstOperand[traceno] = 0;
		m_mathSecondOperand[traceno] = 0;
		m_mathOperator[traceno] = TQString::null;
		m_mathHorizontalUnits[traceno] = "s";
		m_mathVerticalUnits[traceno] = "V";
		m_mathTraceControlWidgetList[traceno] = NULL;
	}
	m_triggerLevelSet = false;
	m_triggerChannelSet = false;
	m_horizontalTimebaseSet = false;
	m_runningSet = false;

	// Create widgets
	m_base = new ScopeBase(widget());
	m_traceControlWidgetGrid = new TQGridLayout(m_base->traceControlLayoutWidget);
	m_mathTraceControlWidgetGrid = new TQGridLayout(m_base->mathTraceControlLayoutWidget);
	m_timebaseControlWidgetGrid = new TQGridLayout(m_base->timebaseControlLayoutWidget);
	m_timebaseControlWidget = new TimebaseControlWidget(m_base->timebaseControlLayoutWidget);
	connect(m_timebaseControlWidget, SIGNAL(secondsPerDivChanged(double)), this, SLOT(traceControlSDivChanged(double)));
	m_timebaseControlWidgetGrid->addMultiCellWidget(m_timebaseControlWidget, 0, 0, 0, 0);
	m_traceWidget = m_base->traceScrollWidget->traceWidget();
	connect(m_traceWidget, SIGNAL(cursorDragged(uint, double)), this, SLOT(cursorLevelChanged(uint, double)));
	m_base->traceScrollWidget->setSizePolicy(TQSizePolicy(TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding));
	m_base->traceScrollWidget->setResizePolicy(TQScrollView::AutoOneFit);
	m_base->traceScrollWidget->setHScrollBarMode(TQScrollView::AlwaysOff);
	m_base->traceScrollWidget->setVScrollBarMode(TQScrollView::AlwaysOff);
	m_traceWidget->setNumberOfCursors(5);
	m_traceWidget->setZoomCursorStartIndex(1);
	m_traceWidget->setCursorColor(0, TQColor(64, 255, 255));
	m_traceWidget->setCursorHighlightColor(0, TQColor(192, 255, 255));
	m_traceWidget->setCursorOrientation(0, TQt::Horizontal);
	m_traceWidget->setCursorOrientation(1, TQt::Horizontal);
	m_traceWidget->setCursorOrientation(2, TQt::Horizontal);
	m_traceWidget->setCursorOrientation(3, TQt::Vertical);
	m_traceWidget->setCursorOrientation(4, TQt::Vertical);
	m_traceWidget->setCursorEnabled(0, false);
	m_traceWidget->setCursorEnabled(1, true);
	m_traceWidget->setCursorEnabled(2, true);
	m_traceWidget->setCursorEnabled(3, true);
	m_traceWidget->setCursorEnabled(4, true);
	m_traceWidget->setCursorName(0, "Trigger");
	m_traceWidget->setCursorName(1, "Cursor H1");
	m_traceWidget->setCursorName(2, "Cursor H2");
	m_traceWidget->setCursorName(3, "Cursor V1");
	m_traceWidget->setCursorName(4, "Cursor V2");
	m_traceWidget->setCursorPosition(0, 40);
	m_traceWidget->setCursorPosition(1, 25);
	m_traceWidget->setCursorPosition(2, 75);
	m_traceWidget->setCursorPosition(3, 25);
	m_traceWidget->setCursorPosition(4, 75);
	TraceNumberList activeTraces;
	for (uint trace=0; trace<MAXTRACES; trace++) {
		activeTraces.append(trace);
	}
	m_traceWidget->setCursorActiveTraceList(1, activeTraces);
	m_traceWidget->setCursorActiveTraceList(2, activeTraces);
	m_traceWidget->setCursorActiveTraceList(3, activeTraces);
	m_traceWidget->setCursorActiveTraceList(4, activeTraces);
	m_traceWidget->setZoomBoxEnabled(true);

	m_base->traceZoomWidget->setSizePolicy(TQSizePolicy(TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding));
	connect(m_traceWidget, SIGNAL(zoomBoxChanged(const TQRectF&)), this, SLOT(updateZoomWidgetLimits(const TQRectF&)));
	connect(m_traceWidget, SIGNAL(offsetChanged(uint, double)), m_base->traceZoomWidget, SLOT(setTraceOffset(uint, double)));

	connect(m_base->acqStart, SIGNAL(clicked()), this, SLOT(startDAQ()));
	connect(m_base->acqStop, SIGNAL(clicked()), this, SLOT(stopDAQ()));
	connect(m_base->runControlStartButton, SIGNAL(clicked()), this, SLOT(startScope()));
	connect(m_base->runControlStopButton, SIGNAL(clicked()), this, SLOT(stopScope()));

	connect(m_base->waveformSave, SIGNAL(clicked()), this, SLOT(saveWaveforms()));
	connect(m_base->waveformRecall, SIGNAL(clicked()), this, SLOT(recallWaveforms()));

	TQTimer::singleShot(0, this, TQT_SLOT(postInit()));
}

ScopePart::~ScopePart() {
	if (m_instrumentMutex->locked()) {
		printf("[WARNING] Exiting when data transfer still in progress!\n\r"); fflush(stdout);
	}

	disconnectFromServer();
	delete m_instrumentMutex;
}

void ScopePart::postInit() {
	setUsingFixedSize(false);
}

bool ScopePart::openURL(const KURL &url) {
	int ret;
	m_connectionActiveAndValid = false;
	ret = connectToServer(url.url());
	processLockouts();
	return (ret != 0);
}

bool ScopePart::closeURL() {
	disconnectFromServer();
	m_url = KURL();
	return true;
}

void ScopePart::processLockouts() {
	// Largest area
	if (m_connectionActiveAndValid) {
		if ((m_commHandlerMode < 2) && (m_commHandlerState < 2)) {
			m_base->setEnabled(false);
		}
		else {
			m_base->setEnabled(true);
		}
	}
	else {
		m_base->setEnabled(false);
	}

	// Middle area
	if (((m_commHandlerMode < 2) && (m_commHandlerState < 50)) || (m_stopTraceUpdate)) {
		m_base->groupOscilloscopeCaptureControls->setEnabled(false);
	}
	else {
		m_base->groupOscilloscopeCaptureControls->setEnabled(true);
	}

	// Least area
	if (m_stopTraceUpdate) {
		m_base->acqStop->setEnabled(false);
		m_base->acqStart->setEnabled(true);
		m_base->waveformSave->setEnabled(true);
		m_base->waveformRecall->setEnabled(true);
	}
	else {
		m_base->acqStop->setEnabled(true);
		m_base->acqStart->setEnabled(false);
		m_base->waveformSave->setEnabled(false);
		m_base->waveformRecall->setEnabled(false);
	}
	if (m_running) {
		m_base->runControlStartButton->setEnabled(false);
		m_base->runControlStopButton->setEnabled(true);
	}
	else {
		m_base->runControlStartButton->setEnabled(true);
		m_base->runControlStopButton->setEnabled(false);
	}
}

void ScopePart::disconnectFromServerCallback() {
	m_forcedUpdateTimer->stop();
	m_updateTimeoutTimer->stop();
	m_connectionActiveAndValid = false;
}

void ScopePart::connectionFinishedCallback() {
	connect(m_socket, SIGNAL(readyRead()), m_socket, SLOT(processPendingData()));
	m_socket->processPendingData();
	connect(m_socket, SIGNAL(newDataReceived()), this, SLOT(mainEventLoop()));
	m_tickerState = 0;
	m_commHandlerState = 0;
	m_commHandlerMode = 0;
	m_socket->setDataTimeout(NETWORK_COMM_TIMEOUT_MS);
	m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
	processLockouts();
	mainEventLoop();
	return;
}

void ScopePart::connectionStatusChangedCallback() {
	processLockouts();
}

void ScopePart::setTickerMessage(TQString message) {
	int i;
	bool updatesPending = false;
	for (i=0; i<=MAXTRACES;i++) {
		if (m_channelActiveSet[i]) updatesPending = true;
		if (m_voltsDivSet[i]) updatesPending = true;
		if (m_triggerLevelSet) updatesPending = true;
		if (m_triggerChannelSet) updatesPending = true;
		if (m_horizontalTimebaseSet) updatesPending = true;
		if (m_runningSet) updatesPending = true;
	}

	m_connectionActiveAndValid = true;
	TQString tickerChar;
	switch (m_tickerState) {
		case 0:
			tickerChar = "-";
			break;
		case 1:
			tickerChar = "\\";
			break;
		case 2:
			tickerChar = "|";
			break;
		case 3:
			tickerChar = "/";
			break;
	}
	if (updatesPending) {
		setStatusMessage(i18n("Updates pending") + ", " + message + TQString("... %1").arg(tickerChar));
	}
	else {
		setStatusMessage(message + TQString("... %1").arg(tickerChar));
	}
	m_tickerState++;
	if (m_tickerState > 3) {
		m_tickerState = 0;
	}
}

#define UPDATEDISPLAY_TIMEOUT		m_connectionActiveAndValid = false;														\
					m_tickerState = 0;																\
					m_commHandlerState = ScopeState_ResetRequest;													\
					m_commHandlerMode = 0;																\
					m_socket->clearIncomingData();															\
					setStatusMessage(i18n("Server ping timeout.  Please verify the status of your network connection."));						\
					m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);											\
					m_instrumentMutex->unlock();															\
					return;

#define COMMUNICATIONS_FAILED		m_connectionActiveAndValid = false;														\
					m_tickerState = 0;																\
					m_commHandlerState = ScopeState_ResetRequest;													\
					m_commHandlerMode = 0;																\
					m_socket->clearIncomingData();															\
					setStatusMessage(i18n("Instrument communication failure.  Please verify the status of your network connection."));				\
					m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);											\
					m_instrumentMutex->unlock();															\
					return;

#define SET_WATCHDOG_TIMER		if (!m_updateTimeoutTimer->isActive()) m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
#define PAT_WATCHDOG_TIMER		m_updateTimeoutTimer->stop(); m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);

#define SET_NEXT_STATE(x)		if (m_commHandlerMode == 0) {															\
						m_commHandlerState = x;															\
					}																		\
					else {																		\
						m_commHandlerState = ScopeState_ExternalCommandRequest;											\
						EXEC_NEXT_STATE_IMMEDIATELY														\
					}
#define SET_NEXT_STATE_DATA_WAITING(x)	m_commHandlerState = x;

#define EXEC_NEXT_STATE_IMMEDIATELY	m_forcedUpdateTimer->start(0, TRUE);

int getNextActiveChannel(int current, bool* activity, int maxtracenumber) {
	int ret = -1;
	for (int i=current+1; i<=maxtracenumber; i++) {
		if (activity[i]) {
			ret = i;
			break;
		}
	}
	return ret;
}

void ScopePart::mainEventLoop() {
	TQDataStream ds(m_socket);
	ds.setPrintableData(true);

	if (!m_instrumentMutex->tryLock()) {
		EXEC_NEXT_STATE_IMMEDIATELY
		return;
	}

	if (m_socket) {
		if ((m_commHandlerMode == 0) || (m_commHandlerMode == 1)) {
			if (m_commHandlerState == ScopeState_InitialRequest) {
				// Request scope access
				ds << TQString("OSCILLOSCOPE");
				m_socket->writeEndOfFrame();

				m_commHandlerState = ScopeState_InitialRequest+1;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_InitialRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Connected"));

					// Get command status
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_ResetRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_ResetRequest) {
				// Reset scope
				ds << TQString("RESET");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_ResetRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_ResetRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Reset complete]"));

					// Get command status
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_HorizontalDivCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_HorizontalDivCountRequest) {
				// Get number of horizontal divisions, step 1
				ds << TQString("GETHORIZONTALDIVCOUNT");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_HorizontalDivCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_HorizontalDivCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received horizontal division count]"));

					// Get number of horizontal divisions, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_hdivs;
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_VerticalDivCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_VerticalDivCountRequest) {
				// Get number of vertical divisions, step 1
				ds << TQString("GETVERTICALDIVCOUNT");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_VerticalDivCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_VerticalDivCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received vertical division count]"));

					// Get number of vertical divisions, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_vdivs;
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_PermittedSecondsDivRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_PermittedSecondsDivRequest) {
				// Get permitted seconds/div settings, step 1
				ds << TQString("GETPERMITTEDSDIVS");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_PermittedSecondsDivRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_PermittedSecondsDivRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received allowed seconds/div list]"));

					// Get permitted seconds/div settings, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						TQDoubleList list;
						ds >> list;
						m_timebaseControlWidget->setSecondsPerDivList(list);
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_ChannelCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_ChannelCountRequest) {
				// Get number of channels, step 1
				ds << TQString("GETNUMBEROFCHANNELS");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_ChannelCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_ChannelCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received number of channels]"));

					// Get number of channels, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_maxNumberOfTraces;
						if (m_maxNumberOfTraces > MAXTRACES) {
							m_maxNumberOfTraces = MAXTRACES;
						}
						updateTraceControlWidgets();
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = 1;
						SET_NEXT_STATE(ScopeState_ChannelActiveStateRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_ChannelActiveStateRequest) {
				// Get channel status, step 1
				ds << TQString("GETCHANNELACTIVE");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_ChannelActiveStateRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_ChannelActiveStateRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received channel %1 activity status]").arg(m_currentOpChannel));

					// Get channel status, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						TQ_INT16 active;
						ds >> active;
						m_channelActive[m_currentOpChannel] = (active != 0);
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						if (m_currentOpChannel < m_maxNumberOfTraces) {
							m_currentOpChannel++;
							SET_NEXT_STATE(ScopeState_ChannelActiveStateRequest)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							if (m_currentOpChannel > 0) {
								SET_NEXT_STATE(ScopeState_TraceSampleCountRequest)
							}
							else {
								m_currentOpChannel = 1;
								SET_NEXT_STATE(ScopeState_ChannelCountRequest)
							}
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TraceSampleCountRequest) {
				// Get number of samples in trace, step 1
				ds << TQString("GETTRACESAMPLECOUNT");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TraceSampleCountRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TraceSampleCountRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received trace sample count for channel %1]").arg(m_currentOpChannel));

					// Get number of samples in trace, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_samplesInTrace[m_currentOpChannel];
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(ScopeState_TraceSampleCountRequest)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							SET_NEXT_STATE(ScopeState_TracePermittedVoltsDivRequest)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TracePermittedVoltsDivRequest) {
				// Get permitted volts/div settings, step 1
				ds << TQString("GETPERMITTEDVDIVS");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TracePermittedVoltsDivRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TracePermittedVoltsDivRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received allowed V/div list for channel %1]").arg(m_currentOpChannel));

					// Get permitted volts/div settings, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_traceAllowedVoltsDiv[m_currentOpChannel];
						if (m_traceControlWidgetList[m_currentOpChannel-1]) {
							m_traceControlWidgetList[m_currentOpChannel-1]->setVoltsPerDivList(m_traceAllowedVoltsDiv[m_currentOpChannel]);
						}
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						if (m_currentOpChannel < m_maxNumberOfTraces) {
							m_currentOpChannel++;
							SET_NEXT_STATE(ScopeState_TracePermittedVoltsDivRequest)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							SET_NEXT_STATE(ScopeState_TraceVoltsDivRequest)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TraceVoltsDivRequest) {
				// Get volts per division, step 1
				ds << TQString("GETVOLTSDIV");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TraceVoltsDivRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TraceVoltsDivRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received volts/div for channel %1]").arg(m_currentOpChannel));

					// Get volts per division, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_voltsDiv[m_currentOpChannel];
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(ScopeState_TraceVoltsDivRequest)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							SET_NEXT_STATE(ScopeState_TraceSecondsDivRequest)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TraceSecondsDivRequest) {
				// Get seconds per division, step 1
				ds << TQString("GETSECONDSSDIV");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TraceSecondsDivRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TraceSecondsDivRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received seconds/div for channel %1]").arg(m_currentOpChannel));

					// Get seconds per division, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_secsDiv[m_currentOpChannel];
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(ScopeState_TraceSecondsDivRequest)
						}
						else {
							SET_NEXT_STATE(ScopeState_HorizontalTimebaseRequest)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_HorizontalTimebaseRequest) {
				// Get horizontal timebase, step 1
				ds << TQString("GETHORIZTIMEBASE");
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_HorizontalTimebaseRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_HorizontalTimebaseRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received horizontal timebase]"));

					// Get horizontal timebase, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_horizontalTimebase;
						m_timebaseControlWidget->setSelectedSecondsPerDiv(m_horizontalTimebase);
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = 1;
						SET_NEXT_STATE(ScopeState_TriggerChannelRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TriggerChannelRequest) {
				// Get trigger channel, step 1
				ds << TQString("GETTRIGGERCHANNEL");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TriggerChannelRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TriggerChannelRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received trigger channel]"));

					// Get trigger channel, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_triggerChannel;
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_TriggerLevelRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TriggerLevelRequest) {
				// Get trigger level, step 1
				ds << TQString("GETTRIGGERLEVEL");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TriggerLevelRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TriggerLevelRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received trigger level]"));

					// Get trigger level, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> m_triggerLevel;
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						// Update display widget(s)
						updateGraticule();
					}

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_RunningRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_RunningRequest) {
				// Get running, step 1
				ds << TQString("GETRUNNING");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_RunningRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_RunningRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Loading [Received run status]"));

					// Get running, step 2
					TQString result;
					ds >> result;
					if (result == "ACK") {
						TQ_INT16 status;
						ds >> status;
						m_running = (status != 0);
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						// Update display widget(s)
						updateGraticule();
					}

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						SET_NEXT_STATE(ScopeState_TraceRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TraceRequest) {
				// Get trace, step 1
				ds << TQString("GETCHANNELTRACE");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				SET_NEXT_STATE_DATA_WAITING(ScopeState_TraceRequest+1)
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TraceRequest+1) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Running [Received trace for channel %1]").arg(m_currentOpChannel));

					// Get trace, step 2
					TQDoubleArray trace;
					TQDoubleArray positions;
					TQString result;
					ds >> result;
					if (result == "ACK") {
						ds >> trace;
						ds >> positions;
					}
					m_socket->clearFrameTail();

					if (result == "ACK") {
						// Update display widget(s)
						m_traceWidget->setSamples(m_currentOpChannel-1, trace);
						m_traceWidget->setPositions(m_currentOpChannel-1, positions);
						m_base->traceZoomWidget->setSamples(m_currentOpChannel-1, trace);
						m_base->traceZoomWidget->setPositions(m_currentOpChannel-1, positions);
						postProcessTrace();
						processMathTraces();
						m_traceWidget->repaint(false);
						m_base->traceZoomWidget->repaint(false);
					}

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if ((m_channelActiveSet[m_currentOpChannel] == false)
							&& (m_voltsDivSet[m_currentOpChannel] == false)
							&& (m_triggerLevelSet == false)
							&& (m_triggerChannelSet == false)
							&& (m_horizontalTimebaseSet == false)
							&& (m_runningSet == false)
						) {
							if (m_currentOpChannel <= 0) {
								m_currentOpChannel = 1;
							}
							SET_NEXT_STATE(ScopeState_TraceRequest)
						}
						else {
							m_currentOpChannel = 1;
							if (m_traceWidget->userIsInteractingWithCursor()) {
								// Defer pending updates until user has stopped changing cursor value(s)
								SET_NEXT_STATE(ScopeState_TraceRequest)
							}
							else {
								SET_NEXT_STATE(ScopeState_ChannelActiveStateUpdate)
							}
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_ChannelActiveStateUpdate) {
				if (m_channelActiveSet[m_currentOpChannel]) {
					// Set channel active, step 1
					ds << TQString("SETCHANNELACTIVE");
					ds << m_currentOpChannel;
					TQ_INT16 active = (m_channelActive[m_currentOpChannel])?1:0;
					ds << active;
					m_socket->writeEndOfFrame();

					m_channelActiveSet[m_currentOpChannel] = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_ChannelActiveStateUpdate+1)
				}
				else {
					m_currentOpChannel = m_currentOpChannel + 1;
					if (m_currentOpChannel < m_maxNumberOfTraces) {
						SET_NEXT_STATE(ScopeState_ChannelActiveStateUpdate)
					}
					else {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						SET_NEXT_STATE(ScopeState_TraceVoltsDivUpdate)
					}
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_ChannelActiveStateUpdate+1) {
				m_settingsChanged = true;
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set channel %1 activity status]").arg(m_currentOpChannel));

					// Set channel active, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(ScopeState_ChannelActiveStateUpdate)
						}
						else {
							m_currentOpChannel = m_currentOpChannel + 1;
							if (m_currentOpChannel < m_maxNumberOfTraces) {
								SET_NEXT_STATE(ScopeState_ChannelActiveStateUpdate)
							}
							else {
								m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
								SET_NEXT_STATE(ScopeState_TraceVoltsDivUpdate)
							}
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TraceVoltsDivUpdate) {
				if (m_voltsDivSet[m_currentOpChannel]) {
					// Set volts per division, step 1
					ds << TQString("SETVOLTSDIV");
					ds << m_currentOpChannel;
					ds << m_voltsDiv[m_currentOpChannel];
					m_socket->writeEndOfFrame();

					m_voltsDivSet[m_currentOpChannel] = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_TraceVoltsDivUpdate+1)
				}
				else {
					m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
					if (m_currentOpChannel > 0) {
						SET_NEXT_STATE(ScopeState_TraceVoltsDivUpdate)
					}
					else {
						SET_NEXT_STATE(ScopeState_TriggerChannelUpdate)
					}
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TraceVoltsDivUpdate+1) {
				m_settingsChanged = true;
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set volts/div for channel %1]").arg(m_currentOpChannel));

					// Set volts per division, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if (m_currentOpChannel > 0) {
							SET_NEXT_STATE(ScopeState_TraceVoltsDivUpdate)
						}
						else {
							SET_NEXT_STATE(ScopeState_TriggerChannelUpdate)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TriggerChannelUpdate) {
				if (m_triggerChannelSet) {
					// Set trigger channel, step 1
					ds << TQString("SETTRIGGERCHANNEL");
					ds << m_triggerChannel;
					m_socket->writeEndOfFrame();

					m_triggerChannelSet = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_TriggerChannelUpdate+1)
				}
				else {
					SET_NEXT_STATE(ScopeState_TriggerLevelUpdate)
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TriggerChannelUpdate+1) {
				m_settingsChanged = true;
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set trigger level]"));

					// Set trigger channel, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_TriggerLevelUpdate)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TriggerLevelUpdate) {
				if (m_triggerLevelSet) {
					// Set trigger level, step 1
					ds << TQString("SETTRIGGERLEVEL");
					ds << m_triggerLevel;
					m_socket->writeEndOfFrame();

					m_triggerLevelSet = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_TriggerLevelUpdate+1)
				}
				else {
					SET_NEXT_STATE(ScopeState_HorizontalTimebaseUpdate)
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TriggerLevelUpdate+1) {
				m_settingsChanged = true;
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set trigger level]"));

					// Set trigger level, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_HorizontalTimebaseUpdate)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_HorizontalTimebaseUpdate) {
				if (m_horizontalTimebaseSet) {
					// Set horizontal timebase, step 1
					ds << TQString("SETHORIZTIMEBASE");
					ds << m_horizontalTimebase;
					m_socket->writeEndOfFrame();

					m_horizontalTimebaseSet = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_HorizontalTimebaseUpdate+1)
				}
				else {
					SET_NEXT_STATE(ScopeState_RunningUpdate)
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_HorizontalTimebaseUpdate+1) {
				m_settingsChanged = true;
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set horizontal timebase]"));

					// Set horizontal timebase, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						SET_NEXT_STATE(ScopeState_RunningUpdate)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_RunningUpdate) {
				if (m_runningSet) {
					// Set running, step 1
					ds << TQString("SETRUNNING");
					TQ_INT16 running = (m_running)?1:0;
					ds << running;
					m_socket->writeEndOfFrame();

					m_runningSet = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_RunningUpdate+1)
				}
				else {
					m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
					if (m_settingsChanged) {
						m_settingsChanged = false;
						SET_NEXT_STATE(ScopeState_ReloadSettings)
					}
					else {
						SET_NEXT_STATE(ScopeState_TraceRequest)
					}

				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_RunningUpdate+1) {
				m_settingsChanged = true;
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Updating [Set run status]"));

					// Set running, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						if (m_settingsChanged) {
							m_settingsChanged = false;
							SET_NEXT_STATE(ScopeState_ReloadSettings)
						}
						else {
							SET_NEXT_STATE(ScopeState_TraceRequest)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerState == ScopeState_ExternalCommandRequest) {
				// Execute pending command
				m_commHandlerMode = 2;
				m_socket->clearIncomingData();
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			SET_WATCHDOG_TIMER
		}
		else if (m_commHandlerMode == 2) {
			if (m_commHandlerCommandState == 0) {
				m_commHandlerMode = 0;
				m_commHandlerState = ScopeState_ChannelActiveStateRequest;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerCommandState == 1) {
				// Set channel active
				ds << TQString("SETCHANNELACTIVE");
				ds << m_nextOpChannel;
				ds << m_nextOpParameter16;
				m_socket->writeEndOfFrame();

				m_commHandlerCommandState = 2;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerCommandState == 2) {
				// Get response data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER
					setTickerMessage(i18n("Connected"));

					// Set channel active, step 2
					TQString result;
					ds >> result;
					m_socket->clearFrameTail();

					if (result == "ACK") {
						m_commHandlerCommandState = 0;
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (m_stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						if (m_stopTraceUpdate == false) {
							UPDATEDISPLAY_TIMEOUT
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
			}
			else if (m_commHandlerCommandState == 3) {
				if (m_stopTraceUpdate == false) {
					m_commHandlerCommandState = 0;
					EXEC_NEXT_STATE_IMMEDIATELY
				}
				else {
					setTickerMessage(i18n("Data acquisition stopped"));
				}
			}
		}
	}
	else {
		m_commHandlerState = ScopeState_ResetRequest;
		m_commHandlerCommandState = 0;
	}

	processLockouts();

	m_instrumentMutex->unlock();
}

void ScopePart::postProcessTrace() {
	return;
}

void ScopePart::startDAQ() {
	m_stopTraceUpdate = false;
	if (m_socket) m_socket->clearIncomingData();
	EXEC_NEXT_STATE_IMMEDIATELY
}

void ScopePart::stopDAQ() {
	if (m_commHandlerMode < 2) {
		m_stopTraceUpdate = true;
		for (int i=0; i<=MAXTRACES;i++) {
			m_channelActiveSet[i] = false;
			m_voltsDivSet[i] = false;
		}
		m_triggerLevelSet = false;
		m_triggerChannelSet = false;
		m_horizontalTimebaseSet = false;
		m_runningSet = false;
		m_commHandlerMode = 1;
		m_commHandlerCommandState = 3;
		mainEventLoop();
	}
}

#define WAVEFORM_MAGIC_NUMBER 1
#define WAVEFORM_FILE_VERSION 4

void ScopePart::saveWaveforms() {
	TQString saveFileName = KFileDialog::getSaveFileName(TQString::null, "*.wfm|Waveform Files (*.wfm)", 0, i18n("Save waveforms..."));
	if (saveFileName != "") {
		TQFile file(saveFileName);
		file.open(IO_WriteOnly);
		TQDataStream ds(&file);
		TQ_INT32 magicNumber = WAVEFORM_MAGIC_NUMBER;
		TQ_INT32 version = WAVEFORM_FILE_VERSION;
		ds << magicNumber;
		ds << version;
		ds << m_hdivs;
		ds << m_vdivs;
		ds << m_maxNumberOfTraces;
		ds << m_maxNumberOfMathTraces;
		for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
			TQ_UINT8 boolValue;
			boolValue = m_channelActive[traceno];
			ds << boolValue;
			ds << m_samplesInTrace[traceno];
			ds << m_traceAllowedVoltsDiv[traceno];
			ds << m_voltsDiv[traceno];
			ds << m_secsDiv[traceno];
			ds << m_base->traceZoomWidget->traceOffset(traceno-1);
			ds << m_traceWidget->samples(traceno-1);
			ds << m_traceWidget->positions(traceno-1);
		}
		for (int traceno=1; traceno<=m_maxNumberOfMathTraces; traceno++) {
			TQ_UINT8 boolValue;
			boolValue = m_mathChannelActive[traceno];
			ds << boolValue;
			ds << m_mathVoltsDiv[traceno];
			ds << m_mathFirstOperand[traceno];
			ds << m_mathSecondOperand[traceno];
			ds << m_mathOperator[traceno];
			ds << m_base->traceZoomWidget->traceOffset(traceno-1+m_maxNumberOfTraces);
		}
		for (int cursorno=0; cursorno<5; cursorno++) {
			ds << m_traceWidget->cursorPosition(cursorno);
		}
		ds << m_base->userNotes->text();
	}
}

void ScopePart::recallWaveforms() {
	TQString openFileName = KFileDialog::getOpenFileName(TQString::null, "*.wfm|Waveform Files (*.wfm)", 0, i18n("Open waveforms..."));
	if (openFileName != "") {
		TQFile file(openFileName);
		file.open(IO_ReadOnly);
		TQDataStream ds(&file);
		TQ_INT32 magicNumber;
		TQ_INT32 version;
		ds >> magicNumber;
		if (magicNumber == WAVEFORM_MAGIC_NUMBER) {
			ds >> version;
			if ((version >= 1) && (version <= WAVEFORM_FILE_VERSION)) {
				ds >> m_hdivs;
				ds >> m_vdivs;
				ds >> m_maxNumberOfTraces;
				if (version >= 3) {
					ds >> m_maxNumberOfMathTraces;
				}
				for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
					TQ_UINT8 boolValue;
					ds >> boolValue;
					m_channelActive[traceno] = (boolValue!=0)?true:false;
					ds >> m_samplesInTrace[traceno];
					if (version >= 3) {
						ds >> m_traceAllowedVoltsDiv[traceno];
					}
					ds >> m_voltsDiv[traceno];
					ds >> m_secsDiv[traceno];
					double offset;
					TQDoubleArray values;
					TQDoubleArray positions;
					ds >> offset;
					ds >> values;
					ds >> positions;
					m_traceWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno], true);
					m_traceWidget->setSamples(traceno-1, values);
					m_traceWidget->setPositions(traceno-1, positions);
					m_traceWidget->setTraceOffset(traceno-1, offset);
					m_base->traceZoomWidget->setSamples(traceno-1, values);
					m_base->traceZoomWidget->setPositions(traceno-1, positions);
					m_base->traceZoomWidget->setTraceOffset(traceno-1, offset);
				}
				if (version >= 3) {
					for (int traceno=1; traceno<=m_maxNumberOfMathTraces; traceno++) {
						TQ_UINT8 boolValue;
						ds >> boolValue;
						m_mathChannelActive[traceno] = (boolValue!=0)?true:false;
						ds >> m_mathVoltsDiv[traceno];
						ds >> m_mathFirstOperand[traceno];
						ds >> m_mathSecondOperand[traceno];
						ds >> m_mathOperator[traceno];
						if (version >= 4) {
							double offset;
							ds >> offset;
							m_traceWidget->setTraceOffset(traceno-1+m_maxNumberOfTraces, offset);
							m_base->traceZoomWidget->setTraceOffset(traceno-1+m_maxNumberOfTraces, offset);
						}
					}
				}
				for (int cursorno=0; cursorno<5; cursorno++) {
					double cursorPos;
					ds >> cursorPos;
					m_traceWidget->setCursorPosition(cursorno, cursorPos);
				}
				if (version < 2) {
					m_base->userNotes->setText(TQString::null);
				}
				else {
					TQString notes;
					ds >> notes;
					m_base->userNotes->setText(notes);
				}
				m_triggerChannel = -1;
				m_triggerLevel = 0;
				updateGraticule();
				postProcessTrace();
				processMathTraces();
				m_traceWidget->repaint(false);
				m_base->traceZoomWidget->repaint(false);
				updateTraceControlWidgets();
			}
			else {
				KMessageBox::error(0, i18n("<qt>The selected waveform file version (%1) is not compatible with this client, which only understands versions %2-%3</qt>").arg(version).arg(1).arg(WAVEFORM_FILE_VERSION), i18n("Invalid File"));
			}
		}
		else {
			KMessageBox::error(0, i18n("<qt>Invalid waveform file selected</qt>"), i18n("Invalid File"));
		}
	}
}

void ScopePart::updateZoomWidgetLimits(const TQRectF& zoomRect) {
	for (int traceno=0; traceno<m_maxNumberOfTraces+m_maxNumberOfMathTraces; traceno++) {
		TQRectF fullZoomRect = m_traceWidget->displayLimits(traceno);
		double widthSpan = fullZoomRect.width()-fullZoomRect.x();
		double heightSpan = fullZoomRect.height()-fullZoomRect.y();

		TQRectF zoomLimitsRect((fullZoomRect.x()+(widthSpan*(zoomRect.x()/100.0))), (fullZoomRect.y()+(heightSpan*(zoomRect.y()/100.0))), (fullZoomRect.x()+(widthSpan*((zoomRect.x()/100.0)+(zoomRect.width()/100.0)))), (fullZoomRect.y()+(heightSpan*((zoomRect.y()/100.0)+(zoomRect.height()/100.0)))));

		m_base->traceZoomWidget->setDisplayLimits(traceno, zoomLimitsRect);
	}
}

void ScopePart::processTriggerButtons() {
	int i;
	int channel = -1;
	const TraceControlWidget* widget = dynamic_cast<const TraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_traceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXTRACES)) {
			channel = channel + 1;
			if (channel != m_triggerChannel) {
				m_triggerChannel = channel;
				m_triggerChannelSet = true;
			}
		}
	}

	for (int i=0; i<m_maxNumberOfTraces;i++) {
		if (m_traceControlWidgetList[i]) {
			m_traceControlWidgetList[i]->setTriggerChannel(i == (m_triggerChannel-1));
		}
	}
}

void ScopePart::updateGraticule() {
	m_traceWidget->setNumberOfHorizontalDivisions(m_hdivs);
	m_traceWidget->setNumberOfVerticalDivisions(m_vdivs);
	m_base->traceZoomWidget->setNumberOfHorizontalDivisions(m_hdivs);
	m_base->traceZoomWidget->setNumberOfVerticalDivisions(m_vdivs);

	if (!m_triggerLevelSet) {
		if ((m_triggerChannel > 0) && (m_triggerChannel <= m_maxNumberOfTraces)) {
			TraceNumberList activeTraces;
			activeTraces.append(m_triggerChannel-1);
			m_traceWidget->setCursorActiveTraceList(0, activeTraces);
			m_traceWidget->setCursorPosition(0, (50.0-((m_triggerLevel*100.0)/(m_voltsDiv[m_triggerChannel]*m_vdivs))));
			m_traceWidget->setCursorEnabled(0, true);
		}
		else {
			m_traceWidget->setCursorEnabled(0, false);
		}
	}

	processTriggerButtons();

	if (m_maxNumberOfTraces > 0) m_traceWidget->setTraceColor(0, TQColor(255, 255, 255));
	if (m_maxNumberOfTraces > 1) m_traceWidget->setTraceColor(1, TQColor(128, 255, 128));
	if (m_maxNumberOfTraces > 2) m_traceWidget->setTraceColor(2, TQColor(255, 255, 128));
	if (m_maxNumberOfTraces > 3) m_traceWidget->setTraceColor(3, TQColor(128, 128, 255));

	if (m_maxNumberOfTraces > 0) m_base->traceZoomWidget->setTraceColor(0, TQColor(255, 255, 255));
	if (m_maxNumberOfTraces > 1) m_base->traceZoomWidget->setTraceColor(1, TQColor(128, 255, 128));
	if (m_maxNumberOfTraces > 2) m_base->traceZoomWidget->setTraceColor(2, TQColor(255, 255, 128));
	if (m_maxNumberOfTraces > 3) m_base->traceZoomWidget->setTraceColor(3, TQColor(128, 128, 255));

	TQInt16List activeChannels;
	for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
		m_traceWidget->setTraceEnabled(traceno-1, m_channelActive[traceno], TraceWidget::FullText, true);
		m_traceWidget->setTraceName(traceno-1, TQString("Channel %1").arg(traceno), true);
		m_traceWidget->setTraceHorizontalUnits(traceno-1, "s", true);
		m_traceWidget->setTraceVerticalUnits(traceno-1, "V", true);

		m_base->traceZoomWidget->setTraceEnabled(traceno-1, m_channelActive[traceno], TraceWidget::SummaryText, true);
		m_base->traceZoomWidget->setTraceName(traceno-1, TQString("Channel %1").arg(traceno), true);
		m_base->traceZoomWidget->setTraceHorizontalUnits(traceno-1, "s", true);
		m_base->traceZoomWidget->setTraceVerticalUnits(traceno-1, "V", true);

		m_traceWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno], true);
		m_base->traceZoomWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno], (traceno<m_maxNumberOfTraces)?true:false);

		m_traceWidget->setDisplayLimits(traceno-1, TQRectF(0.0, (m_voltsDiv[traceno]*m_vdivs)/2.0, (m_secsDiv[traceno]*m_hdivs), (m_voltsDiv[traceno]*m_vdivs)/-2.0), (traceno<m_maxNumberOfTraces)?true:false);
		if (m_traceControlWidgetList[traceno-1]) {
			m_traceControlWidgetList[traceno-1]->setVoltsPerDivList(m_traceAllowedVoltsDiv[traceno]);
			m_traceControlWidgetList[traceno-1]->setSelectedVoltsPerDiv(m_voltsDiv[traceno]);
			m_traceControlWidgetList[traceno-1]->setTraceEnabled(m_channelActive[traceno]);
		}

		if (m_channelActive[traceno]) {
			activeChannels.append(traceno);
		}
	}
	for (int traceno=1; traceno<=m_maxNumberOfMathTraces; traceno++) {
		updateMathTraceAllowedVoltsPerDivList(traceno);

		m_traceWidget->setTraceEnabled(traceno-1+m_maxNumberOfTraces, m_mathChannelActive[traceno], TraceWidget::FullText, true);
		m_traceWidget->setTraceName(traceno-1+m_maxNumberOfTraces, TQString("Math %1").arg(traceno), true);
		m_traceWidget->setTraceHorizontalUnits(traceno-1+m_maxNumberOfTraces, m_mathHorizontalUnits[traceno], true);
		m_traceWidget->setTraceVerticalUnits(traceno-1+m_maxNumberOfTraces, m_mathVerticalUnits[traceno], true);

		m_base->traceZoomWidget->setTraceEnabled(traceno-1+m_maxNumberOfTraces, m_mathChannelActive[traceno], TraceWidget::SummaryText, true);
		m_base->traceZoomWidget->setTraceName(traceno-1+m_maxNumberOfTraces, TQString("Math %1").arg(traceno), true);
		m_base->traceZoomWidget->setTraceHorizontalUnits(traceno-1+m_maxNumberOfTraces, m_mathHorizontalUnits[traceno], true);
		m_base->traceZoomWidget->setTraceVerticalUnits(traceno-1+m_maxNumberOfTraces, m_mathVerticalUnits[traceno], true);

		m_traceWidget->setNumberOfSamples(traceno-1+m_maxNumberOfTraces, m_samplesInMathTrace[traceno], true);
		m_base->traceZoomWidget->setNumberOfSamples(traceno-1+m_maxNumberOfTraces, m_samplesInMathTrace[traceno], (traceno<m_maxNumberOfMathTraces)?true:false);

		m_traceWidget->setDisplayLimits(traceno-1+m_maxNumberOfTraces, TQRectF(0.0, (m_mathVoltsDiv[traceno]*m_vdivs)/2.0, (m_mathSecsDiv[traceno]*m_hdivs), (m_mathVoltsDiv[traceno]*m_vdivs)/-2.0), (traceno<m_maxNumberOfMathTraces)?true:false);
		if (m_mathTraceControlWidgetList[traceno-1]) {
			m_mathTraceControlWidgetList[traceno-1]->setVerticalUnits(m_mathVerticalUnits[traceno]);
			m_mathTraceControlWidgetList[traceno-1]->setVoltsPerDivList(m_mathTraceAllowedVoltsDiv[traceno]);
			m_mathTraceControlWidgetList[traceno-1]->setSelectedVoltsPerDiv(m_mathVoltsDiv[traceno]);
			m_mathTraceControlWidgetList[traceno-1]->setTraceEnabled(m_mathChannelActive[traceno]);
			m_mathTraceControlWidgetList[traceno-1]->setFirstMathOperandList(activeChannels);
			m_mathTraceControlWidgetList[traceno-1]->setSecondMathOperandList(activeChannels);
			m_mathTraceControlWidgetList[traceno-1]->setMathOperatorList(m_availableMathOperators);
			m_mathTraceControlWidgetList[traceno-1]->setSelectedFirstMathOperand(m_mathFirstOperand[traceno]);
			m_mathTraceControlWidgetList[traceno-1]->setSelectedSecondMathOperand(m_mathSecondOperand[traceno]);
			m_mathTraceControlWidgetList[traceno-1]->setSelectedMathOperator(m_mathOperator[traceno]);
		}
	}
	updateZoomWidgetLimits(m_traceWidget->zoomBox());
}

void ScopePart::updateTraceControlWidgets() {
	// Add or remove trace control widgets as needed...
	int i;
	for (i=0; i<m_maxNumberOfTraces;i++) {
		if (!m_traceControlWidgetList[i]) {
			m_traceControlWidgetList[i] = new TraceControlWidget(m_base->traceControlLayoutWidget);
			connect(m_traceControlWidgetList[i], SIGNAL(enableChanged(bool)), this, SLOT(traceControlEnableChanged(bool)));
			connect(m_traceControlWidgetList[i], SIGNAL(voltsPerDivChanged(double)), this, SLOT(traceControlVDivChanged(double)));
			connect(m_traceControlWidgetList[i], SIGNAL(triggerChannelChangeRequested()), this, SLOT(processTriggerButtons()));
			m_traceControlWidgetGrid->addMultiCellWidget(m_traceControlWidgetList[i], i, i, 0, 0);
			m_traceControlWidgetList[i]->setTraceName(i18n("Channel %1").arg(i+1));
			m_traceControlWidgetList[i]->show();
		}
	}
	for (i=m_maxNumberOfTraces; i<MAXTRACES;i++) {
		if (m_traceControlWidgetList[i]) {
			m_traceControlWidgetGrid->remove(m_traceControlWidgetList[i]);
			delete m_traceControlWidgetList[i];
		}
	}
	for (i=0; i<m_maxNumberOfMathTraces;i++) {
		if (!m_mathTraceControlWidgetList[i]) {
			m_mathTraceControlWidgetList[i] = new MathTraceControlWidget(m_base->mathTraceControlLayoutWidget);
			connect(m_mathTraceControlWidgetList[i], SIGNAL(enableChanged(bool)), this, SLOT(mathTraceControlEnableChanged(bool)));
			connect(m_mathTraceControlWidgetList[i], SIGNAL(voltsPerDivChanged(double)), this, SLOT(mathTraceControlVDivChanged(double)));
			connect(m_mathTraceControlWidgetList[i], SIGNAL(firstMathOperandChanged(int)), this, SLOT(mathTraceControlFirstOperandChanged(int)));
			connect(m_mathTraceControlWidgetList[i], SIGNAL(secondMathOperandChanged(int)), this, SLOT(mathTraceControlSecondOperandChanged(int)));
			connect(m_mathTraceControlWidgetList[i], SIGNAL(mathOperatorChanged(TQString)), this, SLOT(mathTraceControlOperatorChanged(TQString)));
			m_mathTraceControlWidgetGrid->addMultiCellWidget(m_mathTraceControlWidgetList[i], i+m_maxNumberOfTraces, i+m_maxNumberOfTraces, 0, 0);
			m_mathTraceControlWidgetList[i]->setTraceName(i18n("Math %1").arg(i+1));
			m_mathTraceControlWidgetList[i]->show();
		}
	}
	for (i=m_maxNumberOfMathTraces; i<MAXMATHTRACES;i++) {
		if (m_mathTraceControlWidgetList[i]) {
			m_mathTraceControlWidgetGrid->remove(m_mathTraceControlWidgetList[i]);
			delete m_mathTraceControlWidgetList[i];
		}
	}
}

void ScopePart::traceControlEnableChanged(bool enabled) {
	int i;
	int channel = -1;
	const TraceControlWidget* widget = dynamic_cast<const TraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_traceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXTRACES)) {
			m_channelActive[channel+1] = enabled;
			m_channelActiveSet[channel+1] = true;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
}

void ScopePart::traceControlVDivChanged(double vdiv) {
	int i;
	int channel = -1;
	const TraceControlWidget* widget = dynamic_cast<const TraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_traceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXTRACES)) {
			m_voltsDiv[channel+1] = vdiv;
			m_voltsDivSet[channel+1] = true;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
}

void ScopePart::traceControlSDivChanged(double sdiv) {
	m_horizontalTimebase = sdiv;
	m_horizontalTimebaseSet = true;
}

void ScopePart::mathTraceControlEnableChanged(bool enabled) {
	int i;
	int channel = -1;
	const MathTraceControlWidget* widget = dynamic_cast<const MathTraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXMATHTRACES;i++) {
			if (m_mathTraceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXMATHTRACES)) {
			m_mathChannelActive[channel+1] = enabled;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
	processMathTraces();
}

void ScopePart::mathTraceControlVDivChanged(double vdiv) {
	int i;
	int channel = -1;
	const MathTraceControlWidget* widget = dynamic_cast<const MathTraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_mathTraceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXMATHTRACES)) {
			m_mathVoltsDiv[channel+1] = vdiv;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
}

void ScopePart::mathTraceControlFirstOperandChanged(int operand) {
	int i;
	int channel = -1;
	const MathTraceControlWidget* widget = dynamic_cast<const MathTraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_mathTraceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXMATHTRACES)) {
			m_mathFirstOperand[channel+1] = operand;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
	processMathTraces();
}

void ScopePart::mathTraceControlSecondOperandChanged(int operand) {
	int i;
	int channel = -1;
	const MathTraceControlWidget* widget = dynamic_cast<const MathTraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_mathTraceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXMATHTRACES)) {
			m_mathSecondOperand[channel+1] = operand;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
	processMathTraces();
}

void ScopePart::mathTraceControlOperatorChanged(TQString op) {
	int i;
	int channel = -1;
	const MathTraceControlWidget* widget = dynamic_cast<const MathTraceControlWidget*>(sender());
	if (widget) {
		for (i=0; i<MAXTRACES;i++) {
			if (m_mathTraceControlWidgetList[i] == widget) {
				channel = i;
				break;
			}
		}
		if ((channel >= 0) && (channel <=MAXMATHTRACES)) {
			m_mathOperator[channel+1] = op;
		}
	}

	updateGraticule();
	m_traceWidget->repaint(false);
	m_base->traceZoomWidget->repaint(false);
	updateTraceControlWidgets();
	processMathTraces();
}

void ScopePart::updateMathTraceAllowedVoltsPerDivList(int traceno) {
	if (m_mathFirstOperand[traceno] < 1) {
		m_mathFirstOperand[traceno] = 1;
	}
	if (m_mathSecondOperand[traceno] < 1) {
		m_mathSecondOperand[traceno] = 1;
	}
	if (m_mathFirstOperand[traceno] > MAXTRACES) {
		m_mathFirstOperand[traceno] = MAXTRACES;
	}
	if (m_mathSecondOperand[traceno] > MAXTRACES) {
		m_mathSecondOperand[traceno] = MAXTRACES;
	}
	if (m_mathOperator[traceno] == "") {
		m_mathOperator[traceno] = "+";
	}
	int firstOperandChannel = m_mathFirstOperand[traceno];
	int secondOperandChannel = m_mathSecondOperand[traceno];
	if ((m_mathOperator[traceno] == "+")
		|| (m_mathOperator[traceno] == "-")
		|| (m_mathOperator[traceno] == "*")
		|| (m_mathOperator[traceno] == "/")) {
		// Compute intersection of both trace operand volt/div lists
		m_mathTraceAllowedVoltsDiv[traceno].clear();
		TQDoubleList::iterator it;
		for (it = m_traceAllowedVoltsDiv[firstOperandChannel].begin(); it != m_traceAllowedVoltsDiv[firstOperandChannel].end(); ++it) {
			m_mathTraceAllowedVoltsDiv[traceno].append(*it);
		}
		for (it = m_traceAllowedVoltsDiv[secondOperandChannel].begin(); it != m_traceAllowedVoltsDiv[secondOperandChannel].end(); ++it) {
			if (!m_mathTraceAllowedVoltsDiv[traceno].contains(*it)) {
				m_mathTraceAllowedVoltsDiv[traceno].append(*it);
			}
		}
		for (int i=1; i<=m_maxNumberOfTraces; i++) {
			int vdiv = m_voltsDiv[i];
			if (!m_mathTraceAllowedVoltsDiv[traceno].contains(vdiv)) {
				m_mathTraceAllowedVoltsDiv[traceno].append(vdiv);
			}
		}
		qHeapSort(m_mathTraceAllowedVoltsDiv[traceno]);

		// Reset GUI if not set (e.g. after startup)
		if ((m_mathVoltsDiv[traceno] == 0) && (m_mathTraceAllowedVoltsDiv[traceno].count() > 0)) {
			m_mathVoltsDiv[traceno] = m_mathTraceAllowedVoltsDiv[traceno][0];
		}

		int firstTraceLength = m_samplesInTrace[m_mathFirstOperand[traceno]];
		m_samplesInMathTrace[traceno] = firstTraceLength;
		m_mathSecsDiv[traceno] = m_secsDiv[traceno];

		m_mathHorizontalUnits[traceno] = "s";
		m_mathVerticalUnits[traceno] = "V";
	}
#ifdef ENABLE_FFT
	else if (m_mathOperator[traceno] == "FFT") {
		int firstTraceLength = m_samplesInTrace[m_mathFirstOperand[traceno]];
		m_samplesInMathTrace[traceno] = firstTraceLength;

		// Calculate horizontal steps per division
		// Full scale needs to be the sampling rate
		TQDoubleArray inputPositions = m_traceWidget->positions(m_mathFirstOperand[traceno]-1);
		double fs = 1.0 / (inputPositions[1] - inputPositions[0]);
		fs = fs / 2.0;	// Truncate waveform at the Nyquist frequency
		m_mathSecsDiv[traceno] = fs/m_hdivs;

		// Add several dB/div settings
		m_mathTraceAllowedVoltsDiv[traceno].clear();
		m_mathTraceAllowedVoltsDiv[traceno].append(0.1);
		m_mathTraceAllowedVoltsDiv[traceno].append(1);
		m_mathTraceAllowedVoltsDiv[traceno].append(10);
		m_mathTraceAllowedVoltsDiv[traceno].append(100);
		m_mathTraceAllowedVoltsDiv[traceno].append(1000);
		qHeapSort(m_mathTraceAllowedVoltsDiv[traceno]);

		m_mathHorizontalUnits[traceno] = "Hz";
		m_mathVerticalUnits[traceno] = "dB";

		// Get next highest power of 2 for the FFT algorithm
		int fftLength = powf(2, ceilf(log2f(firstTraceLength)));
		m_samplesInMathTrace[traceno] = fftLength;
	}
#endif // ENABLE_FFT
	else {
		m_mathTraceAllowedVoltsDiv[traceno].clear();
	}
}

void ScopePart::processMathTraces() {
	for (int traceno=1; traceno<=m_maxNumberOfMathTraces; traceno++) {
		if ((m_mathOperator[traceno] == "+")
			|| (m_mathOperator[traceno] == "-")
			|| (m_mathOperator[traceno] == "*")
			|| (m_mathOperator[traceno] == "/")) {
			TQDoubleArray outputValues;
			TQDoubleArray outputPositions;
			TQDoubleArray firstValues = m_traceWidget->samples(m_mathFirstOperand[traceno]-1);
			TQDoubleArray firstPositions = m_traceWidget->positions(m_mathFirstOperand[traceno]-1);
			TQDoubleArray secondValues = m_traceWidget->samples(m_mathSecondOperand[traceno]-1);
			TQDoubleArray secondPositions = m_traceWidget->positions(m_mathSecondOperand[traceno]-1);
			outputValues.resize(m_samplesInMathTrace[traceno]);
			outputPositions = firstPositions;

			if (m_mathOperator[traceno] == "+") {
				for (int i=0; i < m_samplesInMathTrace[traceno]; i++) {
					outputValues[i] = firstValues[i] + secondValues[i];
				}
			}
			else if (m_mathOperator[traceno] == "-") {
				for (int i=0; i < m_samplesInMathTrace[traceno]; i++) {
					outputValues[i] = firstValues[i] - secondValues[i];
				}
			}
			else if (m_mathOperator[traceno] == "*") {
				for (int i=0; i < m_samplesInMathTrace[traceno]; i++) {
					outputValues[i] = firstValues[i] * secondValues[i];
				}
			}
			else if (m_mathOperator[traceno] == "/") {
				for (int i=0; i < m_samplesInMathTrace[traceno]; i++) {
					if (secondValues[i] == 0) {
						secondValues[i] = 1e-12;
					}
					outputValues[i] = firstValues[i] / secondValues[i];
				}
			}
			else {
				for (int i=0; i < m_samplesInMathTrace[traceno]; i++) {
					outputValues[i] = 0;
				}
			}

			m_traceWidget->setSamples(m_maxNumberOfTraces-1+traceno, outputValues);
			m_traceWidget->setPositions(m_maxNumberOfTraces-1+traceno, outputPositions);
			m_base->traceZoomWidget->setSamples(m_maxNumberOfTraces-1+traceno, outputValues);
			m_base->traceZoomWidget->setPositions(m_maxNumberOfTraces-1+traceno, outputPositions);
		}
#ifdef ENABLE_FFT
		else if (m_mathOperator[traceno] == "FFT") {
			TQDoubleArray outputValues;
			TQDoubleArray outputPositions;
			TQDoubleArray inputValues = m_traceWidget->samples(m_mathFirstOperand[traceno]-1);
			TQDoubleArray inputPositions = m_traceWidget->positions(m_mathFirstOperand[traceno]-1);
			int inputLength = m_samplesInTrace[m_mathFirstOperand[traceno]];
			int fftLength = m_samplesInMathTrace[traceno];

			// Resize arrays
			inputValues.resize(fftLength);
			outputValues.resize(fftLength);
			outputPositions.resize(fftLength);

			// Generate output positions
			// The FFT starts at 0Hz and goes up in Fs/N steps
			double pos = 0;
			double fs = 1.0 / (inputPositions[1] - inputPositions[0]);
			double step = fs / fftLength;
			for (int i=0; i<fftLength; i++) {
				outputPositions[i] = pos;
				pos = pos + step;
			}

			// Zero-pad FFT input
			for (int i=inputLength; i<fftLength; i++) {
				inputValues[i] = 0;
			}

			// Allocate buffers
			float __attribute__ ((aligned(32))) *ffts_input = (float*) valloc(2 * fftLength * sizeof(float));
			float __attribute__ ((aligned(32))) *ffts_output = (float*) valloc(2 * fftLength * sizeof(float));

			// Load data
			for (int i=0; i<fftLength; i++) {
				ffts_input[i*2] = inputValues[i];
				ffts_input[(i*2)+1] = 0;
			}

			// Execute FFT
			ffts_plan_t *p = ffts_init_1d(fftLength, -1);
			if (p) {
				ffts_execute(p, ffts_input, ffts_output);

				// Save data
				double magnitude;
				// double phase;
				for (int i=0; i<fftLength; i++) {
					magnitude = sqrt(pow(ffts_output[i*2], 2) + pow(ffts_output[(i*2)+1], 2));
					// phase = atan2(ffts_output[(i*2)+1], ffts_output[i*2]);
					outputValues[i] = 10.0*log10(magnitude);	// Convert magnitude to dB
				}

				ffts_free(p);
			}
			else {
				printf("[ERROR] Unable to execute FFT!\n\r");
				for (int i=0; i < fftLength; i++) {
					outputValues[i] = 0;
				}
			}

			// Free buffers
			free(ffts_input);
			free(ffts_output);

			m_traceWidget->setSamples(m_maxNumberOfTraces-1+traceno, outputValues);
			m_traceWidget->setPositions(m_maxNumberOfTraces-1+traceno, outputPositions);
			m_base->traceZoomWidget->setSamples(m_maxNumberOfTraces-1+traceno, outputValues);
			m_base->traceZoomWidget->setPositions(m_maxNumberOfTraces-1+traceno, outputPositions);
		}
#endif // ENABLE_FFT
		else {
			TQDoubleArray outputValues;
			TQDoubleArray outputPositions;

			for (int i=0; i < m_samplesInMathTrace[traceno]; i++) {
				outputValues[i] = 0;
			}

			m_traceWidget->setSamples(m_maxNumberOfTraces-1+traceno, outputValues);
			m_traceWidget->setPositions(m_maxNumberOfTraces-1+traceno, outputPositions);
			m_base->traceZoomWidget->setSamples(m_maxNumberOfTraces-1+traceno, outputValues);
			m_base->traceZoomWidget->setPositions(m_maxNumberOfTraces-1+traceno, outputPositions);
		}
	}
}

void ScopePart::cursorLevelChanged(uint cursor, double level) {
	if (cursor == 0) {
		// Trigger level changed
		m_triggerLevel = (((50.0-level)*(m_voltsDiv[m_triggerChannel]*m_vdivs))/100.0);
		m_triggerLevelSet = true;

		updateGraticule();
		m_traceWidget->repaint(false);
		m_base->traceZoomWidget->repaint(false);
		updateTraceControlWidgets();
	}
}

void ScopePart::startScope() {
	m_running = true;
	m_runningSet = true;
}

void ScopePart::stopScope() {
	m_running = false;
	m_runningSet = true;
}

TDEAboutData* ScopePart::createAboutData() {
	return new TDEAboutData( APP_NAME, I18N_NOOP( APP_PRETTYNAME ), APP_VERSION );
}

} //namespace RemoteLab

#include "part.moc"
