//Author:    Timothy Pearson <kb9vqf@pearsoncomputing.net>, (C) 2012
//Copyright: See COPYING file that comes with this distribution

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

#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 <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>

#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_ChannelCountRequest			= 8,
	ScopeState_ChannelActiveStateRequest		= 10,
	ScopeState_TraceSampleCountRequest		= 12,
	ScopeState_TracePermittedVoltsDivRequest	= 14,
	ScopeState_TraceVoltsDivRequest			= 16,
	ScopeState_TraceSecondsDivRequest		= 18,
	ScopeState_TriggerChannelRequest		= 20,
	ScopeState_TriggerLevelRequest			= 22,
	ScopeState_RunningRequest			= 24,
	ScopeState_TraceRequest				= 50,
	ScopeState_ChannelActiveStateUpdate		= 100,
	ScopeState_TraceVoltsDivUpdate			= 102,
	ScopeState_TriggerLevelUpdate			= 104,
	ScopeState_RunningUpdate			= 106,
	ScopeState_ExternalCommandRequest		= 255
};

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);
}

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::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));
}

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_triggerChannel(-1), m_base(0), 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;
	for (int traceno=0; traceno<=MAXTRACES; traceno++) {
		m_samplesInTrace[traceno] = 0;
		m_channelActive[traceno] = false;
		m_voltsDiv[traceno] = 0;
		m_secsDiv[traceno] = 0;
		m_traceControlWidgetList[traceno] = NULL;

		m_voltsDivSet[traceno] = false;
		m_channelActiveSet[traceno] = false;
	}
	m_triggerLevelSet = false;
	m_runningSet = false;

	// Create widgets
	m_base = new ScopeBase(widget());
	m_traceControlWidgetGrid = new TQGridLayout(m_base->traceControlLayoutWidget);
	m_traceWidget = m_base->traceWidget;
	connect(m_traceWidget, SIGNAL(cursorDragged(uint, double)), this, SLOT(cursorLevelChanged(uint, double)));
	m_traceWidget->setSizePolicy(TQSizePolicy(TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding));
	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)) || (stopTraceUpdate)) {
		m_base->groupOscilloscopeCaptureControls->setEnabled(false);
	}
	else {
		m_base->groupOscilloscopeCaptureControls->setEnabled(true);
	}

	// Least area
	if (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_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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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_ChannelCountRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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") {
						TQDoubleList list;
						ds >> list;
						if (m_traceControlWidgetList[m_currentOpChannel-1]) {
							m_traceControlWidgetList[m_currentOpChannel-1]->setVoltsPerDivList(list);
						}
					}
					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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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_TriggerChannelRequest)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TraceRequest) {
				// Get trace, step 1
				ds << TQString("GETCHANNELTRACE");
				ds << m_currentOpChannel;
				m_socket->writeEndOfFrame();

				m_lastChangesRequireFullUpdate = false;
				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();
						m_traceWidget->repaint(false);
						m_base->traceZoomWidget->repaint(false);
					}

					if (result == "ACK") {
						m_currentOpChannel = getNextActiveChannel(m_currentOpChannel, m_channelActive, m_maxNumberOfTraces);
						if ((m_currentOpChannel > 0)
							&& (m_channelActiveSet[m_currentOpChannel] == false)
							&& (m_voltsDivSet[m_currentOpChannel] == false)
							&& (m_triggerLevelSet == false)
							&& (m_runningSet == false)
						) {
							SET_NEXT_STATE(ScopeState_TraceRequest)
						}
						else {
							m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							SET_NEXT_STATE(ScopeState_ChannelActiveStateUpdate)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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_lastChangesRequireFullUpdate = true;
					m_channelActiveSet[m_currentOpChannel] = false;
					SET_NEXT_STATE_DATA_WAITING(ScopeState_ChannelActiveStateUpdate+1)
				}
				else {
					if (m_currentOpChannel < m_maxNumberOfTraces) {
						m_currentOpChannel++;
						SET_NEXT_STATE(ScopeState_ChannelActiveStateUpdate)
					}
					else {
						m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
						if (m_lastChangesRequireFullUpdate) {
							SET_NEXT_STATE(ScopeState_TraceVoltsDivRequest)
						}
						else {
							SET_NEXT_STATE(ScopeState_TraceVoltsDivUpdate)
						}
					}
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_ChannelActiveStateUpdate+1) {
				// 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 = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
							if (m_lastChangesRequireFullUpdate) {
								SET_NEXT_STATE(ScopeState_TraceVoltsDivRequest)
							}
							else {
								SET_NEXT_STATE(ScopeState_TraceVoltsDivUpdate)
							}
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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_TriggerLevelUpdate)
					}
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TraceVoltsDivUpdate+1) {
				// 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_TriggerLevelUpdate)
						}
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			else if (m_commHandlerState == ScopeState_TriggerLevelUpdate) {
				if (m_voltsDivSet[m_currentOpChannel]) {
					// 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 {
					m_currentOpChannel = getNextActiveChannel(0, m_channelActive, m_maxNumberOfTraces);
					SET_NEXT_STATE(ScopeState_TraceRequest)
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_TriggerLevelUpdate+1) {
				// 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_RunningUpdate)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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);
					SET_NEXT_STATE(ScopeState_TraceRequest)
				}
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == ScopeState_RunningUpdate+1) {
				// 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);
						SET_NEXT_STATE(ScopeState_TraceRequest)
						EXEC_NEXT_STATE_IMMEDIATELY
					}
					else {
						if (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			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 (stopTraceUpdate == false) {
							COMMUNICATIONS_FAILED
						}
						else {
							setTickerMessage(i18n("Data acquisition stopped"));
						}
					}
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}
			}
			else if (m_commHandlerCommandState == 3) {
				if (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() {
	stopTraceUpdate = false;
	if (m_socket) m_socket->clearIncomingData();
	EXEC_NEXT_STATE_IMMEDIATELY
}

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

#define WAVEFORM_MAGIC_NUMBER 1
#define WAVEFORM_FILE_VERSION 1

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;
		for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
			TQ_UINT8 boolValue;
			boolValue = m_channelActive[traceno];
			ds << boolValue;
			ds << m_samplesInTrace[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 cursorno=0; cursorno<5; cursorno++) {
			ds << m_traceWidget->cursorPosition(cursorno);
		}
	}
}

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 == WAVEFORM_FILE_VERSION) {
				ds >> m_hdivs;
				ds >> m_vdivs;
				ds >> m_maxNumberOfTraces;
				for (int traceno=1; traceno<=m_maxNumberOfTraces; traceno++) {
					TQ_UINT8 boolValue;
					ds >> boolValue;
					m_channelActive[traceno] = (boolValue!=0)?true:false;
					ds >> m_samplesInTrace[traceno];
					ds >> m_voltsDiv[traceno];
					ds >> m_secsDiv[traceno];
					double offset;
					TQDoubleArray values;
					TQDoubleArray positions;
					ds >> offset;
					ds >> values;
					ds >> positions;
					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);
				}
				for (int cursorno=0; cursorno<5; cursorno++) {
					double cursorPos;
					ds >> cursorPos;
					m_traceWidget->setCursorPosition(cursorno, cursorPos);
				}
				m_triggerChannel = -1;
				m_triggerLevel = 0;
				updateGraticule();
				postProcessTrace();
				m_traceWidget->repaint(false);
				m_base->traceZoomWidget->repaint(false);
				updateTraceControlWidgets();
			}
			else {
				KMessageBox::error(0, i18n("<qt>The selected waveform file version does not match this client</qt>"), 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; 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::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);
		}
	}

	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));

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

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

		m_traceWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno]);
		m_base->traceZoomWidget->setNumberOfSamples(traceno-1, m_samplesInTrace[traceno]);

		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));
		if (m_traceControlWidgetList[traceno-1]) {
			m_traceControlWidgetList[traceno-1]->setSelectedVoltsPerDiv(m_voltsDiv[traceno]);
			m_traceControlWidgetList[traceno-1]->setTraceEnabled(m_channelActive[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)));
			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];
		}
	}
}

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::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"
