#include <stdio.h>
#include "math.h"
#include "tc_vars.h"
#include "hardware_t.h"
#include "flash_t.h"
#include "display_t.h"
#include "floatstr_t.h"

//#define _Debug_
//#define _Debug_IRQ_
//#define _Debug_QM_
//#define _Debug_FindZero_
//#define _Debug_AutoScale_
//#define _Debug_FindVoltage_
//#define _Debug_FindTimebase_
//#define _Debug_ZeroLevel_
//#define _Debug_Cursor_
//#define _Debug_Roll_Mode_
//#define _Debug_Memory_
//#define _Debug_USB_
//#define _Debug_FFT_

// Class Hardware
void Hardware::Init(void)						// Hardware Init Routine
{
	int x;
	unsigned long ChannelSign = 0;

	na_data_adr->np_piodata = 0x01;
	na_mode->np_piodata 	= 0x01;		//reset CH3 & CH4
	na_mode->np_piodata 	= 0x00;
	na_data_adr->np_piodata = 0x01;		// delay


#ifdef _Debug_
	printf("debug\r\n");
#endif

	//printf("Get number of channels\r\n");
	ChannelSign = READADC(3);

	if ((ChannelSign & 0xFFFF0000) == 0x12480000)
	{
		printf("4-Channels found Signatur : %x\r\n", ChannelSign);
		NumberOfChannels = 4;
	}
	else
	{
		printf("2-Channels found Signatur : %x\r\n", ChannelSign);
		NumberOfChannels = 2;
	}
	
	data_adr->np_piodata = 0x00;

	printf("Setup hardware\r");
	Setup_Hardware();	
	printf("Setup hardware 				- done\r\n");

	Read_Version();	
	printf("HW Version : %x  Channels : %d\r\n", tc_hw_version, NumberOfChannels);

	printf("Testing LEDs\r\n");
	//LED-test, 	BF
	for(x=0;x<16;x++)	//switch all LEDs off 	
	{ Reset_LED(x); }
	
	Set_LED(12);		//Run/Stop green
	//Set_LED(15);		//Single green

	//Set_LED(13);		//Run/Stop red
	Set_LED(14);		//Single red

	for(x=0;x<12;x++)	//switch  LEDs on 
	{ Set_LED(x); }		
	
	//Reset_LED(12);
	//Reset_LED(15);
	//Set_LED(13);		//Run/Stop red
	Set_LED(14);		//Single red
	
	nr_delay(5);
	Send_LED();
	nr_delay(200);

	//LED-test, 	BF
	for(x=0;x<16;x++)	//switch all LEDs off 	
	{ Reset_LED(x); }
	
	nr_delay(5);
	Send_LED();
	nr_delay(200);

	//Set_LED(12);		//Run/Stop green
	//Set_LED(15);		//Single green

	Set_LED(13);		//Run/Stop red
	Set_LED(14);		//Single red

	for(x=0;x<12;x++)	//switch  LEDs on 
	{ Set_LED(x); }		
	
	//Reset_LED(12);
	//Reset_LED(15);
	//Set_LED(13);		//Run/Stop red
	Set_LED(14);		//Single red
	
	nr_delay(5);
	Send_LED();
	nr_delay(1);


	printf("Setup vars\r");
	Setup_Vars();
	printf("Setup vars 				- done\r\n");

	printf("Setup vars to default values\r");
	Set_Vars_Default();
	printf("Setup vars to default values 		- done\r\n");	

	printf("Read config from flash\r");
	AMDFlash::Read_Config_Flash();
	printf("Read config from flash 			- done\r\n");
	
	printf("Read protected config from flash\r");
	AMDFlash::Read_Protected_Flash();
	printf("Read protected config from flash	- done\r\n");
        
	//printf("11\r\n");
  	//  out_test->np_piodata = test_port_reg;		

	printf("Recalc vars\r");
	Recalc_Vars();
        printf("Recalc vars				- done\r\n");
	
	if (MenuStatus[MENU_CHANNEL1][3] < 104) MenuStatus[MENU_CHANNEL1][3] = 104;
	if (MenuStatus[MENU_CHANNEL2][3] < 104) MenuStatus[MENU_CHANNEL2][3] = 104;
	if (MenuStatus[MENU_CHANNEL3][3] < 104) MenuStatus[MENU_CHANNEL3][3] = 104;
	if (MenuStatus[MENU_CHANNEL4][3] < 104) MenuStatus[MENU_CHANNEL4][3] = 104;
	if (MenuStatus[MENU_TRIGGERMODE][4] < 104) MenuStatus[MENU_TRIGGERMODE][4] = 104;
	
	// Coupling channel popup
    	if (MenuStatus[MENU_CHANNEL1][0] == 7)
    	{
        	MenuPopupStatus[13][0] = 2;                                     // Popup Coupling = AC
        	MenuPopupStatus[13][1] = 3;
        	MenuPopupStatus[13][2] = 2;
    	}
    	else if (MenuStatus[MENU_CHANNEL1][0] == 8)
    	{
        	MenuPopupStatus[13][0] = 2;                                     // Popup Coupling = DC
        	MenuPopupStatus[13][1] = 2;
        	MenuPopupStatus[13][2] = 3;
    	}
    	else
    	{
        	MenuPopupStatus[13][0] = 3;                                     // Popup Coupling = GND
        	MenuPopupStatus[13][1] = 2;
        	MenuPopupStatus[13][2] = 2;
    	}	

	if (MenuStatus[MENU_CHANNEL2][0] == 7)
	{
		MenuPopupStatus[14][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[14][1] = 3;
		MenuPopupStatus[14][2] = 2;
	}
	else if (MenuStatus[MENU_CHANNEL2][0] == 8)
	{
		MenuPopupStatus[14][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[14][1] = 2;
		MenuPopupStatus[14][2] = 3;
	}
	else
	{
		MenuPopupStatus[14][0] = 3;                                     // Popup Coupling = DC
		MenuPopupStatus[14][1] = 2;
		MenuPopupStatus[14][2] = 2;
	}	
	
	if (MenuStatus[MENU_CHANNEL3][0] == 7)
	{
		MenuPopupStatus[15][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[15][1] = 3;
		MenuPopupStatus[15][2] = 2;
	}
	else if (MenuStatus[MENU_CHANNEL3][0] == 8)
	{
		MenuPopupStatus[15][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[15][1] = 2;
		MenuPopupStatus[15][2] = 3;
	}
	else
	{
		MenuPopupStatus[15][0] = 3;                                     // Popup Coupling = DC
		MenuPopupStatus[15][1] = 2;
		MenuPopupStatus[15][2] = 2;
	}	
	
	if (MenuStatus[MENU_CHANNEL4][0] == 7)
	{
		MenuPopupStatus[16][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[16][1] = 3;
		MenuPopupStatus[16][2] = 2;
	}
	else if (MenuStatus[MENU_CHANNEL4][0] == 8)
	{
		MenuPopupStatus[16][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[16][1] = 2;
		MenuPopupStatus[16][2] = 3;
	}
	else
	{
		MenuPopupStatus[16][0] = 3;                                     // Popup Coupling = DC
		MenuPopupStatus[16][1] = 2;
		MenuPopupStatus[16][2] = 2;
	}	

	
//    Debug_Mode = true;	
//    ADC_Debug_Mode = true;	

	

    	dmode_factor = Timebase_Delayed_Factor_Matrix[Selected_Timebase][SIGNALFaktor_idx] / Timebase_Delayed_Factor_Matrix[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx];

    	Cursor_Delayed_1 = ((GRID_WIDTH / 2) - (int) (((float) GRID_WIDTH / dmode_factor) / 2)) + dmode_Window_Offset_Pos;
    	Cursor_Delayed_2 = Cursor_Delayed_1 + (int) ((float) GRID_WIDTH / dmode_factor);
    	Cursor_Delayed_Size = Cursor_Delayed_2 - Cursor_Delayed_1;
		
	if (NumberOfChannels == 2)
	{
		Channel_3_Active = 0;
		Channel_4_Active = 0;
		
		LED_ON[2] = 0;
		LED_ON[3] = 0;
		
		sprintf(&MenuData[29][0], "Math");
		sprintf(&MenuData[140][0], "External");	
		
		MenuDataDef[29] = 33;
		MenuDataDef[140] = 21;
		
		sprintf(&MenuPopupText[1][3][0], "Math");
		sprintf(&MenuPopupText[3][3][0], "Math");
		sprintf(&MenuPopupText[5][3][0], "Math");
		sprintf(&MenuPopupText[6][3][0], "Math");
		sprintf(&MenuPopupText[7][3][0], "External");		
		sprintf(&MenuPopupText[24][3][0], "Math");
		sprintf(&MenuPopupText[25][3][0], "Math");
		sprintf(&MenuPopupText[26][3][0], "Math");

		
		MenuPopupDef[1][1] = 2;//3
		MenuPopupDef[3][1] = 2;//3
		MenuPopupDef[5][1] = 3;
		MenuPopupDef[6][1] = 3;
		MenuPopupDef[7][1] = 3;	
		MenuPopupDef[24][1] = 3;
		MenuPopupDef[25][1] = 3;
		MenuPopupDef[26][1] = 3;
		MenuPopupDef[28][1] = 2;
		MenuPopupDef[29][1] = 2;

		MenuPopupStatus[1][2] = 0;//1;
		MenuPopupStatus[1][3] = 0;
		//MenuPopupStatus[1][4] = 0;
		MenuPopupStatus[3][2] = 0;//1
		MenuPopupStatus[3][3] = 0;
//		MenuPopupStatus[3][4] = 0;    //kein math mehr
		MenuPopupStatus[5][2] = 1;
		MenuPopupStatus[5][3] = 0;
		MenuPopupStatus[5][4] = 0;
		MenuPopupStatus[6][2] = 1;
		MenuPopupStatus[6][3] = 0;
		MenuPopupStatus[6][4] = 0;
		MenuPopupStatus[7][3] = 0;
		MenuPopupStatus[7][4] = 0;
		MenuPopupStatus[24][2] = 1;
		MenuPopupStatus[24][3] = 0;
		MenuPopupStatus[24][4] = 0;
		MenuPopupStatus[25][2] = 1;
		MenuPopupStatus[25][3] = 0;
		MenuPopupStatus[25][4] = 0;
		MenuPopupStatus[26][2] = 0;
		MenuPopupStatus[26][3] = 1;
		MenuPopupStatus[26][4] = 0;	
		MenuPopupStatus[28][2] = 0;
		MenuPopupStatus[28][3] = 0;		
		MenuPopupStatus[29][2] = 0;
		MenuPopupStatus[29][3] = 0;
	}

//BF added
	//set LEDs depending on run mode
	if (Continius)
	{
		LED_ON[12] = 1;			                                        // Run/Stop Green
		LED_ON[13] = 0;			                                        // Run/Stop Red
		LED_ON[14] = 0;			                                        // Single Red
		LED_ON[15] = 0;			                                        // Single Green
	}
	else if(SingleMode)
	{
		LED_ON[12] = 0;			                                        // Run/Stop Green
		LED_ON[13] = 0;			                                        // Run/Stop Red
		LED_ON[14] = 0;			                                        // Single Red
		LED_ON[15] = 1;			                                        // Single Green
	}
	else
	{
		LED_ON[12] = 0;			                                        // Run/Stop Green
		LED_ON[13] = 1;			                                        // Run/Stop Red
		LED_ON[14] = 0;			                                        // Single Red
		LED_ON[15] = 1;								// Single Green
	}

	Setup_Interrupts();					//enable all interupts

	key_reset->np_piodata = 0;				//reset keyboard
	nr_delay(1);
	key_reset->np_piodata = 1;	

	key_int->np_pioedgecapture = 0;				// clear IRQ conditions		
		       		
//	FindSlope();
	
#ifdef _Debug_		       		
	if (Debug_Mode) printf("Init Hardware Ready \n");
#endif

/* BF del
	if (Selected_Timebase > 18)
	{
		Selected_Timebase = 18;
		timebase_reg      = tb_value[Selected_Timebase];
		Display_Timebase  = Selected_Timebase + SIGNALFaktor_idx;
	}
*/

	//-------------------------------------------------
	//BF add new ultra slow timebase mode
	//-------------------------------------------------
	if (USTB_Mode != USTB_OFF) 	//timebase > 200mS/Div?
	{
		Display::USTB_Clear_Buffer();	//clear all buffers
		Reset_Timer2();
	}

}

void Hardware::Reset_the_Watchdog(void)					//Resets the WatchDog
{
	reset_watchdog->np_piodata = 0x00;			// Reset WatchDog
	reset_watchdog->np_piodata = 0x01;	
}
//#####################################################################################################################################
void Hardware::Start_Record(void)						
{
    //if (Test_Mode) return;

	//BF add 
	//Don't start new record if ADC is still running
	//if(adc_started) return;

	la_pulse->np_piodata = 0x01;				//stop record Port On
	la_pulse->np_piodata = 0x00;				//stop record Port Off	
	
	READADC(1);
	
	adc_started = true;
	start_acq->np_piodata = 0x01;				//start record Port On
	start_acq->np_piodata = 0x00;				//start record Port Off	
 	//printf("Start Record\r\n");
}
//#####################################################################################################################################
void Hardware::Stop_Record(void)							
{
    adc_started = false;
    la_pulse->np_piodata = 0x01;				//stop record Port On
    la_pulse->np_piodata = 0x00;				//stop record Port Off	

//    READADC(1);
 //printf("Stop Record\r\n");

}
//#####################################################################################################################################
void Hardware::Read_Version(void)					//Read the hardware version
{
    la_gate->np_piodata = 0x01;
    tc_hw_version = (unsigned long) la_data->np_piodata;
    la_gate->np_piodata = 0x00;
}
//#####################################################################################################################################
void Hardware::Setup_Vars(void)						// Set standart values for variables
{
	short ix, ix2, ix3;
    	int cnt;
	
	for (ix = 0;ix < 480;ix++)
	    Display_Line_Adresses[ix] = ix * 20;

	for (ix = 0;ix < 480;ix++)
	    Display_Line_Adresses2[ix] = ix * 80;
	
	for (ix = 0; ix <= 255; ix++) 
        for (ix2 = 0; ix2 < 6; ix2++) 
            for (ix3 = 0; ix3 < 9; ix3++)
                FIR_Tab_big[ix][ix2][ix3] = (short) FIR_Tabel[ix2][ix3] * ix;
    
	for (ix = 0;ix < 32;ix++)
		LogicData[ix] = ix;

	for (ix = 0;ix <= GRID_WIDTH;ix++) {	
	    SIGNAL1_SUM_MIN[ix] = 255;
	    SIGNAL1_SUM_MAX[ix] = 0;
	}
/*
	for (cnt = 0; cnt < 1024; cnt++)
	{
		freq_re[cnt] = 0;
		freq_im[cnt] = 0;
	}
*/

/*
	// BF cha QM changed by Stefan
	for (cnt = 0; cnt < 256; cnt++)
	{
		SIGNAL_Histo[1][cnt] = 0;
		SIGNAL_Histo[2][cnt] = 0;
		SIGNAL_Histo[3][cnt] = 0;
		SIGNAL_Histo[4][cnt] = 0;
	}
*/

	// BF -> changed Stefans initialization to 1 dimensional array
	for (cnt = 0; cnt < 1024; cnt++)
	SIGNAL_Histo[cnt] = 0;
	

	// delete signals
	for (cnt = 0; cnt < 0x4000; cnt++) {
		SIGNAL1[cnt] = ADC_ZERO;
		SIGNAL2[cnt] = ADC_ZERO;
		SIGNAL3[cnt] = ADC_ZERO;
		SIGNAL4[cnt] = ADC_ZERO;
	        SIGNALM[cnt] = ADC_ZERO;
	}	


/* BF transferred into splash */	
	printf("Building trigonometric tables\r");
	Display::FFT_BuildTrigoTables();						// BF insert - init FFT-data
	printf("Building trigonometric tables 		- done\r\n");

	MenuStored  = 0;
	MenuActive  = 0;
	MenuChanged = 0;
		
	IsPopuped   = 0;
	
	Selected_ADCs_CH1 = 0;
	Selected_ADCs_CH2 = 0;
	Selected_ADCs_CH3 = 0;
	Selected_ADCs_CH4 = 0;
	
	SelectedChannel    = 1;
	SelectedChannelOld = 1;
		
	Channel_1_Active = 1;	
	Channel_2_Active = 1;
	Channel_3_Active = 1;
	Channel_4_Active = 1;	
	Channel_Math_Active = 0;
	
	Channel_1_Active_Old = 0;	
	Channel_2_Active_Old = 0;
	Channel_3_Active_Old = 0;
	Channel_4_Active_Old = 0;			
	Channel_Math_Active_Old = 0;
	
	//Reset all LEDs	BF
//	for(cnt=0;cnt<16;cnt++)
//	{ Reset_LED(cnt); }

	led_status = 0x01;

	// Channel 1-4 on + Math off
	LED_ON[0] = 1;	
	LED_ON[1] = 1;
	LED_ON[2] = 1;
	LED_ON[3] = 1;	
	LED_ON[4] = 0;
	
	// General Wheel LED off
	LED_ON[5] = 0;	
	
	// Run Green LED On
	LED_ON[12] = 1;
	
	// Trigger edge On
	LED_ON[8] = 1;		

	
    	Cursor_Enabled = false;
	
	Cursor_Both_Selected_Old = 0;	
    	Cursor_Both_Selected = 0;	
	
	SelectedCursor = 0;
	SelectedCursorOld = 0;	
	
	CursorChanged = 0;
	
	Cursor_Horizontal_Active = 0;
	Cursor_Horizontal_Active_Old = 0; 	

	Cursor_Horizontal_Position_Real1 = 103;
	Cursor_Horizontal_Position_Real2 = 203;	

	Cursor_Horizontal_Position1_Old = 103;
	Cursor_Horizontal_Position2_Old = 203;	

	Cursor_Vertical_Active = 0;
	Cursor_Vertical_Active_Old = 0;	

	Cursor_Vertical_Position_Real1 = 103;
	Cursor_Vertical_Position_Real2 = 203;	

	Cursor_Vertical_Position1_Old = 103;
	Cursor_Vertical_Position2_Old = 203;	

	Cursor_Vertical_Position_Real_XY_1 = 103;
	Cursor_Vertical_Position_Real_XY_2 = 203;	

	Cursor_Vertical_Position_XY_1_Old = 103;
	Cursor_Vertical_Position_XY_2_Old = 203;
	
    	QM_Enabled = false;
	QM_Changed[0] = 0;
	QM_Changed[1] = 0;
	QM_Changed[2] = 0;
	
	QM_Type[0] = 0;
	QM_Type[1] = 0;
	QM_Type[2] = 0;

	QM_Type_Old[0] = 0;
	QM_Type_Old[1] = 0;
	QM_Type_Old[2] = 0;
	
	QM_Channel[0] = 1;
	QM_Channel[1] = 1;
	QM_Channel[2] = 1;	
    	
	QM_Horizontal_Active = 3;
	QM_Horizontal_Active_Old = 3; 	

	QM_Horizontal_Position_Real1 = 103;
	QM_Horizontal_Position_Real2 = 203;	

	QM_Horizontal_Position1_Old = 103;
	QM_Horizontal_Position2_Old = 203;	

	QM_Vertical_Active = 3;
	QM_Vertical_Active_Old = 3;	

	QM_Vertical_Position_Real1 = 103;
	QM_Vertical_Position_Real2 = 203;	

	QM_Vertical_Position1_Old = 103;
	QM_Vertical_Position2_Old = 203;		

    	Quick_Measure_Threshold_btn_select = 1;

	SelectedEdgeExtern = 0;

	Memory_Position = 0;	
	
	Selected_Trigger_Source     = 0;
	Selected_Trigger_Source_Old = 5;
	
	Selected_Timebase = 4;
	Display_Timebase  = 4;       // Mu� vielleicht ins Flash
	Selected_Expand_Timebase = 0;
	
	dmode_Selected_Timebase = 4;
	dmode_Window_Offset_Pos = 0;
	
	TriggerWay = 1;

/*	BF del -> is set in default setup
	Trigger_Pos_CH1 = 50;
	Trigger_Pos_CH2 = 100;
	Trigger_Pos_CH3 = 150;
	Trigger_Pos_CH4 = 200;
	Trigger_Pos_CHE = 15;
*/	
	Trigger_Pos_CH1_Old = 50;
	Trigger_Pos_CH2_Old = 100;
	Trigger_Pos_CH3_Old = 150;
	Trigger_Pos_CH4_Old = 200;
	Trigger_Pos_CHE_Old = 15;	
	
	Timebase_Offset_Pos 	= 0;
	Timebase_Offset_Pos_Old = 0;

	//Trigger_Offset_Pos 	= 8192;		//BF not used
	//Trigger_Offset_Pos_Old = 8192;	//BF not used
    	
	Selected_Voltage_CH1 = 9;
	Selected_Voltage_CH2 = 9;
	Selected_Voltage_CH3 = 9;
	Selected_Voltage_CH4 = 9;
	Selected_TB = 0;	
	
	SwitchesCH1 = 0x00D5;
	SwitchesCH2 = 0x00D5;
	SwitchesCH3 = 0x00D5;
	SwitchesCH4 = 0x00D5;	
	SwitchesTB  = 0x0000;		

	SwitchesCH1Old = 0x0000;
	SwitchesCH2Old = 0x0000;
	SwitchesCH3Old = 0x0000;
	SwitchesCH4Old = 0x0000;		
	SwitchesTBOld  = 0x0001;

	ScreenShotActive = 0;	
	
	USB_Data_Trans  = 0;
	USB_SendAllData = 0;
	USB_OnlyTrigger = 0;
	Continius       = 1;				// Constant Recodinng
	SingleMode      = 0;	
	Single_Restart  = 0;
	
	ADC_Debug_Mode = false;
	Debug_Mode     = false;
	Command_Mode   = false;
	Calc_Mode      = false;
	ExtraTrg_Mode  = false;
	Search_Mode    = false;
	Search_Auto    = false;
	
	adc_started    = false;
	Connect_Vals   = true;		//BF -> ?kann weg??
	
	ctrl_reg     = 0x00A3;
	adc_ctrl_reg = 0x01C0;
	
	adc_del_reg = 0;
	pre_reg = 0x0000;
	//trg_val_reg = 0x00A0;
	//trg_hyst_reg = 0x0090;
	ext_trg_val_reg = 0x80;
	triggering = 0x00;
	channel_Adr_add = 0x0000;
	trig_range_reg = 0;
	trig_width_reg = 0x0001;
	
	trg_val_CHI_reg   = 0x00A0;
	trg_val_CHII_reg  = 0x00A0;
	trg_val_CHIII_reg = 0x00A0;
	trg_val_CHIV_reg  = 0x00A0;
	
	trig_holdoff_reg = 0x00000000;
	adc_change12_reg = 0x00000000;
	adc_change34_reg = 0x00000000;
	adc_ctr12_reg = 0x00000000;
	adc_ctr34_reg = 0x00000000;

	timebase_reg = 0xFFFFFFFF;
	ram_adress_reg = 0;
	test_port_reg = 0;
	
	CH1_DAC_Offset = 8192;
//	alpha[0] = 0;			//ADC-zero offset channel 1
//	beta[0]  = 1;			//gain correction channel 1
	CH1_DAC_1 = 0;		//BF not used???
	CH1_DAC_2 = 0;		//BF not used???
	CH1_DAC_3 = 0;		//BF not used???
	CH1_DAC_4 = 0;		//BF not used???
	
	CH2_DAC_Offset = 8192;
//	alpha[1] = 0;			//ADC-zero offset channel 2
//	beta[1]  = 1;			//gain correction channel 2
	CH2_DAC_1 = 0;		//BF not used???
	CH2_DAC_2 = 0;		//BF not used???
	CH2_DAC_3 = 0;		//BF not used???
	CH2_DAC_4 = 0;		//BF not used???
	
	CH3_DAC_Offset = 8192;
//	alpha[2] = 0;			//ADC-zero offset channel 3
//	beta[2]  = 1;			//gain correction channel 3
	CH3_DAC_1 = 0;		//BF not used???
	CH3_DAC_2 = 0;		//BF not used???
	CH3_DAC_3 = 0;		//BF not used???
	CH3_DAC_4 = 0;		//BF not used???
	
	CH4_DAC_Offset = 8192;
//	alpha[3] = 0;			//ADC-zero offset channel 4
//	beta[3]  = 1;			//gain correction channel 4
	CH4_DAC_1 = 0;		//BF not used???
	CH4_DAC_2 = 0;		//BF not used???
	CH4_DAC_3 = 0;		//BF not used???
	CH4_DAC_4 = 0;		//BF not used???

/* BF del -> not used	
	Channel1_1_ADC_Correction = 0;
	Channel1_2_ADC_Correction = 0;
	Channel1_3_ADC_Correction = 0;//256;
	Channel1_4_ADC_Correction = 0;
	
	Channel2_1_ADC_Correction = 0;
	Channel2_2_ADC_Correction = 0;
	Channel2_3_ADC_Correction = 0;//256;
	Channel2_4_ADC_Correction = 0;
	
	Channel3_1_ADC_Correction = 0;
	Channel3_2_ADC_Correction = 0;
	Channel3_3_ADC_Correction = 0;//256;
	Channel3_4_ADC_Correction = 0;
	
	Channel4_1_ADC_Correction = 0;
	Channel4_2_ADC_Correction = 0;
	Channel4_3_ADC_Correction = 0;//256;
	Channel4_4_ADC_Correction = 0;
*/
/* BF del -> not used		
	CH1_X_Offset_1 = 0;
	CH1_X_Offset_2 = 0;
	CH1_X_Offset_3 = 0;
	CH1_X_Offset_4 = 0;
	
	CH2_X_Offset_1 = 0;
	CH2_X_Offset_2 = 0;
	CH2_X_Offset_3 = 0;
	CH2_X_Offset_4 = 0;
	
	CH3_X_Offset_1 = 0;
	CH3_X_Offset_2 = 0;
	CH3_X_Offset_3 = 0;
	CH3_X_Offset_4 = 0;
	
	CH4_X_Offset_1 = 0;
	CH4_X_Offset_2 = 0;
	CH4_X_Offset_3 = 0;
	CH4_X_Offset_4 = 0;
*/	
/* BF initialisation from protected Flash
	CH1_DAC_Correction_1 = 100;
	CH1_DAC_Correction_2 = 130;
	CH1_DAC_Correction_3 = 100;
	CH2_DAC_Correction_1 = 100;
	CH2_DAC_Correction_2 = 130;
	CH2_DAC_Correction_3 = 100;
	CH3_DAC_Correction_1 = 100;
	CH3_DAC_Correction_2 = 130;
	CH3_DAC_Correction_3 = 100;
	CH4_DAC_Correction_1 = 100;
	CH4_DAC_Correction_2 = 130;
	CH4_DAC_Correction_3 = 100;
*/
	
	VSync_Needed = 0;
	
	ClearPlane  = 0x00;
	DrawPlane   = 0x00;
	RemovePlane = 0x00;
	ClearPhase  = true;

	GridColorArrayPos         = 3;
	GridColor_Val             = 0x3F;
	GridColorArrayPos_Delayed = 2;
	//BF not used GridColor_Val_Delayed     = 0x15;	
	
	Rotary_Direction           = 0;
	Rotary_Direction_mem       = 0;
	Rotary_Direction_mem_pulse = 1;
	Rotary_Switch              = 0;
	Rotary_Steps               = 1;
	Rotary_Changed             = 0;
	
	Keyboard_mem     = 0;
	Keyboard_Changed = 0;
	
	ADC_Data_Available = 0;

	SIGNAL_StartFr_idx = 0;
	SIGNAL_OFFSET 	   = 0;
	SIGNALFaktor_idx   = 0;	
	
	FirEnabledCH1 = 0;
	FirEnabledCH2 = 0;
	FirEnabledCH3 = 0;
	FirEnabledCH4 = 0;
	
	//BF -> not used FirStartCH = 5;
	//BF -> not used FirStartCH_delayed = 5;
	
	SmoothEnabledCH1 = 0;
	SmoothEnabledCH2 = 0;
	SmoothEnabledCH3 = 0;
	SmoothEnabledCH4 = 0;
	
	USB_Data_Trans  = false;
	USB_SendAllData = false;
	USB_OnlyTrigger = false;
	
	ButtonChanged = false;
	RoteryChanged = false;
	
	DoDraw = false;
	
	PopUpPosition    = 0;
	IsPopuped        = false;
	PopupTimeCounter = 0;
	
	TriggerLevelChanged = 1;								// Was Triggerlevel changed
	TriggerModeChanged  = 1;								// Was Triggermode changed
	TriggerWayChanged   = 1;								// Was Triggerway changed
	TimebaseChanged     = 1;								// Was Timebase changed
	TimeOffsetChanged   = 1;								// Was Time_Offset changed
	SIGNALFaktorChanged = 1;								// Was SIGNALFaktor changed
	
	TriggerLevelActive = 0;								    	// Is Triggerlevel selected ?
	TimeOffsetActive   = 0;									// Is Time_Offset selected ?
	
	StatusbarChanged  = 0;									// When 1 then is changed
	ZeroPopupChanged  = 0;									// When 1 then is changed
	MenuPopupChanged  = 0;									// When 1 then is changed
	MenuPopupActive   = -1;									// Stores the actual Menupopup
	VoltageChangedCh1 = 1;									// Was Voltage changed
	VoltageChangedCh2 = 1;									// Was Voltage changed
	VoltageChangedCh3 = 1;									// Was Voltage changed
	VoltageChangedCh4 = 1;									// Was Voltage changed
	MenuPopupChanged2 = 0;									// Was MenuPopup changed
	MenuOnlyChanged  = 0;									// When 1 then is changed
	
	MenuItemChanged[0] = 0;
	MenuItemChanged[1] = 0;
	MenuItemChanged[2] = 0;
	MenuItemChanged[3] = 0;
	MenuItemChanged[4] = 0;
	MenuItemChanged[5] = 0;
	
	MenuItemPushed[0] = 0;				                    // When Menuitem is pushed drawed
	MenuItemPushed[1] = 0;				                    // When Menuitem is pushed drawed
	MenuItemPushed[2] = 0;				                    // When Menuitem is pushed drawed
	MenuItemPushed[3] = 0;				                    // When Menuitem is pushed drawed
	MenuItemPushed[4] = 0;				                    // When Menuitem is pushed drawed
	MenuItemPushed[5] = 0;				                    // When Menuitem is pushed drawed
	
	MenuStatusChanged = 0;									// When switching on/off a menu holds menunr
	
	VS_ZeroChangedCh1 = 1;									// Was Zero changed
	VS_ZeroChangedCh2 = 1;									// Was Zero changed
	VS_ZeroChangedCh3 = 1;									// Was Zero changed
	VS_ZeroChangedCh4 = 1;									// Was Zero changed
	VS_TrigLevelChanged = 1;								// Was Triggerlevel changed
	
	MenuPopupX = 0;
	MenuPopupY = 0;
	MenuPopupSizeX = 0;
	MenuPopupSizeY = 0;
	
	MenuStored      = 0;
	MenuActive      = 18;		//Startmenu
	MenuActiveOld   = 0;
	MenuChanged     = true;
	MenuTimeCounter = 0;										// Counter for Menu Pulldown
	
	MenuItemCount    = 0;											// Store the count of the Menuitems
	MenuOldItemCount = 0;										// Store the count of the old Menuitems
	
	New_Menu     = -1;
	Active_Menu  = -1;
	Menu_Changed = -1;
	
/*	BF not used
	Btns_Status[0] = 0;
	Btns_Status[1] = 0;
	Btns_Status[2] = 0;
	Btns_Status[3] = 0;
	Btns_Status[4] = 0;
	Btns_Status[5] = 0;
*/	
	wheelchanged = 0;
	Rot_Summary  = 0;
	
	Memory_Position = 0;

	UI_request         = 0;	

	//clear buffers
	for (cnt = 0; cnt < 32; cnt++)
	  LogicData[cnt] = 0;
	
//BF	for (cnt = 0; cnt < 301; cnt++)
//	  SIGNAL_IntBuf[cnt] = 0;
/*	
	for (cnt = 0; cnt < 1024; cnt++)
	{
		freq_re[cnt] = 0;
		freq_im[cnt] = 0;
	}

	for (cnt = 0; cnt < 256; cnt++)
	{
		SIGNAL1_Histo[cnt] = 0;
		SIGNAL2_Histo[cnt] = 0;
		SIGNAL3_Histo[cnt] = 0;
		SIGNAL4_Histo[cnt] = 0;
	}

	// delete signals
	for (cnt = 0; cnt < 16385; cnt++) {
		SIGNAL1[cnt] = ADC_ZERO;
		SIGNAL2[cnt] = ADC_ZERO;
		SIGNAL3[cnt] = ADC_ZERO;
		SIGNAL4[cnt] = ADC_ZERO;
	        SIGNALM[cnt] = ADC_ZERO;
	}	
*/
}
//################################################################################################################################
void Hardware::Setup_Hardware(void)					// Setup the Hardware
{
	dma->np_piointerruptmask = 0x00;							// disable all IRQs
	dma->np_piodirection = 0x01;								// set all bits to output
	dma->np_piodata = 0x00;									// Set to 0

	serstartled->np_piointerruptmask = 0x00;						// disable all IRQs
	serstartled->np_piodirection = 0x01;							// set all bits to output
	serstartled->np_piodata = 0x00;								// Set to 0

	serstartsw->np_piointerruptmask = 0x00;							// disable all IRQs
	serstartsw->np_piodirection = 0x01;							// set all bits to output
	serstartsw->np_piodata = 0x00;								// Set to 0

	serstartdac->np_piointerruptmask = 0x00;						// disable all IRQs
	serstartdac->np_piodirection = 0x01;							// set all bits to output
	serstartdac->np_piodata = 0x00;								// Set to 0

	serdata->np_piointerruptmask = 0x00;							// disable all IRQs
	serdata->np_piodirection = 0xFF;							// set all bits to output
	serdata->np_piodata = 0x00;								// Set to 0

	key_reset->np_piointerruptmask = 0x00;							// disable all IRQs
	key_reset->np_piodirection = 0x01;							// set all bits to output
	key_reset->np_piodata = 0x01;								// Set to 1

	key_int->np_piointerruptmask = 0x00;							// disable all IRQs
	key_int->np_piodirection = 0x00;							// set all bits to input
	key_int->np_piodata = 0x00;								// Set to 0

	key->np_piointerruptmask = 0x00;							// disable all IRQs
	key->np_piodirection = 0x00;								// set all bits to input
	key->np_piodata = 0x00;									// Set to 0

	rot_speed_read->np_piointerruptmask = 0x00;						// disable all IRQs
	rot_speed_read->np_piodirection = 0x01;							// set all bits to output
	rot_speed_read->np_piodata = 0x00;							// Set to 0

	data_adr->np_piointerruptmask = 0x00;							// disable all IRQs
	data_adr->np_piodirection = 0x01;							// set all bits to output
	data_adr->np_piodata = 0x00;								// Set to 0
	
	mode->np_piointerruptmask = 0x00;							// disable all IRQs
	mode->np_piodirection = 0x01;								// set all bits to output
	mode->np_piodata = 0x00;								// Set to 0
	
	start_acq->np_piointerruptmask = 0x00;							// disable all IRQs
	start_acq->np_piodirection = 0x01;							// set all bits to output
	start_acq->np_piodata = 0x00;								// Set to 0

	acq_ready->np_piointerruptmask = 0x00;							// disable all IRQs
	acq_ready->np_piodirection = 0x00;							// set all bits to input
	acq_ready->np_piodata = 0x00;								// Set to 0

	reset_watchdog->np_piointerruptmask = 0x00;						// disable all IRQs
	reset_watchdog->np_piodirection = 0x01;							// set all bits to output
	reset_watchdog->np_piodata = 0x00;							// Set to 0

	la_data->np_piointerruptmask = 0x00;							// disable all IRQs
	la_data->np_piodirection = 0x00;							// set all bits to input
	la_data->np_piodata = 0x00;								// Set to 0

	la_interrupt->np_piointerruptmask = 0x00;						// disable all IRQs
	la_interrupt->np_piodirection = 0x00;							// set all bits to input
	la_interrupt->np_piodata = 0x00;							// Set to 0

	la_gate->np_piointerruptmask = 0x00;							// disable all IRQs
	la_gate->np_piodirection = 0x01;							// set all bits to output
	la_gate->np_piodata = 0x00;									// Set to 0

	la_pulse->np_piointerruptmask = 0x00;							// disable all IRQs
	la_pulse->np_piodirection = 0x01;							// set all bits to output
	la_pulse->np_piodata = 0x00;								// Set to 0

	//out_test->np_pioedgecapture = 0x00; 							// clear all existing IRQ conditions
	//out_test->np_piodirection = 0x01;								// set all bits to output
	//out_test->np_piodata = 0x08;

	boot_reset_key->np_piointerruptmask = 0x00;						// disable all IRQs
	boot_reset_key->np_piodirection = 0x00;							// set all bits to input
	boot_reset_key->np_piodata = 0x00;							// Set to 0

	power_on_boot_key->np_piointerruptmask = 0x00;						// disable all IRQs
	power_on_boot_key->np_piodirection = 0x00;						// set all bits to input
	power_on_boot_key->np_piodata = 0x00;							// Set to 0
	
	//key_test->np_piointerruptmask = 0x00;							// disable all IRQs
	//key_test->np_piodirection = 0x00;							// set all bits to input
	//key_test->np_piodata = 0x00;			

    if ((boot_reset_key->np_piodata == 0x00) && (power_on_boot_key->np_piodata == 0x00)) {
        printf("No Keyboard selected\n");
        keyboard_found = 1;
    } 
	else if ((boot_reset_key->np_piodata == 0x01) && (power_on_boot_key->np_piodata == 0x00)) {
        printf("Power on Boot Pressed\n");
        keyboard_found = 2;
    } 
	else if ((boot_reset_key->np_piodata == 0x00) && (power_on_boot_key->np_piodata == 0x01)) {
        printf("Reset on Boot Pressed\n");
        keyboard_found = 3;
    } else {
        printf("Keyboard found\n");
        keyboard_found = 4;
    }

	triggering = 0;
}
//################################################################################################################################
void Hardware::Setup_Interrupts(void)					// Setup the Interrupts
{
	if (keyboard_found == 4)
	{
		DoEnableKeyInterrupt();
		DoEnableRotInterrupt();
	}
	
	DoEnableUARTInterrupt();
	DoEnableUART2Interrupt();
	//BF not used DoEnableTimerInterrupt();
	DoEnableADCInterrupt();	
	DoEnableReadVSyncInterrupt();
	//    DoEnableLogicAnalyserInterrupt();
	DoEnableTimer2Interrupt();
	DoEnableTimer3Interrupt();	
}
//################################################################################################################################
void Hardware::Set_Vars_Default(void)					//Resets all vars to standard values
{
	int cnt;
	
	// Main/Delayed - Timebase
	MenuStatus[MENU_TIMEBASE][0] = 1;                               // Main
	MenuStatus[MENU_TIMEBASE][1] = 0;                               // Delayed
	MenuStatus[MENU_TIMEBASE][2] = 0;                               // XY-Mode
	MenuStatus[MENU_TIMEBASE][3] = 246;                     	// Roll-Mode 
	MenuStatus[MENU_TIMEBASE][4] = 246;                             // Shift-Mode
	MenuStatus[MENU_DISPLAY][2] = 136;                              // Display - Grid - 100%
	XY_Mode = 0;                                               	// Normal Mode - No XY-Mode
	USTB_Mode     = USTB_OFF;					// ultra slow timebase off	
	USTB_Mode_bak = USTB_ROLL;

	test_signal   = 0;

	MenuStatus[MENU_AUTOSCALE][1] = 240;                 		// Autoscale - Search Slow TBs
	
	Selected_Timebase  = 4;                                         // 50 ns
	SIGNALFaktor_idx   = 0;                                         // non zoom
	SIGNAL_StartFr_idx = 0;                                         // running. so 0
	SIGNAL_OFFSET      = 0;                                         // signal offset
	
	Timebase_Offset_Pos = -300;//-298;                              // Timebase Offset
	Memory_Position     = 0;                               		// Memory Position

//BF ins	
	//Trig_Pos_Mem           = 300; 
	Trig_Pos_Display       = 300;      
	Trig_Pos_Display_dmode = 300;             
	Trig_Pos_Zoom          = 1.0;                     
	//MemWinStart           = -300;       

	Trig_Pos_Mem_old           = 300;           	
	Trig_Pos_Display_old       = 300;    
	Trig_Pos_Display_dmode_old = 300;   	
	Trig_Pos_Zoom_old          = 1.0;    
	MemWinStart_old           = -300;     

// BF end
	
	Trig_Pos_Mem = 300;
	MemWinStart = 0;   	
	dmode_Window_Offset_Pos = 0;
		
	SwitchesTB = 0;                                                 // timebase switches
	timebase_reg = 0xFFFFFFFF;                                      // fastest timebase
	Display_Timebase = 4;                                           // Displayed timebase is 50 ns
	
	dmode_Selected_Timebase = 3;                                    // delayed timebase is 20 ns
	dmode_SIGNALFaktor_idx = 0;                                     // non zoom for delayed windows
	dmode_factor = 0;                                               // factor for delayed windows cursor calculation
	dmode_SIGNAL_StartFr_idx = 0;                                   // running. so 0
	dmode_SIGNAL_OFFSET = 0;                                        // signal offset
	
	Cursor_Delayed_1    = 180;                                      // Delayed windows cursor position 1
	Cursor_Delayed_2    = 420;                                      // Delayed windows cursor position 2
	Cursor_Delayed_Size = 240;                                      // Delayed windows size
	

	// Trigger
	// Trigger Mode
	MenuStatus[MENU_TRIGGERMODE][0] = 93;                                         // Triggering - Auto
	MenuStatus[MENU_TRIGGERMODE][1] = 95;                                         // Triggering - Coupling DC
	MenuStatus[MENU_TRIGGERMODE][2] = 97;                                         // Triggering - LF Reject
	MenuStatus[MENU_TRIGGERMODE][4] = 104;                                        // Triggering - External Probe 1:1
	
	MenuPopupStatus[9][0] = 3;
	MenuPopupStatus[9][1] = 2;
		
	EdgeToggle = 1;                                                 // Holdoff deaktive
	
	// Trigger Edge
	MenuStatus[MENU_TRIGGEREDGE][0] = 2;                                          // Triggering - positive edge
	MenuStatus[MENU_TRIGGEREDGE][1] = 138;                                        // Triggering - Source = channel 1
	MenuStatus[MENU_TRIGGEREDGE][2] = 0;                                          // Triggering - no externel triggering
	MenuStatus[MENU_TRIGGEREDGE][3] = 0;                                          // Triggering - no externel TV triggering
	MenuPopupStatus[28][0] = 3;
	MenuPopupStatus[28][1] = 2;
	
	
	// Trigger Pulse
	MenuStatus[MENU_PULSEWIDTH][0] = 138;                                        // Triggering - Source Channel 1
	//MenuStatus[MENU_PULSEWIDTH][1] = 2;                                          // Triggering - Negative Pulse
	MenuStatus[MENU_PULSEWIDTH][2] = 3;                                          // Triggering - bigger - smaller - then
	
	// Quick Print
	//    MenuStatus[MENU_QUICKPRINT][0] = 241;                                        // quick Print - USB
	//    MenuStatus[MENU_QUICKPRINT][1] = 240;                                        // quick Print - RS-232
	
	Selected_Trigger_Source = 1;                                    // Selected Trigger Source is Channel 1
	SelectedEdgeExtern = 0;                                         // Trigger Edge by extern triggering
			
	//BF set zero levels to default
	if (NumberOfChannels == 2)
	{
		ZeroLevelCH1 = (int)(GRID_HEIGHT / 4);		// 1/4 grid height
		ZeroLevelCH2 = (int)((GRID_HEIGHT / 4) * 3);	// 3/4 grid height
		ZeroLevelCH3 = (int)(GRID_HEIGHT >> 1);	
		ZeroLevelCH4 = (int)(GRID_HEIGHT >> 1);
	}
	else
	{
		ZeroLevelCH1 = (int)(GRID_HEIGHT / 5.333);			//10% line
		ZeroLevelCH2 = (int)((GRID_HEIGHT / 8) * 3);			//third div
		ZeroLevelCH3 = (int)((GRID_HEIGHT / 8) * 5);			//fifth div
		ZeroLevelCH4 = (int)(GRID_HEIGHT - (GRID_HEIGHT / 5.333));	//90% line
	}

	ZeroLevelCH1_Old = ZeroLevelCH1;
	ZeroLevelCH2_Old = ZeroLevelCH2;
	ZeroLevelCH3_Old = ZeroLevelCH3;
	ZeroLevelCH4_Old = ZeroLevelCH4;

	Virtual_ZeroLevelCH1 = ZeroLevelCH1 - (GRID_HEIGHT / 2);	//Virtual zeroes are related to 1/2 grid height,
	Virtual_ZeroLevelCH2 = ZeroLevelCH2 - (GRID_HEIGHT / 2);	//means that VZero = 0 is the middle of the grid
	Virtual_ZeroLevelCH3 = ZeroLevelCH3 - (GRID_HEIGHT / 2);	
	Virtual_ZeroLevelCH4 = ZeroLevelCH4 - (GRID_HEIGHT / 2);
	
	Virtual_ZeroLevelXYCH1 = 0;	// 0 = middle of the grid
	Virtual_ZeroLevelXYCH2 = 0;	// 0 = middle of the grid
	Virtual_ZeroLevelXYCH3 = 0;	// 0 = middle of the grid	
	Virtual_ZeroLevelXYCH4 = 0;	// 0 = middle of the grid


	//BF set trigger levels
	Trigger_Pos_CH1 = ZeroLevelCH1;			// Trigger Level Channel 1
	Trigger_Pos_CH2 = ZeroLevelCH2;			// Trigger Level Channel 2
	Trigger_Pos_CH3 = ZeroLevelCH3;			// Trigger Level Channel 3
	Trigger_Pos_CH4 = ZeroLevelCH4;			// Trigger Level Channel 4
	Trigger_Pos_CHE = 15;				// Trigger Level Extern Trigger Source
	
	//trg_val_reg = 0xB1;                                             // Trigger Value
	//trg_hyst_reg = 0xA9;                                            // Trigger Hysterese
	trg_val_CHI_reg   = 0x00A0;
	trg_val_CHII_reg  = 0x00A0;
	trg_val_CHIII_reg = 0x00A0;
	trg_val_CHIV_reg  = 0x00A0;
	
	ext_trg_val_reg  = 0x80;                                         // Trigger Extern Value
	
	trig_range_reg   = 0;                                             // Trigger Range
	trig_holdoff_reg = 0;                                             // Trigger Holdoff
	trig_width_reg   = 0;                                             // Trigger Width
	
	ctrl_reg         = 0x0007;                                        // Control register
	//adc_ctrl_reg = 0x01C0;                                          // ADC Control register
	adc_ctrl_reg     = 0x81C0;                                          // ADC Control register - Auto Slope detect off
	
	pre_reg          = 0x6C;                                                 // PreTrigger Value
	//    channel_Adr_add = 0;                                            // Channel Add Value
	//    adc_change12_reg &= 0x0000FF00;                                   // ADC Change  - let ADC Shift Bits set
	//    adc_change34_reg &= 0x0000FF00;                                   // ADC Change  - let ADC Shift Bits set
	
	//    adc_ctr12_reg &= 0x000000FF;
	//    adc_ctr34_reg &= 0x000000FF;
	
	triggering = 1;                                                 // Triggering - Free Run
	TriggerWay = 1;                                                 // Edge
	Continius  = 1;                                                 // Continius Running
	
	//Trigger_Offset_Pos = 353;//(pre_reg << 2);	//BF not used
	
	HoldOff_Value = 0;
	HoldOff_Expo  = 1;   //ns
	HoldOff_Steps = 40;
	
	Pulse11_Value = 16;
	Pulse11_Expo  = 1;   //ns
	Pulse11_Steps = 8;
	
	Pulse12_Value = 8;
	Pulse12_Expo  = 1;   //ns
	Pulse12_Steps = 8;
	
	Pulse21_Value = 16;
	Pulse21_Expo  = 1;   //ns
	Pulse21_Steps = 8;
	
	Pulse22_Value = 16;
	Pulse22_Expo  = 1;   //ns
	Pulse22_Steps = 8;
/* BF del	
	Math_Off_Mul_Value     = 1;
	Math_Off_Mul_Value_int = 1;
	Math_Off_Mul_Expo      = 0;   //�V
	Math_Off_Mul_Steps     = 1;
	
	Math_Off_Sub_Value     = 1;
	Math_Off_Sub_Value_int = 1;
	Math_Off_Sub_Expo      = 0;   //mV
	Math_Off_Sub_Steps     = 1;
	
	Math_Off_Add_Value     = 1;
	Math_Off_Add_Value_int = 1;
	Math_Off_Add_Expo      = 0;   //mV
	Math_Off_Add_Steps     = 1;
*/
	math_scale     = 11;	//BF added -> 5V default
	math_mul_scale = 177;	//BF -> 5V
	math_sub_scale = 161;	//BF -> 5V 
	math_add_scale = 161;	//BF -> 5V
	
	//BF added for new offset calculation
	Math_Offset     = 0;
	Math_Mul_Offset = 0;
	Math_Sub_Offset = 0;
	Math_Add_Offset = 0;
	
	Math_Offset_mul.Init(0.000001, 0.000001, 1000, 0.000001, 2, 3, "", "", "V");
	Math_Offset_mul.RenderText();
	Math_Offset_add.Init(0.001, 0.001, 1000, 0.001, 2, 3, "", "", "V");
	Math_Offset_add.RenderText();
	Math_Offset_sub.Init(0.001, 0.001, 1000, 0.001, 2, 3, "", "", "V");
	Math_Offset_sub.RenderText();

	// Channel 1
	Channel_1_Active = 1;                                           // Channel 1 active
	Channel_1_Active_Old = 0;                                       // Channel 1 old must be 0
	MenuStatus[MENU_CHANNEL1][0] = 8;                                           // Channel 1 - Coupling AC
	MenuStatus[MENU_CHANNEL1][1] = 240;                                         // Channel 1 - BW Linit off
	MenuStatus[MENU_CHANNEL1][2] = 240;                                         // Channel 1 - Invert off
	MenuStatus[MENU_CHANNEL1][3] = 104;                                         // Channel 1 - Probe 1.0 : 1
	
	MenuPopupStatus[13][0] = 2;                                     // Popup Coupling = DC
	MenuPopupStatus[13][1] = 2;
	MenuPopupStatus[13][2] = 3;
	
	SwitchesCH1 = 0x0F1A;                                           // Switches for Channel 1 and for the other the AC bit
	Selected_Voltage_CH1 = 11;                                      // Voltage 5V

// BF not used ?
	CH1_DAC_1 = 0;                                                  // channel 1 dac 1 offset
	CH1_DAC_2 = 0;                                                  // channel 1 dac 2 offset
	CH1_DAC_3 = 0;                                                  // channel 1 dac 3 offset
	CH1_DAC_4 = 0;                                                  // channel 1 dac 4 offset
	
	signal_zoomed1 = false;                                         // signal not zoomed
	
	// Channel2
	Channel_2_Active = 1;                                           // Channel 2 active
	Channel_2_Active_Old = 0;                                       // Channel 2 old must be 0
	MenuStatus[MENU_CHANNEL2][0] = 8;                                           // Channel 2 - Coupling AC
	MenuStatus[MENU_CHANNEL2][1] = 240;                                         // Channel 2 - BW Linit off
	MenuStatus[MENU_CHANNEL2][2] = 240;                                         // Channel 2 - Invert off
	MenuStatus[MENU_CHANNEL2][3] = 104;                                         // Channel 2 - Probe 1.0 : 1
	
	MenuPopupStatus[14][0] = 2;                                     // Popup Coupling = DC
	MenuPopupStatus[14][1] = 2;
	MenuPopupStatus[14][2] = 3;
	
	SwitchesCH2 = 0x001A;                                           // Switches for Channel 2
	Selected_Voltage_CH2 = 11;                                      // Voltage 5V

// BF not used ?
	CH2_DAC_1 = 0;                                                  // channel 2 dac 1 offset
	CH2_DAC_2 = 0;                                                  // channel 2 dac 2 offset
	CH2_DAC_3 = 0;                                                  // channel 2 dac 3 offset
	CH2_DAC_4 = 0;                                                  // channel 2 dac 4 offset

	
	signal_zoomed2 = false;                                         // signal not zoomed
	
	if (NumberOfChannels == 4)
	{
		// Channel 3
		Channel_3_Active = 1;                                           // Channel 3 active
		Channel_3_Active_Old = 0;                                       // Channel 3 old must be 0
		MenuStatus[MENU_CHANNEL3][0] = 8;                                           // Channel 3 - Coupling AC
		MenuStatus[MENU_CHANNEL3][1] = 240;                                         // Channel 3 - BW Linit off
		MenuStatus[MENU_CHANNEL3][2] = 240;                                         // Channel 3 - Invert off
		MenuStatus[MENU_CHANNEL3][3] = 104;                                         // Channel 3 - Probe 1.0 : 1
	
		MenuPopupStatus[15][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[15][1] = 2;
		MenuPopupStatus[15][2] = 3;
	
		SwitchesCH3 = 0x001A;                                           // Switches for Channel 3
		Selected_Voltage_CH3 = 11;                                      // Voltage 5V

// BF not used ?	
		CH3_DAC_1 = 0;                                                  // channel 3 dac 1 offset
		CH3_DAC_2 = 0;                                                  // channel 3 dac 2 offset
		CH3_DAC_3 = 0;                                                  // channel 3 dac 3 offset
		CH3_DAC_4 = 0;                                                  // channel 3 dac 4 offset
	
		signal_zoomed3 = false;                                         // signal not zoomed
	
		// Channel 4
		Channel_4_Active = 1;                                           // Channel 4 active
		Channel_4_Active_Old = 0;                                       // Channel 4 old must be 0
		MenuStatus[MENU_CHANNEL4][0] = 8;                                           // Channel 4 - Coupling AC
		MenuStatus[MENU_CHANNEL4][1] = 240;                                         // Channel 4 - BW Linit off
		MenuStatus[MENU_CHANNEL4][2] = 240;                                         // Channel 4 - Invert off
		MenuStatus[MENU_CHANNEL4][3] = 104;                                         // Channel 4 - Probe 1.0 : 1
	
		MenuPopupStatus[16][0] = 2;                                     // Popup Coupling = DC
		MenuPopupStatus[16][1] = 2;
		MenuPopupStatus[16][2] = 3;
	
		SwitchesCH4 = 0x001A;                                           // Switches for Channel 4
		Selected_Voltage_CH4 = 11;                                      // Voltage 5V

// BF not used ?	
		CH4_DAC_1 = 0;                                                  // channel 4 dac 1 offset
		CH4_DAC_2 = 0;                                                  // channel 4 dac 2 offset
		CH4_DAC_3 = 0;                                                  // channel 4 dac 3 offset
		CH4_DAC_4 = 0;                                                  // channel 4 dac 4 offset
	
		signal_zoomed4 = false;                                         // signal not zoomed

	}
	
	Channel_Math_Active = 0;                                        	// Math channel off
	MenuStatus[MENU_MATH][1] = 0;                                          	// standart math FFT off
	MenuStatus[MENU_MATH][2] = 0;                                          	// standart math 1*2 off
	MenuStatus[MENU_MATH][3] = 1;                                          	// standart math 1-2 on
	MenuStatus[MENU_MATH][4] = 0;                                          	// standart math 1+2 off

	math_mul_scale = 177;							//5V	math scaling default setting
	math_sub_scale = 161;							//5V	math scaling default setting
	math_add_scale = 161;							//5V	math scaling default setting
 
	MenuStatus[MENU_FFT][0] = 138;                                          // source = channel 1
	MenuStatus[MENU_FFT][1] = 193;                                          // window = rectangle
	MenuStatus[MENU_FFT][2] = 66;                                          	// mode   = linear
	MenuStatus[MENU_FFT][3] = 83;                                          	// length = 512
	
	FFT_Mode    = FFT_OFF;							// FFT off
	FFT_NewData = 0;
	FFT_Length  = FFT_512;
	FFT_Level   = 9;							// FFT_Level = ld(FFT_Length)
	FFT_Windex  = -1;							// FFT window index default is rect
	FFT_Scale   = 2;

	
	// deactivate Trigger TV
	//MenuStatus[MENU_TRIGGEREDGE][3] = 246;                                          // Trigger TV deactive
	
	// deactive LF Reject and Holdoff
	//MenuStatus[MENU_TRIGGERMODE][2] = 246;                                          // Reject deactive
	//MenuStatus[MENU_TRIGGERMODE][3] = 246;                                          // Holdoff deactive
	
	MenuPopupStatus[8][0] = 3;
	MenuPopupStatus[8][1] = 2;
	MenuPopupStatus[8][2] = 2;

//    Recalc_Trigger();

// BF default timebase is 4 !!!
	if (Selected_Timebase > 7)
	 { adc_change12_reg |= 0x01000000; }
	else
	 { adc_change12_reg &= 0xFEFFFFFF; }

	adc_change12_reg |= 0x02000000; 				//filter
	
	//Recalc_Vars();						//BF del 
	
	// Cursors
	MenuStatus[MENU_CURSOR][0] = 27;                                         // Cursor soruce = channel 1
	
	Cursor_Enabled = false;
	Cursor_Both_Selected = 0;	
	SelectedCursor = 0;
	Cursor_Horizontal_Active = 0;
	Cursor_Horizontal_Position_Real1 = 103;
	Cursor_Horizontal_Position_Real2 = 203;	
	Cursor_Vertical_Active = 0;
	Cursor_Vertical_Position_Real1 = 103;
	Cursor_Vertical_Position_Real2 = 203;	
	Cursor_Vertical_Position_Real_XY_1 = 103;
	Cursor_Vertical_Position_Real_XY_2 = 203;	
		

    	// Quick Measure
	QM_Enabled = false;
	
	QM_Type[0] = 5;
	QM_Type[1] = 8;
	QM_Type[2] = 0;
	
	QM_Channel[0] = 1;
	QM_Channel[1] = 1;
	QM_Channel[2] = 1;	
    	
	QM_Horizontal_Active = 0;
	QM_Horizontal_Position_Real1 = 103;
	QM_Horizontal_Position_Real2 = 203;	

	QM_Vertical_Active = 0;
	QM_Vertical_Position_Real1 = 103;
	QM_Vertical_Position_Real2 = 203;	

	Quick_Measure_Threshold_btn_select = 1;
	
	// Display settings
	GridColorArrayPos         = 1;                                          // Normal Grid 33 %
	GridColor_Val             = GridColorArray[GridColorArrayPos];     	// GridColor White
	GridColorArrayPos_Delayed = 1;                                  	// Delayed Grid 33 %
	//BF not used GridColor_Val_Delayed     = 0x15;                                   	// GridColore Gray

 	MenuStatus[MENU_DISPLAY][0] = 240;                                         // Display - Persist off
	MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;                     // Display - Grid 33%
	MenuStatus[MENU_DISPLAY][3] = 241;                                         // Display - Vectors on
	MenuStatus[MENU_TIMEBASE][5] = 240;                                        // Timebase - Browse off

	// Aquire
	MenuStatus[MENU_ACQUIRE][0] = 1;					// Aquire - Normal on
	MenuStatus[MENU_ACQUIRE][1] = 0;					// Aquire - Averaging
	MenuStatus[MENU_ACQUIRE][2] = 0;					// no noise suppression

	// LEDs
	LED_ON[0] = 1;			                                        // Select Channel 1
	LED_ON[1] = 1;			                                        // Select Channel 2
	LED_ON[2] = 1;			                                        // Select Channel 3
	LED_ON[3] = 1;			                                        // Select Channel 4
	LED_ON[4] = 0;			                                        // Select Channel Math
	LED_ON[5] = 1;			                                        // General
	LED_ON[6] = 0;			                                        // Cursor
	LED_ON[7] = 0;			                                        // Quick Measure
	LED_ON[8] = 1;			                                        // Edge
	LED_ON[9] = 0;			                                        // Pattern - Not Used
	LED_ON[10] = 0;			                                        // Pulse Width
	LED_ON[11] = 0;			                                        // More - Not Used
	LED_ON[12] = 1;			                                        // Run/Stop Green
	LED_ON[13] = 0;			                                        // Run/Stop Red
	LED_ON[14] = 0;			                                        // Single Red
	LED_ON[15] = 0;			                                        // Single Green
	
	MenuItemChanged[0] = true;
	MenuItemChanged[1] = true;
	MenuItemChanged[2] = true;
	MenuItemChanged[3] = true;
	MenuItemChanged[4] = true;
	MenuItemChanged[5] = true;
	
	RemovePlane |= 0x1F;
	
	ClearPlanes();
	
	//    config_changed = true;
		
}

//#############################################################################################################################################
char Hardware::SearchZero(char channel, char level, int *DAC_Offset, int *ZeroSign)
{
	
	int lcnt = 0;
	//BF del int lcnt2 = 0;
	unsigned long buflong = 0, buflong1 = 0;//, buflong2 = 0;
	//char is_running = 1;

#ifdef _Debug_FindZero_
    	printf("Start searching zero %d\n", channel);
    
    	printf("ZeroSign %8x %d\n", ZeroSign[0], ZeroSign[0]);
#endif
	
	lcnt = 0;
	DAC_Offset[0] = 0x2000;		//8192
	//is_running = 1;
	
	SetDacOffset(channel);
	SetSwitches(channel, level);
	
	triggering = 0;								
	ctrl_reg = 0x0083;							        // Trigger_Master / Trigger_INT / Free Run  / Zero Line search bit
	if (NumberOfChannels == 2) adc_ctrl_reg = 0x00C0;				// Disable Trigger sources and remove the master bits
	else  adc_ctrl_reg = 0x0000;						        // Remove the master bits
	
	switch (channel)
	{
		case 1 : adc_ctrl_reg |= 0x0100; break;                     // Set channel 1 Master bit
		case 2 : adc_ctrl_reg |= 0x0200; break;                     // Set channel 2 Master bit
		case 3 : adc_ctrl_reg |= 0x0400; break;                     // Set channel 3 Master bit
		case 4 : adc_ctrl_reg |= 0x0800; break;                     // Set channel 4 Master bit
	}

	SetupADC();
	
	nr_delay(100);
	
	ctrl_reg = 0x0183;                                               // Add zero_line_adj
	
	SetupADC();

	buflong = 0x00000000;
	if (channel < 3)	// Channel 1 & 2
	{
		
		while (1 == 1)
		{
			data_adr->np_piodata = 0x01;
			
			buflong = READADC(1);
			//printf("buflong %8x %d\n", buflong, buflong);
			if ((buflong & 0x00008000) == 0x00008000)
			{
			
				buflong1 = READADC(1) & 0x3FFF;
							
				ZeroSign[0] = (int) (buflong1 - 8192);		// Wertübergabe an NIOS
			
		//          printf("buflong_ch1 %8x %d\n", buflong, buflong);
		          	//printf("buflong1 %8x %d\n", buflong1, buflong1);
				printf("Channel %d ZeroSign %d\n", channel, ZeroSign[0]);	
				break;
			}
			
			data_adr->np_piodata = 0x00;
			lcnt++;
			
			if (lcnt == 50000) break;
		}
	}
	else	// Channel 3 & 4
	{
		lcnt = 0;
		while (1 == 1)		
		{
			data_adr->np_piodata = 0x01;

			buflong = READADC(3);

			buflong = READADC(1);	
			
			if ((buflong & 0x00008000) == 0x00008000)
			{
				buflong1 = READADC(3) & 0x3FFF;
								
				ZeroSign[0] = (int)buflong1 ;	//(buflong1 - 8192);//BF test
				
				printf("Channel %d ZeroSign %d\n", channel, ZeroSign[0]);	
				break;
			}
			
			data_adr->np_piodata = 0x00;
			lcnt++;
			if (lcnt == 50000) break;
		}
	}
	lcnt = 0;
	data_adr->np_piodata = 0x00;


	//buflong2 = READADC(channel);
	    
#ifdef _Debug_FindZero_
	printf("buflong %8x %d\n", buflong, buflong);
	printf("buflong1 %8x %d\n", buflong1, buflong1);
	//printf("buflong2 %8x %d\n", buflong2, buflong2);
	printf("ZeroSign %8x %d\n", ZeroSign[0], ZeroSign[0]);
  //  printf("%i %i : dir : %i lcnt : %i  BB : %i  BT : %i CZSO : %i \n", channel, level, dir, lcnt, bottom_val, top_val, ZeroSign[0]);
#endif

	ctrl_reg = 0x0083;	// Trigger_Master / Trigger_INT / FreeRun bit  /
	SetupADC();


	return 0;
}
//#############################################################################################################################################
char Hardware::SearchZeros(void)
{
	char IsSearching = true;
	int searchcnt = 0;
	
	if ((Search_Mode == false) && (Search_Auto == false)) return 0;

	Stop_Record();
	AutoTimerOff = true;
	
	//reset_watchdog->np_piodata = 0x00;						// Disable WatchDog
	#ifdef _Debug_FindZero_
	printf("We start searching\n");
	#endif
		
	DoDisableUARTInterrupt();
	DoDisableADCInterrupt();
	
	//    if (Search_Auto == false)
	//    {
		Display::DRAWROUNDBUTTON(230, 180, 180, 80, 0, 0);
		Display::TEXTOUTxvbig("Searching zero lines.", 247, 192, 1, UI_Plane2);
		Display::TEXTOUTxvbig("Remove all inputs.", 247, 212, 1, UI_Plane2);
		Display::TEXTOUTxvbig("Can take up to 1 min.", 247, 232, 1, UI_Plane2);
	//    }
	
	// Backup old vars
	Channel_1_Active_bak = Channel_1_Active;
	Channel_2_Active_bak = Channel_2_Active;
	Channel_3_Active_bak = Channel_3_Active;
	Channel_4_Active_bak = Channel_4_Active;
	
	Selected_Timebase_bak  = Selected_Timebase;
	SIGNALFaktor_idx_bak   = SIGNALFaktor_idx;
	SIGNAL_StartFr_idx_bak = SIGNAL_StartFr_idx;
	timebase_reg_bak       = timebase_reg;
	Display_Timebase_bak   = Display_Timebase;
	Continius_bak          = Continius;
	SingleMode_bak         = SingleMode;
	
	triggering_bak   = triggering;
	ctrl_reg_bak     = ctrl_reg;
	adc_ctrl_reg_bak = adc_ctrl_reg;
	
	// backup settings
	CH1_DAC_Offset_bak = CH1_DAC_Offset;
	CH2_DAC_Offset_bak = CH2_DAC_Offset;
	CH3_DAC_Offset_bak = CH3_DAC_Offset;
	CH4_DAC_Offset_bak = CH4_DAC_Offset;
	
	CH1_DAC_Offset = 8192;	//Range middle
	CH2_DAC_Offset = 8192;
	CH3_DAC_Offset = 8192;
	CH4_DAC_Offset = 8192;
	
	/*BF not needed
	
	CH1_DAC_Correction_1_bak = CH1_DAC_Correction_1;
	CH1_DAC_Correction_2_bak = CH1_DAC_Correction_2;
	CH1_DAC_Correction_3_bak = CH1_DAC_Correction_3;
	
	CH2_DAC_Correction_1_bak = CH2_DAC_Correction_1;
	CH2_DAC_Correction_2_bak = CH2_DAC_Correction_2;
	CH2_DAC_Correction_3_bak = CH2_DAC_Correction_3;
	
	CH3_DAC_Correction_1_bak = CH3_DAC_Correction_1;
	CH3_DAC_Correction_2_bak = CH3_DAC_Correction_2;
	CH3_DAC_Correction_3_bak = CH3_DAC_Correction_3;
	
	CH4_DAC_Correction_1_bak = CH4_DAC_Correction_1;
	CH4_DAC_Correction_2_bak = CH4_DAC_Correction_2;
	CH4_DAC_Correction_3_bak = CH4_DAC_Correction_3;
	*/
	
	Channel_1_Active = true;
	Channel_2_Active = true;
	
	if (NumberOfChannels > 2)
	{
		Channel_3_Active = true;
		Channel_4_Active = true;
	}
	
	Continius = 0;
	//   SingleMode = 1;
	
	if (adc_started)
	{
		while (acq_ready->np_piodata == 0x01)
		{}
		adc_started = false;
	}
	
	Selected_Timebase = 4;                                          // 50 nS
	SIGNALFaktor_idx = 0;                                           // zoom factor 0
	SIGNAL_StartFr_idx = 0;                                         // running. so 0
	
	timebase_reg = 0xFFFFFFFF;                                      // real timebase 50ns (1GSa/s)
	Display_Timebase = 4;                                           // Displayed timebase is 50ns
	
	// start condition made -> start searching

	searchcnt = 0;
	IsSearching = true;
	while (IsSearching)
	{
		searchcnt++;
		if (searchcnt == 3) break;
	
		IsSearching = SearchZero(1, 9, &CH1_DAC_Offset, &DAC_Correction[0][0]);	//channel 1 correction for 1er Ranges
	}
	searchcnt = 0;
	IsSearching = true;
	while (IsSearching)
	{
		searchcnt++;
		if (searchcnt == 3) break;
		IsSearching = SearchZero(1, 10, &CH1_DAC_Offset, &DAC_Correction[0][1]);//channel 1 correction for 2er Ranges
	}
	searchcnt = 0;
	IsSearching = true;
	while (IsSearching)
	{
		searchcnt++;
		if (searchcnt == 3) break;
		IsSearching = SearchZero(1, 11, &CH1_DAC_Offset, &DAC_Correction[0][2]);//channel 1 correction for 5er Ranges
	}
	searchcnt = 0;
	IsSearching = true;
	while (IsSearching)
	{
		searchcnt++;
		if (searchcnt == 3) break;
		IsSearching = SearchZero(2, 9, &CH2_DAC_Offset, &DAC_Correction[1][0]);	//channel 2 correction for 1er Ranges
	}
	searchcnt = 0;
	IsSearching = true;
	while (IsSearching)
	{
		searchcnt++;
		if (searchcnt == 3) break;
		IsSearching = SearchZero(2, 10, &CH2_DAC_Offset, &DAC_Correction[1][1]);//channel 2 correction for 2er Ranges
	}
	searchcnt = 0;
	IsSearching = true;
	while (IsSearching)
	{
		searchcnt++;
		if (searchcnt == 3) break;
		IsSearching = SearchZero(2, 11, &CH2_DAC_Offset, &DAC_Correction[1][2]);//channel 2 correction for 5er Ranges
	}
	
	if (NumberOfChannels > 2)
	{
		searchcnt = 0;
		IsSearching = true;
		while (IsSearching)
		{
			searchcnt++;
			if (searchcnt == 3) break;
			IsSearching = SearchZero(3, 9, &CH3_DAC_Offset, &DAC_Correction[2][0]);//channel 3 correction for 1er Ranges
		}
		searchcnt = 0;
		IsSearching = true;
		while (IsSearching)
		{
			searchcnt++;
			if (searchcnt == 3) break;
			IsSearching = SearchZero(3, 10, &CH3_DAC_Offset, &DAC_Correction[2][1]);//channel 3 correction for 2er Ranges
		}
		searchcnt = 0;
		IsSearching = true;
		while (IsSearching)
		{
			searchcnt++;
			if (searchcnt == 3) break;
			IsSearching = SearchZero(3, 11, &CH3_DAC_Offset, &DAC_Correction[2][2]);//channel 3 correction for 5er Ranges
		}
		searchcnt = 0;
		IsSearching = true;
		while (IsSearching)
		{
			searchcnt++;
			if (searchcnt == 3) break;
			IsSearching = SearchZero(4, 9, &CH4_DAC_Offset, &DAC_Correction[3][0]);//channel 4 correction for 1er Ranges
		}
		searchcnt = 0;
		IsSearching = true;
		while (IsSearching)
		{
			searchcnt++;
			if (searchcnt == 3) break;
			IsSearching = SearchZero(4, 10, &CH4_DAC_Offset, &DAC_Correction[3][1]);//channel 4 correction for 2er Ranges
		}
		searchcnt = 0;
		IsSearching = true;
		while (IsSearching)
		{
			searchcnt++;
			if (searchcnt == 3) break;
			IsSearching = SearchZero(4, 11, &CH4_DAC_Offset, &DAC_Correction[3][2]);//channel 4 correction for 5er Ranges
		}
	}
		
	//restore settings
	Channel_1_Active = Channel_1_Active_bak;
	Channel_2_Active = Channel_2_Active_bak;
	Channel_3_Active = Channel_3_Active_bak;
	Channel_4_Active = Channel_4_Active_bak;
	
	Selected_Timebase  = Selected_Timebase_bak;
	SIGNALFaktor_idx   = SIGNALFaktor_idx_bak;
	SIGNAL_StartFr_idx = SIGNAL_StartFr_idx_bak;
	timebase_reg       = timebase_reg_bak;
	Display_Timebase   = Display_Timebase_bak;
	Continius          = Continius_bak;
	SingleMode         = SingleMode_bak;
	
	triggering   = triggering_bak;
	ctrl_reg     = ctrl_reg_bak;
	adc_ctrl_reg = adc_ctrl_reg_bak;
	
	CH1_DAC_Offset = CH1_DAC_Offset_bak;
	CH2_DAC_Offset = CH2_DAC_Offset_bak;
	CH3_DAC_Offset = CH3_DAC_Offset_bak;
	CH4_DAC_Offset = CH4_DAC_Offset_bak;
	
	
	Rotary_Steps = 0;
	ON_Zero_Channel_1();
	Rotary_Steps = 0;
	ON_Zero_Channel_2();
	
	
	SetSwitches(1, Selected_Voltage_CH1);
	SetSwitches(2, Selected_Voltage_CH2);
	
	SetDacOffset(1);
	SetDacOffset(2);
	
	//4 channel version
	if (NumberOfChannels > 2)
	{
		Rotary_Steps = 0;
		ON_Zero_Channel_3();
		Rotary_Steps = 0;
		ON_Zero_Channel_4();
	
		SetSwitches(3, Selected_Voltage_CH3);
		SetSwitches(4, Selected_Voltage_CH4);

		SetDacOffset(3);
		SetDacOffset(4);

	}
	
	SetupADC();
	
	SingleMode = 0;
	Continius = 1;
	
	Search_Mode = 0;
	Search_Auto = 0;



// BF ????????????????????? 
   /*
//    if (USB_Data_Trans == 1)
    {
        send_buffer[0] = (unsigned char) 13;
        send_buffer[1] = (unsigned char) (CH1_DAC_Offset & 0xFF);
        send_buffer[2] = (unsigned char) ((CH1_DAC_Offset & 0xFF00) >> 8);
        send_buffer[3] = (unsigned char) (CH1_DAC_Correction_1 & 0xFF);
        send_buffer[4] = (unsigned char) ((CH1_DAC_Correction_1 & 0xFF00) >> 8);
        send_buffer[5] = (unsigned char) (CH1_DAC_Correction_2 & 0xFF);
        send_buffer[6] = (unsigned char) ((CH1_DAC_Correction_2 & 0xFF00) >> 8);
        send_buffer[7] = (unsigned char) (CH1_DAC_Correction_3 & 0xFF);
        send_buffer[8] = (unsigned char) ((CH1_DAC_Correction_3 & 0xFF00) >> 8);
        send_buffer[9] = (unsigned char) (CH2_DAC_Offset & 0xFF);
        send_buffer[10] = (unsigned char) ((CH2_DAC_Offset & 0xFF00) >> 8);
        send_buffer[11] = (unsigned char) (CH2_DAC_Correction_1 & 0xFF);
        send_buffer[12] = (unsigned char) ((CH2_DAC_Correction_1 & 0xFF00) >> 8);
        send_buffer[13] = (unsigned char) (CH2_DAC_Correction_2 & 0xFF);
        send_buffer[14] = (unsigned char) ((CH2_DAC_Correction_2 & 0xFF00) >> 8);
        send_buffer[15] = (unsigned char) (CH2_DAC_Correction_3 & 0xFF);
        send_buffer[16] = (unsigned char) ((CH2_DAC_Correction_3 & 0xFF00) >> 8);
        send_buffer[17] = (unsigned char) (CH3_DAC_Offset & 0xFF);
        send_buffer[18] = (unsigned char) ((CH3_DAC_Offset & 0xFF00) >> 8);
        send_buffer[19] = (unsigned char) (CH3_DAC_Correction_1 & 0xFF);
        send_buffer[20] = (unsigned char) ((CH3_DAC_Correction_1 & 0xFF00) >> 8);
        send_buffer[21] = (unsigned char) (CH3_DAC_Correction_2 & 0xFF);
        send_buffer[22] = (unsigned char) ((CH3_DAC_Correction_2 & 0xFF00) >> 8);
        send_buffer[23] = (unsigned char) (CH3_DAC_Correction_3 & 0xFF);
        send_buffer[24] = (unsigned char) ((CH3_DAC_Correction_3 & 0xFF00) >> 8);
        send_buffer[25] = (unsigned char) (CH4_DAC_Offset & 0xFF);
        send_buffer[26] = (unsigned char) ((CH4_DAC_Offset & 0xFF00) >> 8);
        send_buffer[27] = (unsigned char) (CH4_DAC_Correction_1 & 0xFF);
        send_buffer[28] = (unsigned char) ((CH4_DAC_Correction_1 & 0xFF00) >> 8);
        send_buffer[29] = (unsigned char) (CH4_DAC_Correction_2 & 0xFF);
        send_buffer[30] = (unsigned char) ((CH4_DAC_Correction_2 & 0xFF00) >> 8);
        send_buffer[31] = (unsigned char) (CH4_DAC_Correction_3 & 0xFF);
        send_buffer[32] = (unsigned char) ((CH4_DAC_Correction_3 & 0xFF00) >> 8);
        send_buffer[33] = (unsigned char) NumberOfChannels;

        SendData(send_buffer);
    }
    */
/*
    printf("DAC1 : %i DAC2 : %i DAC3 : %i DAC4 : %i\n", CH1_DAC_Offset, CH2_DAC_Offset, CH3_DAC_Offset, CH4_DAC_Offset);
    printf("CH1_1 :%3d CH1_2 :%3d CH1_3 :%3d CH2_1 :%3d CH2_2 :%3d CH2_3 :%3d \n", CH1_DAC_Correction_1, CH1_DAC_Correction_2, CH1_DAC_Correction_3, CH2_DAC_Correction_1, CH2_DAC_Correction_2, CH2_DAC_Correction_3);
    printf("CH3_1 :%3d CH3_2 :%3d CH3_3 :%3d CH4_1 :%3d CH4_2 :%3d CH4_3 :%3d \n", CH3_DAC_Correction_1, CH3_DAC_Correction_2, CH3_DAC_Correction_3, CH4_DAC_Correction_1, CH4_DAC_Correction_2, CH4_DAC_Correction_3);
*/ 

   	config_changed = true;
	//BF del AMDFlash::Write_Config_Flash();

   
//BF	if (Search_Auto == false)
//BF	{
		Display::DRAWROUNDBUTTON(230, 180, 180, 80, 0, 1);
		Display::TEXTOUTxvbig("Searching zero lines.", 247, 192, 0, UI_Plane2);
		Display::TEXTOUTxvbig("Remove all inputs.", 247, 212, 0, UI_Plane2);
		Display::TEXTOUTxvbig("Can take up to 1 min.", 247, 232, 0, UI_Plane2);
//BF	}

	
	AutoTimerOff = false;
	
	DoEnableADCInterrupt();
	DoEnableUARTInterrupt();
	
	acq_ready->np_pioedgecapture = 0;
	Start_Record();
	
	//reset_watchdog->np_piodata = 0x01;						// Enable WatchDog
	
	return 0;
}
//#####################################################################################################################################

void Hardware::DoEnableKeyInterrupt(void)							// Enable Keyboard service routine
{
	key_int->np_pioedgecapture = 0x00; 							// clear all existing IRQ conditions
	key_int->np_piodirection = 0x00;							// set all bits to input
	key_int->np_piointerruptmask = 0x01;							// enable Keyboard IRQ

	key_reset->np_piodata = 0;								// Reset Keyboard
	nr_delay(1);
	key_reset->np_piodata = 1;
	
	key_int->np_pioedgecapture = 0x00; 							// clear all existing IRQ conditions	

	nr_installuserisr(na_key_interrupt_irq,ISR_KEY,(int)key_int);	// Install ISR for Keyboard
#ifdef _Debug_IRQ_
	if (Debug_Mode) printf("\nKEY interrupt enabled.\n"); 							// print on console
#endif
}
//#####################################################################################################################################

void Hardware::DoDisableKeyInterrupt(void)							// Disable Keyboard I/O service routine
{
	nr_installuserisr(na_key_interrupt_irq,0,0); 					// Install empty routine for Keyboard irq
	key_int->np_piointerruptmask = 0x00;							// disable all IRQs
}
//#####################################################################################################################################

void Hardware::ISR_KEY(int context)									// Keyboard Interrupt subroutine
	{
	int KeyData = key->np_piodata;									// Get interrupt Keyboad data
	
	ADC_Data_Available_cnt = 2; //BF -> ????? what for
	
	//acq_ready->np_piointerruptmask = 0x00;								// disable adc irq
		
	key_reset->np_piodata = 0;									// Reset Keyboard
	nr_delay(1);
	key_reset->np_piodata = 1;
	key_int->np_pioedgecapture = 0;									// clear IRQ conditions	
	
	Keyboard_mem = KeyData;
	Keyboard_Changed = 1;

	UI_request = 1;	
	
	if (SingleMode == 1)
	{
		SingleMode = 0;
	
		LED_ON[14] = 0;
		LED_ON[15] = 0;
	}
	/*
	LED_ON[12] = 0;
	LED_ON[13] = 1;
	Send_LED();  */

	printf("\nKEY interrupt occured.\n"); 							// print on console
}
//#####################################################################################################################################

void Hardware::Keyboard_Interface(void)
{
#define	STX	0x02
#define	ETX	0x03

	char	cmd;					//The command
	int lMenuKey = -1;
	static unsigned char state=0;	//Stores state for remote-command state-machine

//-----------------------------------------------------------------------------------------------------	
//			handle remote inputs received from UART via RS232
//-----------------------------------------------------------------------------------------------------	

char	charTOlMenuKey[]={
//  0x0  0x1  0x2  0x3  0x4  0x5  0x6  0x7  0x8  0x9  0xA  0xB  0xC  0xD  0xE  0xF
	  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, -11, -12, -10,  -1,  -1,  -1,  -1,  -1,
//  0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F
	  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, -11, -12, -10,  -1,  -1,  -1,  -1,  -1,
//  ' '  '!'  '"'  '#'  '$'  '%'  '&'  '''  '('  ')'  '*'  '+'  ','  '-'  '.'  '/'
	  -2,  80,  81,  -1,  83,  84,  85,  -1,  87,  88,  -1,  -1,  69,  71,  70,  86,
//  '0'  '1'  '2'  '3'  '4'  '5'  '6'  '7'  '8'  '9'  ':'  ';'  '<'  '='  '>'  '?'
      39,  30,  31,  32,  33,  34,  35,  36,  37,  38,  68,  67,-127,  89,-127,-127,
//  '@'  'A'  'B'  'C'  'D'  'E'  'F'  'G'  'H'  'I'  'J'  'K'  'L'  'M'  'N'  'O'
     -1,  50,  64,  62,  52,  42,  53,  54,  55,  47,  56,  57,  58,  66,  65,  48,
//  'P'  'Q'  'R'  'S'  'T'  'U'  'V'  'W'  'X'  'Y'  'Z'  '['  '\'  ']'  '^'  '_'
     49,  40,  43,  51,  44,  46,  63,  41,  61,  60,  45,-127,-127,-127,-127,-127,
//  '`'  'a'  'b'  'c'  'd'  'e'  'f'  'g'  'h'  'i'  'j'  'k'  'l'  'm'  'n'  'o'
     -1,   0,  10,  16,   5,  14,   7,  23,  55,   1,   2,   3,   4,  13,  22,  26,
//  'p'  'q'  'r'  's'  't'  'u'  'v'  'w'  'x'  'y'  'z'  '{'  '|'  '}'  '~'  DEL
     15,  19,   9,   8,  12,   6,  21,  20,  27,  17,  29,  -1,  -1,  -1,  -1,  -1};

	UI_request = 0;				//reset UI-request
	if (UART_NewData) {
		UART_NewData = 0;               //reset UART ISR flag
		switch (state) {
			case 0:
				// map external keyboard command to DSO-keyboard
				
				if (UART_RXData!=STX) {
					if (UART_RXData>0) lMenuKey=charTOlMenuKey[UART_RXData];
					
					if(lMenuKey != -1)
					{
						ButtonChanged = 1;

						Buttonhandler(lMenuKey, 0);
						//return;
					}
				} else state=1;
				break;
			case 1:
				switch(UART_RXData) {
					case	1:
					Display::SCREENSHOT();
					state=0;
					break;
					case	2:
					Display::SCREENSHOT_BW();
					state=0;
					break;
					case	3:
					Display::DUMPCSV();
					state=0;
					break;
				}
				break;
			}
		}



//----------------------------------------------------------------------------------------------------	
//			handle keyboard inputs
//----------------------------------------------------------------------------------------------------	

	if (Keyboard_Changed == 0) return;
	Keyboard_Changed = 0;

	ButtonChanged = 1;	
			
	if      ((Keyboard_mem & 0x00080000) == 0x00) {ResetTimer(); Buttonhandler(30, 0);}	// Function Button 1
	else if ((Keyboard_mem & 0x00040000) == 0x00) {ResetTimer(); Buttonhandler(31, 0);}	// Function Button 2
	else if ((Keyboard_mem & 0x00020000) == 0x00) {ResetTimer(); Buttonhandler(32, 0);}	// Function Button 3
	else if ((Keyboard_mem & 0x00010000) == 0x00) {ResetTimer(); Buttonhandler(33, 0);}	// Function Button 4
	else if ((Keyboard_mem & 0x00400000) == 0x00) {ResetTimer(); Buttonhandler(34, 0);}	// Function Button 5
	else if ((Keyboard_mem & 0x00100000) == 0x00) {ResetTimer(); Buttonhandler(35, 0);}	// Function Button 6
	
	else if ((Keyboard_mem & 0x00200000) == 0x00) Buttonhandler( 1, 0);	// Channel 1 Button
	else if ((Keyboard_mem & 0x00800000) == 0x00) Buttonhandler( 2, 0);	// Channel 2 Button
	else if ((Keyboard_mem & 0x01000000) == 0x00) Buttonhandler( 3, 0);	// Channel 3 Button 
	else if ((Keyboard_mem & 0x02000000) == 0x00) Buttonhandler( 4, 0);	// Channel 4 Button
	else if ((Keyboard_mem & 0x04000000) == 0x00) Buttonhandler(26, 0);	// Channel Math Button
	
	else if ((Keyboard_mem & 0x00008000) == 0x00) Buttonhandler(23, 0);	// Auto Scale
	else if ((Keyboard_mem & 0x00000100) == 0x00) Buttonhandler( 8, 0);	// Save/Recall
	else if ((Keyboard_mem & 0x00000800) == 0x00) Buttonhandler(17, 0);	// Quick Print
	else if ((Keyboard_mem & 0x00002000) == 0x00) Buttonhandler( 6, 0);	// Utility
	else if ((Keyboard_mem & 0x00000001) == 0x00) Buttonhandler(15, 0);	// Pulse Width
	
//	else if ((Keyboard_mem & 0x00000020) == 0x00) Buttonhandler(-1, 0);	// Not used
//	else if ((Keyboard_mem & 0x00000002) == 0x00) Buttonhandler(-1, 0);	// Not used
	else if ((Keyboard_mem & 0x00004000) == 0x00) Buttonhandler(16, 0);	// Cursor
	else if ((Keyboard_mem & 0x00000200) == 0x00) Buttonhandler(19, 0);	// Quick Messurement 	// Kurz geschlossen
	else if ((Keyboard_mem & 0x00000400) == 0x00) Buttonhandler( 0, 0);	// Acquire				//
	else if ((Keyboard_mem & 0x00001000) == 0x00) Buttonhandler( 5, 0);	// Display
	else if ((Keyboard_mem & 0x00000010) == 0x00) Buttonhandler(14, 0);	// Edge
	else if ((Keyboard_mem & 0x00000040) == 0x00) Buttonhandler(12, 0);	// Trigger Mode /Coupling
	
	else if ((Keyboard_mem & 0x00000080) == 0x00) Buttonhandler(10, 0);	// Mode Button (Main/Delayed)
	else if ((Keyboard_mem & 0x00000004) == 0x00) Buttonhandler(37, 0);	// Run / Stop Button
	else if ((Keyboard_mem & 0x00000008) == 0x00) Buttonhandler(38, 0);	// Single Button
	


//----------------------------------------------------------------------------------------------------	
//			send menu status via USB to PC
//----------------------------------------------------------------------------------------------------	
	
	if (USB_Data_Trans == 1)
	{
		//reset_watchdog->np_piodata = 0x00;						// Disable WatchDog
		
		for (int cnt = 0; cnt < 32; cnt++)
		{
			send_buffer[0] = 7;
			send_buffer[1] = cnt;
			send_buffer[2] = 1;
			send_buffer[3] = MenuActive;			
			
			send_buffer[4] = (unsigned char) MenuStatus[cnt][0];
			send_buffer[5] = (unsigned char) MenuStatus[cnt][1];
			send_buffer[6] = (unsigned char) MenuStatus[cnt][2];
			send_buffer[7] = (unsigned char) MenuStatus[cnt][3];
			send_buffer[8] = (unsigned char) MenuStatus[cnt][4];
			send_buffer[9] = (unsigned char) MenuStatus[cnt][5];			
		
			SendData(send_buffer);
		}	
		
		//reset_watchdog->np_piodata = 0x01;						// Enable WatchDog
	}
}
//#####################################################################################################################################
//Main button handler
void Hardware::Buttonhandler(int MenuKey, char Pushedlong)			// Button Handler
{
	volatile int pm, xm,ym;
	volatile int res_xm;
	
	volatile long lpm, lxm,lym;
	volatile long lres_xm;
	
	short x, pos = 0;
	int ix, ix2, xa, Ct, result;
	unsigned long buffer_long;
	unsigned long *flash_address = 0;
	
	float buf_float;
	int buf_int;
	
	long timerVal;
	long timerPeriod;


#ifdef _Debug_        	
	if (Debug_Mode) printf("BH %i MA %i\n", MenuKey, MenuActive);
#endif
	//if (ButtonChanged == 0) return;									// If No Button Pressed return.
	//ButtonChanged = 0;

	if (Splash_drawed)
	{
		Display::REMOVE_SPLASH();
		Display::DrawInitialScreen();	//Display::RefreshScreen();
		Splash_drawed = false;
	
		Continius = true;
	
		TimebaseChanged     = 1;
		TimeOffsetChanged   = 1;
		TriggerLevelChanged = 1;
		TriggerModeChanged  = 1;
		TriggerWayChanged   = 1;
		VoltageChangedCh1   = 1;									// Was Voltage changed
		VoltageChangedCh2   = 1;									// Was Voltage changed
		VoltageChangedCh3   = 1;									// Was Voltage changed
		VoltageChangedCh4   = 1;									// Was Voltage changed          		
			
		Display::StatusUpdate();
		
		CursorChanged = 3;
		Cursor_Data_First_Draw = 1;
		Display::DRAWCURSORDATA(0);
	
		Quick_Measure_First_Draw = 1;
		Display::DRAWQMDATA(0); 	
	
		Display::DRAW_ALL_CURSOR();
		if (Continius) Start_Record();
	
		return;
	}
	if (StatusbarChanged) Display::RemoveStatusBtn();
//	if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
	
	MenuAktive = 1;
	
	switch(MenuKey)
	{			
		//--------------------------------------------
		// Acquire Button pressed	
		//--------------------------------------------
		case 0:
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
						
			New_Menu = 0;
			Menu_Changed = 1;
			
			Reset_LED(5);
			
			break;	
		}	
		
		//--------------------------------------------
		// Channel 1 Button pressed
		//--------------------------------------------	
		case 1:
		{	
			if (FFT_Mode != FFT_OFF) break;

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
										
			if (Active_Menu == MenuKey)
			{
                		if ((Channel_2_Active == 0) && (Channel_3_Active == 0) && (Channel_4_Active == 0)) break;

				if (Channel_1_Active == 0) UpdateChannel(1, 1);
				else UpdateChannel(1, 0);
				
				VoltageChangedCh1 = 1;
			}
			else
			{ UpdateChannel(1, 1); }

//BF changed for channel 3 + 4 support in XY-mode
			if (!Channel_1_Active)	//channel 1 switched off
			{	
				//If XY-Mode is active, at least channel 3 + 4 must be active - else switch off XY-Mode
				if ((MenuStatus[MENU_TIMEBASE][2] == 1)  && !(Channel_3_Active && Channel_4_Active))
				{
					MenuStatus[MENU_TIMEBASE][0] = 1;	//Main mode active
					MenuStatus[MENU_TIMEBASE][2] = 0;	//246; BF cha
					XY_Mode = 0;
					
					//Draw main grid into grid plane
					Display::RefreshScreen();	
					GridColor_Val = GridColorArray[GridColorArrayPos];		//Grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//Menu text item
					SetupADC();							//set intensity
				}
				RemovePlane |= 0x01;
				ClearPlanes();
			}



//BF test del            		if ((Channel_1_Active == 1) && (Channel_2_Active == 1)) MenuStatus[MENU_TIMEBASE][2] = 0;//?????
			
			MenuStatusChanged = 1;
			if (Cursor_Enabled) Display::CALCCURSORDATA();
			
			Display::StatusUpdate();
	
			New_Menu = 1;
			Menu_Changed = 1;
			
			if (Channel_1_Active == 1)
			{
				Set_LED(0);
				MenuAktive = 1;
			}
			else
			{
				Reset_LED(0);
				MenuAktive = 0;
			}
			
			break;	
		}
		
		//--------------------------------------------
		// Channel 2 Button pressed	
		//--------------------------------------------
		case 2:
		{	
			if (FFT_Mode != FFT_OFF) break;

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
	
			MenuButtonCheck(-1);
					
			if (Active_Menu == MenuKey)
			{
                		if ((Channel_1_Active == 0) && (Channel_3_Active == 0) && (Channel_4_Active == 0)) break;

				if (Channel_2_Active == 0) UpdateChannel(2, 1);
				else UpdateChannel(2, 0);
				
				VoltageChangedCh2 = 1;
			}
			else UpdateChannel(2, 1);
			
//BF changed for channel 3 + 4 support in XY-mode
			if (Channel_2_Active == 0)	//channel 2 switched off
            		{
				//If XY-Mode is active, at least channel 3 + 4 must be active - else switch off XY-Mode
				if ((MenuStatus[MENU_TIMEBASE][2] == 1) && !(Channel_3_Active && Channel_4_Active))
				{
					MenuStatus[MENU_TIMEBASE][0] = 1;
					MenuStatus[MENU_TIMEBASE][2] = 0;
					XY_Mode = 0;

					//Draw main grid into grid plane
					Display::RefreshScreen();		
					GridColor_Val = GridColorArray[GridColorArrayPos];		//Grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//Menu text item
					SetupADC();							//set intensity
				}

                		RemovePlane |= 0x02;
                		ClearPlanes();
            		}

//BF test del            		if ((Channel_1_Active == 1) && (Channel_2_Active == 1)) MenuStatus[MENU_TIMEBASE][2] = 0;	//??????????
			
			MenuStatusChanged = 2;
			if (Cursor_Enabled) Display::CALCCURSORDATA();
							
			Display::StatusUpdate();				
			
            		New_Menu = 2;
			Menu_Changed = 1;
			
			if (Channel_2_Active == 1)
			{
				Set_LED(1);
				MenuAktive = 1;
			}
			else
			{
				Reset_LED(1);
				MenuAktive = 0;
			}
						
			break;	
		}
		
		//--------------------------------------------
		// Channel 3 Button pressed	
		//--------------------------------------------
		case 3:
		{
			if (NumberOfChannels == 2) return;

			if (FFT_Mode != FFT_OFF) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
	
			MenuButtonCheck(-1);			
			
			if (Active_Menu == MenuKey)
			{
                		if ((Channel_1_Active == 0) && (Channel_2_Active == 0) && (Channel_4_Active == 0)) break;

				if (Channel_3_Active == 0) UpdateChannel(3, 1);
				else UpdateChannel(3, 0);

				VoltageChangedCh3 = 1;
			}
			else
			{ UpdateChannel(3, 1); }
			

//BF changed for channel 3 + 4 support in XY-mode
			if (Channel_3_Active == 0)	//channel 3 switched off
			{
				//If XY-Mode is active, at least channel 1 + 2 must be active - else switch off XY-Mode
				if ((MenuStatus[MENU_TIMEBASE][2] == 1) && !(Channel_1_Active && Channel_2_Active))
				{
					MenuStatus[MENU_TIMEBASE][0] = 1;
					MenuStatus[MENU_TIMEBASE][2] = 0;
					XY_Mode = 0;

					//Draw main grid into grid plane
					Display::RefreshScreen();		
					GridColor_Val = GridColorArray[GridColorArrayPos];		//Grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//Menu text item
					SetupADC();							//set intensity
				}
				RemovePlane |= 0x04;
				ClearPlanes();
			}
			
			MenuStatusChanged = 3;	
			if (Cursor_Enabled) Display::CALCCURSORDATA();
				
			Display::StatusUpdate();
			
           		New_Menu = 3;
			Menu_Changed = 1;
			
			if (Channel_3_Active == 1)
			{
				Set_LED(2);
				MenuAktive = 1;
			}
			else
			{
				Reset_LED(2);
				MenuAktive = 0;
			}
			
			break;	
		}
		
		//--------------------------------------------
		// Channel 4 Button pressed	
		//--------------------------------------------
		case 4:
		{
			if (NumberOfChannels == 2) return;

			if (FFT_Mode != FFT_OFF) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
						
			if (Active_Menu == MenuKey)
			{
                		if ((Channel_1_Active == 0) && (Channel_2_Active == 0) && (Channel_3_Active == 0)) break;

				if (Channel_4_Active == 0) UpdateChannel(4, 1);
				else UpdateChannel(4, 0);
				
				VoltageChangedCh4 = 1;
			}
			else UpdateChannel(4, 1);
			
//BF changed for channel 3 + 4 support in XY-mode
			if (Channel_4_Active == 0)	//channel 4 switched off
			{
				//If XY-Mode is active, at least channel 1 + 2 must be active - else switch off XY-Mode
				if ((MenuStatus[MENU_TIMEBASE][2] == 1) && !(Channel_1_Active && Channel_2_Active))
				{
					MenuStatus[MENU_TIMEBASE][0] = 1;
					MenuStatus[MENU_TIMEBASE][2] = 0;
					XY_Mode = 0;

					//Draw main grid into grid plane
					Display::RefreshScreen();		
					GridColor_Val = GridColorArray[GridColorArrayPos];		//Grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//Menu text item
					SetupADC();							//set intensity
				}
				RemovePlane |= 0x08;
				ClearPlanes();
			}
			
			MenuStatusChanged = 4;
			if (Cursor_Enabled) Display::CALCCURSORDATA();
			
			Display::StatusUpdate();
			
            		New_Menu = 4;
			Menu_Changed = 1;
			
			if (Channel_4_Active == 1)
			{
				Set_LED(3);
				MenuAktive = 1;
			}
			else
			{
				Reset_LED(3);
				MenuAktive = 0;
			}
			
			break;	
		}
		
		//--------------------------------------------
		// Display Button pressed	
		//--------------------------------------------
		case 5:
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
						
			New_Menu     = 5;
			Menu_Changed = 1;
			
			Set_LED(5);
			
			break;	
		}
		
		//--------------------------------------------
		// Utility Button pressed	
		//--------------------------------------------
		case 6:
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
							
			New_Menu = 6;
			Menu_Changed = 1;
			
			Reset_LED(5);
			
			break;	
		}

/* BF function not implemented yet		
		//--------------------------------------------
		// Service Button pressed	// Ist im menu Utility versteckt. Mu� noch gemacht werden
		//--------------------------------------------
		case 7:
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
							
			New_Menu = 7;
			Menu_Changed = 1;
			
			Reset_LED(5);
			
			break;	
		}
*/		
		//--------------------------------------------
		// Save / Recall Button pressed	
		//--------------------------------------------
		case 8:
		{		
			MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu = 8;
			Menu_Changed = 1;
			
			Reset_LED(5);
			
			break;	
		}
		
		//--------------------------------------------
		// Print Menu Button pressed	
		//--------------------------------------------
		case 9:
		{		
			MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu = 9;
			Menu_Changed = 1;
			
			Reset_LED(5);
			
			break;	
		}
		
		//--------------------------------------------------------
		// Main/Delay Button pressed	(Timebase menu)
		//--------------------------------------------------------
		case 10:
		{	
			if (FFT_Mode != FFT_OFF) break;
	
			if (!XY_Mode)
			{
				//if no channel pair is active -> grey out XY-Mode
				if (!(Channel_1_Active && Channel_2_Active) && !(Channel_3_Active && Channel_4_Active))
				{ MenuStatus[MENU_TIMEBASE][2] = 246; }
				else
				{ MenuStatus[MENU_TIMEBASE][2] = 0; }
				
				//MenuItemChanged[2] = 1;
			}
			
			//No delayed mode for timebase 5ns and USTB
			if (Selected_Timebase == 1 || USTB_Mode != USTB_OFF)
			{ MenuStatus[MENU_TIMEBASE][1] = 246; }	
			else
			{
				if(MenuStatus[MENU_TIMEBASE][0] == 1 || MenuStatus[MENU_TIMEBASE][2] == 1)
				MenuStatus[MENU_TIMEBASE][1] = 0;
				else
				MenuStatus[MENU_TIMEBASE][1] = 1;
				
				//MenuItemChanged[1] = 1;
			}

/* BF USTB support is implemented for XY mode now
	
			//No XY mode for  USTB-timebases
			if (USTB_Mode != 0)
			{ MenuStatus[MENU_TIMEBASE][2] = 246; }	//MenuItemChanged[2] = 1;}	
			else
			{
				if(MenuStatus[MENU_TIMEBASE][0] == 1 || MenuStatus[MENU_TIMEBASE][1] == 1)
				MenuStatus[MENU_TIMEBASE][2] = 0;
				else
				MenuStatus[MENU_TIMEBASE][2] = 1;

				//MenuItemChanged[2] = 1;
			}
*/

			//BF -> grey out Roll/Shift mode for normal timebases
			if(USTB_Mode == USTB_OFF)
			{
				MenuStatus[MENU_TIMEBASE][3] = 246;
				MenuStatus[MENU_TIMEBASE][4] = 246;
			}
			//restore roll/shift mode setting in menu
			else if (USTB_Mode == USTB_ROLL)
			{
				MenuStatus[MENU_TIMEBASE][3] = 1;
				MenuStatus[MENU_TIMEBASE][4] = 0;
			}
			else if (USTB_Mode == USTB_SHIFT)
			{
				MenuStatus[MENU_TIMEBASE][3] = 0;
				MenuStatus[MENU_TIMEBASE][4] = 1;
			}
			

			MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu     = 10;
			Menu_Changed = 1;
			MenuStatusChanged = 1;

			Reset_LED(5);
			
			break;	
		}		
		
		//--------------------------------------------
		// Trigger Mode / Coupling Button
		//--------------------------------------------
		case 12: 
		{ 	
			if(FFT_Mode != FFT_OFF) break;

			/* Toggle deactive		
			if (Active_Menu == 12)
			{
				if (MenuStatus[MENU_TRIGGERMODE][0] == 93)
					MenuStatus[MENU_TRIGGERMODE][0] = 94;
				else
					MenuStatus[MENU_TRIGGERMODE][0] = 93;
	
				MenuItemChanged[0] = 1;						
			}
			*/			

			New_Menu = 12;
			Menu_Changed = 1;
			TriggerLevelChanged = 1;
			TriggerModeChanged = 1;
			
			UpdateTrigger(1);
						
			Display::StatusUpdate();			
			
			Set_LED(5);
			
			break;
		}		
		
		//--------------------------------------------	
		// Edge Trigger Menu Button pressed	
		//--------------------------------------------
		case 14:
		{	
			if(FFT_Mode != FFT_OFF) break;
	
			MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
					
			TriggerWay = 1;
			
			New_Menu = 14;
			Menu_Changed = 1;
			
            		TriggerWayChanged = 1;

            		Display::StatusUpdate();				
			
			LED_ON[5] = 1;
			LED_ON[8] = 1;
			LED_ON[10] = 0;

			Send_LED();
			
			UpdateTrigger(2);
			
			break;	
		}
		
		//--------------------------------------------
		// Pulse Width Trigger Menu Button pressed	
		//--------------------------------------------
		case 15:
		{	
			if(FFT_Mode != FFT_OFF) break;
	
			MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }		
		
            		New_Menu = 15;
			Menu_Changed = 1;


			TriggerWay = 2;			
			
            		TriggerWayChanged = 1;

            		Display::StatusUpdate();			
			
			LED_ON[5] = 1;
			LED_ON[8] = 0;
			LED_ON[10] = 1;	
            		Send_LED();	

            		UpdateTrigger(3);	



			break;	
		}		
		
		//--------------------------------------------
		// Cursor Menu Button pressed	
		//--------------------------------------------
		case 16:
		{		
			MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			//CursorChanged = 7; 			
			if ((Cursor_Enabled) && (Active_Menu == MenuKey) && CRS_Delta)
			{
                		Cursor_Enabled_Old = Cursor_Enabled;
                		Cursor_Enabled = false;
				Cursor_Data_First_Draw = 0;
				//Quick_Measure_First_Draw = 0;
				MenuStatusChanged = 1;

				// remove the cursor data
				for (ix = 407 * 20; ix < 430 * 20; ix++)
				{
					*(UI_Plane1 + ix) = 0;		// delete
					//*(Buffer_UI2Plane + ix) = 0;	// delete Text	Guido:del
					*(UI_Plane2 + ix) = 0;		//Guido add: delete button-text
					*(UI_Plane4 + ix) = 0;		// delete
					*(UI_Plane5 + ix) = 0;		// delete
				}
		
				LED_ON[5] = 0;
				LED_ON[6] = 0;
		
				Send_LED();			
						
				New_Menu = 16;
				Menu_Changed = 1;
				MenuAktive = 0;
						
				Display::DRAW_ALL_CURSOR();
			}
			else
			{
				if(CRS_Delta)		//BF new two step logic for delta cursor
				CRS_Delta = 0;
				else
				CRS_Delta = 1;

				LED_ON[5] = 1;
				LED_ON[6] = 1;
							
				if (QM_Enabled)
				{
					QM_Enabled_Old = QM_Enabled;
					QM_Enabled = false;
					Quick_Measure_First_Draw = 0;
					MenuStatusChanged = 1;
			
					// remove the cursor data
					for (ix = 407 * 20; ix < 430 * 20; ix++)
					{
						*(UI_Plane1 + ix) = 0;		// delete
						//*(Buffer_UI2Plane + ix) = 0;	// delete Text	Guido:del
						*(UI_Plane2 + ix) = 0;		//Guido add: delete button-text
						*(UI_Plane4 + ix) = 0;		// delete
						*(UI_Plane5 + ix) = 0;		// delete
					}
				
					LED_ON[7] = 0;
							
					//New_Menu = 19;
					Menu_Changed = 1;
					//MenuAktive = 0;
							
					Display::CALCQMDATA();
				}	
		
				Cursor_Vertical_Active   = 1;
				Cursor_Horizontal_Active = 3;
		
				Send_LED();	
		
				Cursor_Enabled_Old = Cursor_Enabled;
				Cursor_Enabled = true;
				
				Cursor_Data_First_Draw = 1;		
				MenuStatusChanged = 1;
				
				//SelectedChannel = 0;
				
				CursorChanged = 1;
				CursorChanged = 4;
				//CursorChanged = 3;	
				
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();
				
				Display::DRAW_ALL_CURSOR();

						
				New_Menu = 16;
				Menu_Changed = 1;
				MenuAktive = 1;
			}
#ifdef _Debug_Cursor_			
if (Debug_Mode) printf("CE : %d CB : %d CVA : %d CHA : %d \n", Cursor_Enabled, Cursor_Both_Selected, Cursor_Vertical_Active, Cursor_Horizontal_Active);
#endif			
			UpdateMenuTextPlane = true;
            	
			break;	
		}

		//--------------------------------------------
		// Quick Print Button pressed
		//--------------------------------------------
		//BF -> new two step logic
		//BF QP pushed once -> print menu
		//BF QP pushed twice -> direct screenshot

		case 17: 
		{
			if(QP_request > 2) { QP_request = 0; return; }

			QP_request ++;
			if(QP_request == 1)
			nr_delay(500);
			Keyboard_Interface();	// recursive call

			if(QP_request == 1)			// call print menu
			{
				New_Menu = 17;
				Menu_Changed = 1;
				Reset_LED(5);
				QP_request = 0;
				return;
			}
			else
			{
				Display::SCREENSHOT();		// BF 
				QP_request = 0;
				ISR_TIMER3(0);			// close popup
				return;
			}
			
		}
		
		//--------------------------------------------
		// Quick Measure Button pressed
		//--------------------------------------------
		case 19:
		{ 	
           		// if ((MenuStatus[MENU_TIMEBASE][2] == 1) || (XY_Mode == 1)) return;
            		if (XY_Mode == 1) return;
			if (FFT_Mode != FFT_OFF) return;

            		MenuButtonCheck(-1);
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			
			
			if ((QM_Enabled) && (Active_Menu == MenuKey))
			{
				if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }				
			
				QM_Type_Old[0] = QM_Type[0];
				QM_Type_Old[1] = QM_Type[1];
				QM_Type_Old[2] = QM_Type[2];				
						
				QM_Type[0] = 0;
				QM_Type[1] = 0;
				QM_Type[2] = 0;
		
				QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
		
				QM_Changed[0] = 0;
				QM_Changed[1] = 0;
				QM_Changed[2] = 0;
		
				Quick_Measure_First_Draw = 1;
		
				LED_ON[5] = 0;
				LED_ON[7] = 0;
		
				New_Menu = 19;
				Menu_Changed = 1;
		
				QM_Enabled_Old = QM_Enabled;
				QM_Enabled = false;
		
				QM_Vertical_Active = 0;
				QM_Horizontal_Active = 0;
		
				Display::CALCQMDATA();
			}
			else
			{ 	
				LED_ON[5] = 1;
				LED_ON[7] = 1;
					
				QM_Enabled_Old = QM_Enabled;
				QM_Enabled = true;
		
				QM_Vertical_Active = 3;
				QM_Horizontal_Active = 3;
			
				Quick_Measure_First_Draw = 1;		
				MenuStatusChanged = 1;
				
				if (QM_Type[0] == 0)
				{
					if (QM_Type_Old[0] == 0)
					{
						QM_Type_Old[0] = 5;             // Freqency
						QM_Type_Old[1] = 8;            // Peak-Peak
						QM_Type_Old[2] = 0;
					}

					QM_Type[0] = QM_Type_Old[0];
					QM_Type[1] = QM_Type_Old[1];
					QM_Type[2] = QM_Type_Old[2];
			
					QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
					QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
                		}
				
				if (QM_Type[0] > 0) QM_Changed[0] = 1;
				if (QM_Type[1] > 0) QM_Changed[1] = 1;
				if (QM_Type[2] > 0) QM_Changed[2] = 1;
			
				if (Cursor_Enabled)
				{
					Cursor_Enabled_Old = Cursor_Enabled;
					Cursor_Enabled = false;
					Cursor_Data_First_Draw = 0;
		
					//MenuStatusChanged = 1;
		
					// remove the cursor data
					for (ix = 407 * 20; ix < 430 * 20; ix++)
					{
						*(UI_Plane1 + ix) = 0;	// delete
						//*(Buffer_UI2Plane + ix) = 0;	// delete Text	Guido:del
						*(UI_Plane2 + ix) = 0;	//Guido add: delete button-text
						*(UI_Plane4 + ix) = 0;	// delete
						*(UI_Plane5 + ix) = 0;	// delete
					}
		
				LED_ON[6] = 0;
						
				//New_Menu = 16;
				Menu_Changed = 1;
				//MenuAktive = 0;
						
				Display::DRAW_ALL_CURSOR();
				}
                				
				Display::CALCQMDATA();
				
                		New_Menu     = 19;
				Menu_Changed = 1;
				MenuAktive   = 1;
				UpdateMenuTextPlane = true;
			}
			
			Send_LED();	
			
			break;
		}
		
		//--------------------------------------------
		// Autoscale Button pressed
		//--------------------------------------------
		case 23:
		{	
            		if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

            		SingleMode = 0;
            		Continius = 1;
		
			New_Menu = 23;
			Menu_Changed = 1;
			
            		AutoScale();
			
			break;
        	}

		//--------------------------------------------
		// Math Button pressed
		//--------------------------------------------
		case 26:
		{		
            		//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
            		if (XY_Mode == 1) break;

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuButtonCheck(-1);
			
			// If math menu was active and FFT was active bevore - switch back to old settings
			if (Channel_Math_Active && (Active_Menu == MENU_MATH) && (MenuStatus[MENU_MATH][1] == 1))
			{
				FFT_Mode = FFT_OFF;

				FFT_Restore_Channels();

				//restore triggermode
				MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;	
				MenuPopupStatus[9][0] = 2;
				MenuPopupStatus[9][1] = 3;
				TriggerLevelChanged = 1;
				TriggerModeChanged = 1;
				UpdateTrigger(4);

				Zero_Levels_Restore();	
			}
			// math menu was inactive - backup settings and switch to FFT settings 
			else if (!Channel_Math_Active && (MenuStatus[MENU_MATH][1] == 1))
			{
				//set zerolevels to the middle of the grid
				Zero_Levels_Center();
				
				// setting FFT-mode must be done after switching zero levels!
				FFT_Mode = MenuStatus[MENU_FFT][2] - 65;

				FFT_Set_Channel(1);	//set active channel in backup mode

				//Backup triggersetting and force auto mode	
				AUTOMODE_bak = MenuStatus[MENU_TRIGGERMODE][0];
				MenuStatus[MENU_TRIGGERMODE][0] = 93;		//set trigger auto mode
				MenuPopupStatus[9][0] = 2;
				MenuPopupStatus[9][1] = 3;
				TriggerLevelChanged = 1;
				TriggerModeChanged = 1;
				UpdateTrigger(4);

			}
			
			Display::RefreshScreen();	

			// toggle math menu status
			if ((Active_Menu == MenuKey) && (Channel_Math_Active == 1))
			{							
				if (Channel_Math_Active) Channel_Math_Active = 0;
				else Channel_Math_Active = 1;
			}
			else 
			{	Channel_Math_Active = 1;}

            		New_Menu = MENU_MATH;
			Menu_Changed = 1;
			
			if (Channel_Math_Active == 1)
            		{
				Set_LED(4);		// switch on LED
				MenuAktive = 1;		// activate buttons
		
				if (NumberOfChannels == 2)
				{
					//if (MenuPopupStatus[1][2] == 1) MenuPopupStatus[1][2] = 2;	//Cursor Source
					//if (MenuPopupStatus[3][2] == 1) MenuPopupStatus[3][2] = 2;	//Quick Measurement Source
				}
				else
				{
					//if (MenuPopupStatus[1][4] == 1) MenuPopupStatus[1][4] = 2;	//Cursor Source
					//if (MenuPopupStatus[3][4] == 1) MenuPopupStatus[3][4] = 2;	//Quick Measurement Source
				}
            		}
			else if (!Channel_Math_Active || USTB_Mode != USTB_OFF)
            		{
				Reset_LED(4);		// switch off LED
				MenuAktive = 0;		// grey out the buttons
		
				if (NumberOfChannels == 2)
				{
					//if (MenuPopupStatus[1][2] != 1) MenuPopupStatus[1][2] = 1;	//Cursor Source
					//if (MenuPopupStatus[3][2] != 1) MenuPopupStatus[3][2] = 1;	//Quick Measurement Source
				}
				else
				{
					//if (MenuPopupStatus[1][4] != 1) MenuPopupStatus[1][4] = 1;	//Cursor Source
					//if (MenuPopupStatus[3][4] != 1) MenuPopupStatus[3][4] = 1;	//Quick Measurement Source
				}
		
				RemovePlane |= 0x10;
				ClearPlanes();
            		}

			// Wenn FFT dann vorerst Cursor off
			if ((Cursor_Enabled) && (MenuStatus[MENU_MATH][1] == 1))
			{
				Cursor_Enabled_Old = Cursor_Enabled;
				Cursor_Enabled = false;
				Cursor_Data_First_Draw = 0;
		
				//MenuStatusChanged = 1;
		
				// remove the cursor data
				for (ix = 407 * 20; ix < 430 * 20; ix++)
				{
					*(UI_Plane1 + ix) = 0;		// delete
					//*(Buffer_UI2Plane + ix) = 0;	// delete Text	Guido:del
					*(UI_Plane2 + ix) = 0;		// Guido add: delete button-text
					*(UI_Plane4 + ix) = 0;		// delete
					*(UI_Plane5 + ix) = 0;		// delete
				}
		
				LED_ON[6] = 0;
						
				//New_Menu = 16;
				Menu_Changed = 1;
				//MenuAktive = 0;
						
				Display::DRAW_ALL_CURSOR();
			}

			break;	
		}
		
		//--------------------------------------------
		// Function Button 1 pressed
		//--------------------------------------------
		case 30 :
		{
			// Button handler for function button 1 	BF new function
			F1_Btnhandler();
			break;
		}	

		//--------------------------------------------
		// Function Button 2 pressed
		//--------------------------------------------
		case 31 :
		{
			// Button handler for function button 2 	BF new function
			F2_Btnhandler();
			break;
		}

		//--------------------------------------------	
		// Function Button 3
		//--------------------------------------------
		case 32 :
		{
			// Button handler for function button 3 	BF new function
			F3_Btnhandler();
			break;
		}
		
		//--------------------------------------------
		// Function Button 4
		//--------------------------------------------
		case 33 :
		{
			// Button handler for function button 4 	BF new function
			F4_Btnhandler();
			break;
		}
		
		//--------------------------------------------
		// Function Button 5
		//--------------------------------------------
		case 34 :
		{
			// Button handler for function button 5 	BF new function
			F5_Btnhandler();
			break;
		}
		
		//--------------------------------------------
		// Function Button 6
		//--------------------------------------------
		case 35 :
		{		
			// Button handler for function button 6 	BF new function
			F6_Btnhandler();
			break;
		}
		
		//--------------------------------------------
        	// Run / Stop Button pressed
		//--------------------------------------------
		case 37 :
		{	
			if (Continius == 1)
			{
				Continius = 0;
//BF del   				UserIface_active = 0;
				//UI_request = 0
				//Stop_Record();


				// Run/Stop to red
				LED_ON[12] = 0;
				LED_ON[13] = 1;
		
				LED_ON[14] = 0;
				LED_ON[15] = 0;
		
				SIGNAL_StartFr_idx = SIGNALFaktor_idx;
				Selected_Voltage_CH1_Old = Selected_Voltage_CH1;
				Selected_Voltage_CH2_Old = Selected_Voltage_CH2;
				Selected_Voltage_CH3_Old = Selected_Voltage_CH3;
				Selected_Voltage_CH4_Old = Selected_Voltage_CH4;
		
				AUTOMODE_bak = MenuStatus[MENU_TRIGGERMODE][0];
			}
			else
			{
			/* TMW if (Memory_Window_visible)
				{
				Display::DRAWMEMORY(0, 0, 1);
				}*/
		
				Display::DRAW_ALL_CURSOR();
		
				Continius = 1;
				//Signal_Loaded = 0;
				//UserIface_active = 0;

				if (USTB_Mode != USTB_OFF)
				Display::USTB_Clear_Buffer();

		
				SingleMode = 0;
		
				LED_ON[12] = 1;
				LED_ON[13] = 0;
		
				LED_ON[14] = 0;
				LED_ON[15] = 0;
		
		
				MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;
				
				if (MenuStatus[MENU_TRIGGERMODE][0] == 93)
				{
				MenuPopupStatus[9][0] = 3;
				MenuPopupStatus[9][1] = 2;
				}
				else
				{
				MenuPopupStatus[9][0] = 2;
				MenuPopupStatus[9][1] = 3;
				}
				
				
				MenuItemChanged[0] = 1;	
				Menu_Changed = 1;
				TriggerLevelChanged = 1;
				TriggerModeChanged = 1;
		
				UpdateTrigger(55);	
				Display::StatusUpdate();
		
				Start_Record();
			}

			Send_LED();
		
			TriggerModeChanged = 1;
			Display::StatusUpdate();
#ifdef _Debug_
			printf("Run / Stop Button \n");
			if (Continius) printf("Continius Mode enabled\n");
			else printf("Continius Mode disabled\n");
#endif	
		
			break;
        	}

		//--------------------------------------------
        	// Single Button pressed
		//--------------------------------------------
		case 38 :
		{	
            		//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;

			if (SingleMode == 1)
			{
				// Run / Stop out
				LED_ON[12] = 0;
				LED_ON[13] = 0;
		
				// Single orange
				LED_ON[14] = 1;
				LED_ON[15] = 1;
				Send_LED();	
		
//BF del   				UserIface_active = 0;
		
				//Single_Restart = 1;
			}
			else
			{		
				SingleMode = 1;
				Continius = 0;
//BF del   				UserIface_active = 0;
		
				// Run / Stop out
				LED_ON[12] = 0;
				LED_ON[13] = 0;
		
				// Single orange
				LED_ON[14] = 1;
				LED_ON[15] = 1;
		
				AUTOMODE_bak = MenuStatus[MENU_TRIGGERMODE][0];
			}

			MenuStatus[MENU_TRIGGERMODE][0] = 94;
			MenuPopupStatus[9][0] = 2;
			MenuPopupStatus[9][1] = 3;
			MenuItemChanged[0] = 1;						
			Menu_Changed = 1;
			TriggerLevelChanged = 1;
			TriggerModeChanged = 1;

            		//timebase_reg = tb_value[Selected_Timebase];     // Switch to old timebase

			UpdateTrigger(15);			
            		Display::StatusUpdate();

            		Send_LED();	

           		if (adc_started == false) Start_Record();
#ifdef _Debug_
			if (Debug_Mode) printf("Single Button sm : %i  c : %i\n", SingleMode, Continius);
#endif			
			break;
        }
		
		//--------------------------------------------
		// Test Funktion 0 Q
		//--------------------------------------------
		case 40 :
		{	
			printf("****************************************************************************************\r\n");
			printf("Test function 0 (Q)  adjusting ADC zero offsets\r\n");
			
			for (ix = 0; ix < 100; ix+=4)
			{
				printf("S1_%d : %3d %3d %3d %3d\r\n", ix, SIGNAL1[ix], SIGNAL1[ix + 1], SIGNAL1[ix + 2], SIGNAL1[ix + 3]);
				nr_delay(10);
			}

			printf("\r\nSetting ADC offsets\r\n\r\n");

	
TestVar++;
if(TestVar > 25) TestVar = 0;
switch(TestVar)
{	
	case 0: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 1: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 1; break;}
	case 2: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 0; break;}
	case 3: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 1; break;}
	case 4: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 5: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 1; break;}
	case 6: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 0; break;}
	case 7: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 1; break;}
	case 8: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 9: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 1; break;}
	case 10: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 0; break;}
	case 11: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 1; break;}
	case 12: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 13: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 1; break;}
	case 14: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 0; break;}
	
	case 15: {ADC_Offset[test_channel-1][0] = 2;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 16: {ADC_Offset[test_channel-1][0] = 2;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 17: {ADC_Offset[test_channel-1][0] = 2;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 0; break;}
	case 18: {ADC_Offset[test_channel-1][0] = 2;ADC_Offset[test_channel-1][1] = 2;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 0; break;}
	case 19: {ADC_Offset[test_channel-1][0] = 2;ADC_Offset[test_channel-1][1] = 2;ADC_Offset[test_channel-1][2] = 2;ADC_Offset[test_channel-1][3] = 0; break;}
	case 20: {ADC_Offset[test_channel-1][0] = 2;ADC_Offset[test_channel-1][1] = 2;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 0; break;}
	case 21: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 2; break;}
	case 22: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 1;ADC_Offset[test_channel-1][3] = 2; break;}
	case 23: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 1;ADC_Offset[test_channel-1][2] = 2;ADC_Offset[test_channel-1][3] = 2; break;}
	case 24: {ADC_Offset[test_channel-1][0] = 1;ADC_Offset[test_channel-1][1] = 0;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 2; break;}
	case 25: {ADC_Offset[test_channel-1][0] = 0;ADC_Offset[test_channel-1][1] = 2;ADC_Offset[test_channel-1][2] = 0;ADC_Offset[test_channel-1][3] = 2; break;}

//	case 26: { printf("\r\nAuto calibrating ADC voltage offsets\r\n\r\n");Calibrate_ADC(test_channel); break;}

}			
		
			printf("Channel %d ADC offset = %d %d %d %d\n", test_channel, ADC_Offset[test_channel-1][0],
										      ADC_Offset[test_channel-1][1],
										      ADC_Offset[test_channel-1][2],
										      ADC_Offset[test_channel-1][3]);

			printf("****************************************************************************************\n");
/*


			if (ADC_Debug_Mode) ADC_Debug_Mode = false;
			else ADC_Debug_Mode = true;

			if (Debug_Mode)
			{
				if (ADC_Debug_Mode) printf("ADC Debug Mode enabled\n");
				else printf("ADC Debug Mode disabled\n");
			}

            		config_changed = true;
*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 1 W
		//--------------------------------------------
		case 41 :
		{	
			printf("****************************************************************************************\n");
			printf("Test function 2 decrement zeroes (shift + W)\n");
			
			// Guido: make testfunction work for the selected testchannel:
			switch (test_channel)
			{

				case 1:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL1[ix], SIGNAL1[ix + 1], SIGNAL1[ix + 2], SIGNAL1[ix + 3]);
						nr_delay(10);
					}

					printf("CH1 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH1);
					printf("CH1 Zero Level         = %d\n\n", ZeroLevelCH1);
					
					printf("decrementing zero correction\n\n");
					switch(Selected_Voltage_CH1)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH1-1] --; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH1-1] --; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH1-1] --; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH1-3] --; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH1-3] --; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH1-3] --; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH1-6] --; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH1-6] --; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH1-6] --; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH1-9] --; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH1-9] --; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH1-9] --; break;//5 V
					}
			
					printf("CH1 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH1 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH1 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
				case 2:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL2[ix], SIGNAL2[ix + 1], SIGNAL2[ix + 2], SIGNAL2[ix + 3]);
						nr_delay(10);
					}

					printf("CH2 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH2);
					printf("CH2 Zero Level         = %d\n\n", ZeroLevelCH2);
					
					printf("decrementing zero correction\n\n");
					switch(Selected_Voltage_CH2)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH2-1] --; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH2-1] --; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH2-1] --; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH2-3] --; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH2-3] --; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH2-3] --; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH2-6] --; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH2-6] --; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH2-6] --; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH2-9] --; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH2-9] --; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH2-9] --; break;//5 V
					}
			
					printf("CH2 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH2 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH2 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
				case 3:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL3[ix], SIGNAL3[ix + 1], SIGNAL3[ix + 2], SIGNAL3[ix + 3]);
						nr_delay(10);
					}

					printf("CH3 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH3);
					printf("CH3 Zero Level         = %d\n\n", ZeroLevelCH3);
					
					printf("decrementing zero correction\n\n");
					switch(Selected_Voltage_CH3)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH3-1] --; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH3-1] --; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH3-1] --; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH3-3] --; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH3-3] --; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH3-3] --; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH3-6] --; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH3-6] --; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH3-6] --; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH3-9] --; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH3-9] --; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH3-9] --; break;//5 V
					}
			
					printf("CH3 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH3 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH3 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
				case 4:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL4[ix], SIGNAL4[ix + 1], SIGNAL4[ix + 2], SIGNAL4[ix + 3]);
						nr_delay(10);
					}

					printf("CH4 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH4);
					printf("CH4 Zero Level         = %d\n\n", ZeroLevelCH4);
					
					printf("decrementing zero correction\n\n");
					switch(Selected_Voltage_CH4)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH4-1] --; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH4-1] --; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH4-1] --; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH4-3] --; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH4-3] --; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH4-3] --; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH4-6] --; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH4-6] --; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH4-6] --; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH4-9] --; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH4-9] --; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH4-9] --; break;//5 V
					}
			
					printf("CH4 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH4 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH4 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
			}
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 2 E
		//--------------------------------------------
		case 42 :
		{	
			printf("****************************************************************************************\n");
			printf("Test function 3 increment zeroes (shift + E)\n");

			// Guido: make testfunction work for the selected testchannel:
			switch (test_channel)
			{

				case 1:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL1[ix], SIGNAL1[ix + 1], SIGNAL1[ix + 2], SIGNAL1[ix + 3]);
						nr_delay(10);
					}

					printf("CH1 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH1);
					printf("CH1 Zero Level         = %d\n\n", ZeroLevelCH1);
					
					printf("incrementing zero correction\n\n");
					switch(Selected_Voltage_CH1)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH1-1] ++; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH1-1] ++; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH1-1] ++; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH1-3] ++; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH1-3] ++; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH1-3] ++; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH1-6] ++; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH1-6] ++; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH1-6] ++; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH1-9] ++; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH1-9] ++; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH1-9] ++; break;//5 V
					}
			
					printf("CH1 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH1 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH1 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
				case 2:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL2[ix], SIGNAL2[ix + 1], SIGNAL2[ix + 2], SIGNAL2[ix + 3]);
						nr_delay(10);
					}

					printf("CH2 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH2);
					printf("CH2 Zero Level         = %d\n\n", ZeroLevelCH2);
					
					printf("incrementing zero correction\n\n");
					switch(Selected_Voltage_CH2)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH2-1] ++; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH2-1] ++; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH2-1] ++; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH2-3] ++; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH2-3] ++; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH2-3] ++; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH2-6] ++; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH2-6] ++; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH2-6] ++; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH2-9] ++; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH2-9] ++; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH2-9] ++; break;//5 V
					}
			
					printf("CH2 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH2 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH2 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
				case 3:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL3[ix], SIGNAL3[ix + 1], SIGNAL3[ix + 2], SIGNAL3[ix + 3]);
						nr_delay(10);
					}

					printf("CH3 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH3);
					printf("CH3 Zero Level         = %d\n\n", ZeroLevelCH3);
					
					printf("incrementing zero correction\n\n");
					switch(Selected_Voltage_CH3)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH3-1] ++; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH3-1] ++; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH3-1] ++; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH3-3] ++; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH3-3] ++; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH3-3] ++; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH3-6] ++; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH3-6] ++; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH3-6] ++; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH3-9] ++; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH3-9] ++; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH3-9] ++; break;//5 V
					}
			
					printf("CH3 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH3 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH3 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
				case 4:
				{
					for (ix = 0; ix < 100; ix+=4)
					{
						printf("S1_%d : %3d %3d %3d %3d\n", ix, SIGNAL4[ix], SIGNAL4[ix + 1], SIGNAL4[ix + 2], SIGNAL4[ix + 3]);
						nr_delay(10);
					}

					printf("CH4 Virtual Zero Level = %d\n", Virtual_ZeroLevelCH4);
					printf("CH4 Zero Level         = %d\n\n", ZeroLevelCH4);
					
					printf("incrementing zero correction\n\n");
					switch(Selected_Voltage_CH4)
					{
						case 0: DAC_Correction[test_channel-1][Selected_Voltage_CH4-1] ++; break;//  1 mV
						case 1: DAC_Correction[test_channel-1][Selected_Voltage_CH4-1] ++; break;//  2 mV
						case 2: DAC_Correction[test_channel-1][Selected_Voltage_CH4-1] ++; break;//  5 mV
						case 3: DAC_Correction[test_channel-1][Selected_Voltage_CH4-3] ++; break;// 10 mV
						case 4: DAC_Correction[test_channel-1][Selected_Voltage_CH4-3] ++; break;// 20 mV
						case 5: DAC_Correction[test_channel-1][Selected_Voltage_CH4-3] ++; break;// 50 mV
						case 6: DAC_Correction[test_channel-1][Selected_Voltage_CH4-6] ++; break;//100 mV
						case 7: DAC_Correction[test_channel-1][Selected_Voltage_CH4-6] ++; break;//200 mV
						case 8: DAC_Correction[test_channel-1][Selected_Voltage_CH4-6] ++; break;//500 mV
						case 9: DAC_Correction[test_channel-1][Selected_Voltage_CH4-9] ++; break;// 1 V
						case 10: DAC_Correction[test_channel-1][Selected_Voltage_CH4-9] ++; break;//2 V
						case 11: DAC_Correction[test_channel-1][Selected_Voltage_CH4-9] ++; break;//5 V
					}
			
					printf("CH4 DAC correction 1   = %d\n", DAC_Correction[test_channel-1][0]);
					printf("CH4 DAC correction 2   = %d\n", DAC_Correction[test_channel-1][1]);
					printf("CH4 DAC correction 3   = %d\n", DAC_Correction[test_channel-1][2]);
			
					printf("****************************************************************************************\n");
					break;			
				}
			}
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 3 R
		//--------------------------------------------
		case 43 :
		{	
		/*	//Generate Testsignals
			Do_Gen_Signal();
			VSync_Needed = 1;
		
			Display::DrawSignals(1);		
			TransferPlanes();			
			printf("Generate Signal  ready\n");
		*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 4 T
		//--------------------------------------------
		case 44 :
		{		
		/*	//Generate Signal and calculate FFT
			Channel_Math_Active = 1;
			MenuStatus[MENU_MATH][1] = 1;
			MenuStatus[MENU_MATH][2] = 0;
			MenuStatus[MENU_MATH][3] = 0;
			MenuStatus[MENU_MATH][4] = 0;
				
			VSync_Needed = 1;
			
			Do_Gen_Signal();
			Display::FFT_CalcSpectrum();
			
			Display::DrawSignals(1);		
			TransferPlanes();

            		printf("FFT  ready\n");            	
		*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 5 Z
		//--------------------------------------------
		case 45 :
		{	
			//test channel
			test_channel++;
			if (test_channel > NumberOfChannels) test_channel = 1;
			if (test_channel < 1) test_channel = 1;
			printf("\nTest channel = %d\n", test_channel);

			break;
		}		
		
		//--------------------------------------------
		// Test Funktion 6 U
		//--------------------------------------------
		case 46 :
		{		
			printf("****************************************************************************************\r\n");
			printf("Test function 6 - read ADC - (U)\r\n");	

			long buffer_long;

			buffer_long = READADC(1);    // Read correction
			buffer_long = READADC(1);
	
			READADC_ALL2(1, &readout_sigbuf[0], 4096);
			PREPARE_READADC(ADC_Offset[0][0],ADC_Offset[0][1],ADC_Offset[0][2],ADC_Offset[0][3], 4096);
				
			// Get new Signal Data
			if (Selected_Timebase < 7) //Highspeed
			{
				if (MenuStatus[MENU_ACQUIRE][1] == 1)
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 1, 1); }
				else
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 0, 1); }
		
			}
			else	//Lowspeed
			{
				if (MenuStatus[MENU_ACQUIRE][1] == 1)
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 1, 0); }
				else
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 0, 0); }
			}
			
			//print signal values
			for (ix = 0; ix < 160; ix+=4)
			{
				printf("S1_%d : %3d %3d %3d %3d\r\n", ix, SIGNAL1[ix], SIGNAL1[ix + 1], SIGNAL1[ix + 2], SIGNAL1[ix + 3]);
				nr_delay(10);
			}
			printf("\r\n****************************************************************************************\r\n");
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 7 I
		//--------------------------------------------
		case 47 :
		{		
			if (FirEnabledCH1 == 0) FirEnabledCH1 = 1;
			else FirEnabledCH1 = 0;

            		if (FirEnabledCH1) printf("FIR CH 1 enabled\n");

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 8 O
		//--------------------------------------------
		case 48 :
		{		
			printf("****************************************************************************************\r\n");
			printf("Test function 8 - save protected config data - (shift + O)\r\n");	
			
			AMDFlash::Write_Protected_Flash();	
	

			printf("\r\n****************************************************************************************\r\n");
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 9 P
		//--------------------------------------------
		case 49 :
		{
			printf("****************************************************************************************\r\n");
			printf("Test function 9 - read ADC 1 - (P)\r\n");	

			long buffer_long;

			buffer_long = READADC(1);    // Read correction
			buffer_long = READADC(1);
	
			READADC_ALL2(1, &readout_sigbuf[0], 4096);
			PREPARE_READADC(ADC_Offset[0][0],ADC_Offset[0][1],ADC_Offset[0][2],ADC_Offset[0][3], 4096);
				
			// Get new Signal Data
			if (Selected_Timebase < 7) //Highspeed
			{
				if (MenuStatus[MENU_ACQUIRE][1] == 1)
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 1, 1); }
				else
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 0, 1); }
		
			}
			else	//Lowspeed
			{
				if (MenuStatus[MENU_ACQUIRE][1] == 1)
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 1, 0); }
				else
				{ READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 0, 0); }
			}

			//printf("CH1 alpha correction   = %d\r\n", alpha[0]);
			//printf("CH1 beta correction    =  ");floatprintf(beta[0]);printf("\r\n\r\n");

		
			//print signal values
			for (ix = 0; ix < 160; ix+=4)
			{
				printf("S1_%d : %3d %3d %3d %3d\r\n", ix, SIGNAL1[ix], SIGNAL1[ix + 1], SIGNAL1[ix + 2], SIGNAL1[ix + 3]);
				nr_delay(10);
			}
			printf("\r\n****************************************************************************************\r\n");
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 10 A
		//--------------------------------------------
		case 50 :
		{	
            		printf("****************************************************************************************\r\n");
			printf("Test function 10 (A) - display ADC-values - \r\n");
			
			printf("            Channel 1                    Channel 2                  Channel 3                    Channel 4 \r\n");
			for (ix = 0; ix < 160; ix+=4)
			{
				printf("S1_%d : %3d %3d %3d %3d    ", ix, SIGNAL1[ix], SIGNAL1[ix + 1], SIGNAL1[ix + 2], SIGNAL1[ix + 3]);
				printf("S2_%d : %3d %3d %3d %3d    ", ix, SIGNAL2[ix], SIGNAL2[ix + 1], SIGNAL2[ix + 2], SIGNAL2[ix + 3]);
				if (NumberOfChannels == 4)
				{
					printf("S3_%d : %3d %3d %3d %3d    ", ix, SIGNAL3[ix], SIGNAL3[ix + 1], SIGNAL3[ix + 2], SIGNAL3[ix + 3]);
					printf("S4_%d : %3d %3d %3d %3d    ", ix, SIGNAL4[ix], SIGNAL4[ix + 1], SIGNAL4[ix + 2], SIGNAL4[ix + 3]);
				}
				printf("\n");
				//nr_delay(10);
			}
			printf("\n");
			//printf("Connect values         = %d\r\n", Connect_Vals);
			//printf("Draw factor            = %d\r\n\r\n", draw_factor);
		
			//printf("CH1 alpha correction   = %d\r\n", alpha[0]);
			//printf("CH1 beta correction    =  ");floatprintf(beta[0]);printf("\r\n\r\n");
			
			//printf("CH2 alpha correction   = %d\r\n", alpha[1]);
			//printf("CH2 beta correction    =  ");floatprintf(beta[1]);printf("\r\n\r\n");
			//printf("ZeroLevelCH1            = %d\n", ZeroLevelCH1);
			//printf("Virtual_ZeroLevelCH1    = %d\n\n", Virtual_ZeroLevelCH1);

			printf("Voltage range CH1       = %d\n", Selected_Voltage_CH1);
			printf("Voltage range CH2       = %d\n", Selected_Voltage_CH2);

			if (NumberOfChannels == 4)
			{
				printf("Voltage range CH3       = %d\n", Selected_Voltage_CH3);
				printf("Voltage range CH4       = %d\n", Selected_Voltage_CH4);
			}
			//printf("CH1 scale factor        = "); floatprintf(scale_factor[Selected_Voltage_CH1]); printf("\r\n");
			//printf("CH2 scale factor        = "); floatprintf(scale_factor[Selected_Voltage_CH2]); printf("\r\n\r\n");
			printf("\n");
			printf("CH1 ADC1 Voltage offset = %d\r\n",ADC_Offset[0][0]);
			printf("CH1 ADC2 Voltage offset = %d\r\n",ADC_Offset[0][1]);
			printf("CH1 ADC3 Voltage offset = %d\r\n",ADC_Offset[0][2]);
			printf("CH1 ADC4 Voltage offset = %d\r\n\r\n",ADC_Offset[0][3]);
			
			printf("CH2 ADC1 Voltage offset = %d\r\n",ADC_Offset[1][0]);
			printf("CH2 ADC2 Voltage offset = %d\r\n",ADC_Offset[1][1]);
			printf("CH2 ADC3 Voltage offset = %d\r\n",ADC_Offset[1][2]);
			printf("CH2 ADC4 Voltage offset = %d\r\n\r\n",ADC_Offset[1][3]);
			
			if (NumberOfChannels == 4)
			{
				printf("CH3 ADC1 Voltage offset = %d\r\n",ADC_Offset[2][0]);
				printf("CH3 ADC2 Voltage offset = %d\r\n",ADC_Offset[2][1]);
				printf("CH3 ADC3 Voltage offset = %d\r\n",ADC_Offset[2][2]);
				printf("CH3 ADC4 Voltage offset = %d\r\n\r\n",ADC_Offset[2][3]);
				
				printf("CH4 ADC1 Voltage offset = %d\r\n",ADC_Offset[3][0]);
				printf("CH4 ADC2 Voltage offset = %d\r\n",ADC_Offset[3][1]);
				printf("CH4 ADC3 Voltage offset = %d\r\n",ADC_Offset[3][2]);
				printf("CH4 ADC4 Voltage offset = %d\r\n\r\n",ADC_Offset[3][3]);
			}


			printf("CH1 DAC correction 1   = %d\n", DAC_Correction[0][0]);
			printf("CH1 DAC correction 2   = %d\n", DAC_Correction[0][1]);
			printf("CH1 DAC correction 3   = %d\n", DAC_Correction[0][2]);
			
			printf("CH2 DAC correction 1   = %d\n", DAC_Correction[1][0]);
			printf("CH2 DAC correction 2   = %d\n", DAC_Correction[1][1]);
			printf("CH2 DAC correction 3   = %d\n", DAC_Correction[1][2]);
			
			if (NumberOfChannels == 4)
			{
				printf("CH3 DAC correction 1   = %d\n", DAC_Correction[2][0]);
				printf("CH3 DAC correction 2   = %d\n", DAC_Correction[2][1]);
				printf("CH3 DAC correction 3   = %d\n", DAC_Correction[2][2]);
	
				printf("CH4 DAC correction 1   = %d\n", DAC_Correction[3][0]);
				printf("CH4 DAC correction 2   = %d\n", DAC_Correction[3][1]);
				printf("CH4 DAC correction 3   = %d\n", DAC_Correction[3][2]);
			}
			printf("\r\n****************************************************************************************\r\n");
            		break;
		}
		
		//--------------------------------------------
		// Test Funktion 11 S
		//--------------------------------------------
		case 51 :
		{	
			printf("****************************************************************************************\r\n");
			printf("Test function 11 (S) - test switch 1 on/off - \r\n");
			
			//toggle test switch
			if(test_sw1){ test_sw1 = 0; printf("Test switch 1 is off"); }
			else { test_sw1 = 1; printf("Test switch 1 is on"); }

			printf("\r\n****************************************************************************************\r\n");
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 12 D
		//--------------------------------------------
		case 52 :
		{	
			//Test offset
			if (test_channel == 1)
			test_offs_a++;
			else
			test_offs_b++;
			printf("\ntest offset a = %d ; test offset b = %d\n", test_offs_a , test_offs_b);
/*
			if (Debug_Mode) Debug_Mode = false;
			else Debug_Mode = true;
		
			if (Debug_Mode) printf("Debug Mode enabled\n");
			else printf("Debug Mode disabled\n");
		
			config_changed = true;
*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 13 F
		//--------------------------------------------
		case 53 :
		{	
			//Test zero
			if (test_channel == 1)
			test_zero_a+=10;
			else
			test_zero_b+=10;
			//printf("\ntest zero a = %d ; test zero b = %d\n", test_zero_a , test_zero_b);
/*
			//reset_watchdog->np_piodata = 0x00;						// Disable WatchDog
			AMDFlash::Clear_Data_FLASH();
			printf("Flash formated\n");
			//reset_watchdog->np_piodata = 0x01;						// Enable WatchDog
			//Reset_the_Watchdog();
			printf("Reset Hardware\n");
			nr_delay(3000);						
*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 14 G
		//--------------------------------------------
		case 54 :
		{	
			
			//Test div
			if (test_channel == 1)
			test_div_a++;
			else
			test_div_b++;
			printf("\ntest div a = %d ; test div b = %d\n", test_div_a , test_div_b);

/*
			if (Continius)
			{
				Continius = 0;
				SIGNAL_StartFr_idx = SIGNALFaktor_idx;
			}
			else Continius = 1;

			if (Debug_Mode)
			{
				if (Continius) printf("Continius Mode enabled\n");
				else printf("Continius Mode disabled\n");
			}
*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 15 H/h
		//--------------------------------------------
		case 55 :
		{	
	
			printf("\r\n");
			printf("***************************************************************************\r\n");
			printf("* Keyboard Commands : Menus                                               *\r\n");
			printf("***************************************************************************\r\n");
			printf("* Channel 1     : i  *  Mode / Timebase : b * Display      : d * File : f *\r\n");
			printf("* Channel 2     : j  *  Cursor          : c * Trigger Edge : e *          *\r\n");
			printf("* Channel 3     : k  *  Quick Measure   : q * Mode / Coup  : t *          *\r\n");
			printf("* Channel 4     : l  *  Quick Meas Sett : w * Pulse Width  : p *          *\r\n");
			printf("* Channel Math  : o  *  Acquire         : a * Utility      : u *          *\r\n");
			printf("***************************************************************************\r\n");
			printf("* Extended Commands : Help Keys                                           *\r\n");
			printf("***************************************************************************\r\n");
			printf("* This Help Screen  : h / Shift + H * Test switch 2          : Shift + Y  *\r\n");
			printf("* Enable Debug Mode     : Shift + D * Test switch 3          : Shift + X  *\r\n");
			printf("* Clear Data Flash      : Shift + F * Manual DAC Calibration : Shift + W  *\r\n");
			printf("* Test switch 1         : Shift + S * Manual DAC Calibration : Shift + E  *\r\n");
			printf("* Reset Hardware        : Shift + R * Read ADC 1             : Shift + P  *\r\n");
			printf("* Manual ADC calibration: Shift + Q * Interpolate CH1        : Shift + I  *\r\n");
			printf("* Switch test channel   : Shift + Z * Search Mode            : Shift + M  *\r\n");
			printf("* Continius Rec         : Shift + G * Show Trigger Vals      : Shift + J  *\r\n");
			printf("* Smooth CH I           : Shift + K * Smooth CH II           : Shift + L  *\r\n");
			printf("* Enable Extra Trg      : Shift + T * Display ADC values     : Shift + A  *\r\n");
			printf("* Plane Colordemo       : Shift + C *                                     *\r\n");
			//printf("* Show ADC-Data     :     Shift + A * Search Mode            : Shift + M  *\r\n");
			printf("* Show Variables        : ,         * Switch FFT status displ: Shift + V  *\r\n");
			//printf("*                   :     !         *                        : -          *\r\n");
			//printf("* M-Factor CHI + 10 :     Shift + 2 * M-Factor CHI - 10      : Shift + 3  *\r\n");
			printf("* Read ADC              : Shift + U * Display ADC offsets    : =          *\r\n");
			printf("* Write prot. flash     : Shift + O *                                     *\r\n");
			printf("* Solid grid lines      : x         *                                     *\r\n");
			printf("* Dotted grid lines     : z         *                                     *\r\n");
			printf("*-------------------------------------------------------------------------*\r\n");
			printf("* All test switches off: Vertical pixel connection of next Pixel          *\r\n");
			printf("* Test switch 1 on     : Line drawing with Bresenham line algrithm        *\r\n");
			printf("* Test switch 2 on     : Pixel connection Pmin - Pmax no smoothing        *\r\n");
			printf("* Test switch 3 on     : Signal smoothing (only Pmin/Pmax post processing *\r\n");
			printf("*                                                                         *\r\n");
		//            printf("* Timebase manipulation : Press ShiftKey +                                *\r\n");
		//            printf("*      1       2       3     4    5    6    7      8      9         0     *\r\n");
		//            printf("* -0x10000 -0x1000 -0x100 -0x10 -0x1 +0x1 +0x10 +0x100 +0x1000 +0x100000  *\r\n");
			printf("***************************************************************************\r\n");
			printf("\r\n");

			break;
		}		
		
		//--------------------------------------------
		// Test Funktion 16 J
		//--------------------------------------------
		case 56 :
		{		
			//Reset test values
			test_channel = 1;
			test_offs_a  = 0;
			test_offs_b  = 0;
			test_zero_a  = 0;
			test_zero_b  = 0;
			test_div_a   = 1;
			test_div_b   = 1;
			test_rel_a   = 0;
			test_rel_b   = 0;
			printf("\nTest values resetted\n");

			//printf("ctr %x actr %x tb %x pr %x tvr1 %x tvr2 %x trr %x trw %x tp1 %i adc_ch %x \r\n", ctrl_reg, adc_ctrl_reg, timebase_reg, pre_reg, trg_val_CHI_reg, trg_val_CHII_reg, trig_range_reg, trig_width_reg, Trigger_Pos_CH1, adc_change12_reg);

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 17 K
		//--------------------------------------------
		case 57 :
		{		
			if (SmoothEnabledCH1) SmoothEnabledCH1 = 0;
			else SmoothEnabledCH1 = 1;
		
			if (Debug_Mode)
			{
				if (SmoothEnabledCH1) printf("Smooth CH I enabled\n");
				else printf("Smooth CH I disabled\n");
			}

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 18 L
		//--------------------------------------------
		case 58 :
		{		
			if (SmoothEnabledCH2) SmoothEnabledCH2 = 0;
			else SmoothEnabledCH2 = 1;
		
			if (Debug_Mode)
			{
				if (SmoothEnabledCH2) printf("Smooth CH II enabled\n");
				else printf("Smooth CH II disabled\n");
			}

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 19 Ö
		//--------------------------------------------
		case 59 :
		{		
			//Test 
            		if (test_channel == 1)
			test_rel_a++;
			else
			test_rel_b++;
			printf("\ntest rel a = %d ; test rel b = %d\n", test_rel_a , test_rel_b);

			//TestFir();

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 20 Y
		//--------------------------------------------
		case 60 :
		{	
			printf("****************************************************************************************\r\n");
			printf("Test function 20 (Y) - test switch 2 on/off - \r\n");
			
			//toggle test switch
			if(test_sw2){ test_sw2 = 0; printf("Test switch 2 is off\r\n"); }
			else { test_sw2 = 1; printf("Test switch 2 is on\r\n"); }

			printf("****************************************************************************************\r\n");
			
			//Display::ColorDemo5();
			break;
		}	
		
		//--------------------------------------------
		// Test Funktion 21 X
		//--------------------------------------------
		case 61 :
		{
			printf("****************************************************************************************\r\n");
			printf("Test function 21 (X) - test switch 3 on/off - \r\n");
			
			//toggle test switch
			if(test_sw3){ test_sw3 = 0; printf("Test switch 3 is off\r\n"); }
			else { test_sw3 = 1; printf("Test switch 3 is on\r\n"); }

			printf("****************************************************************************************\r\n");
			
			//Display::ColorDemo6();
			break;	
		}	

		//--------------------------------------------
		// Test Funktion 22 C
		//--------------------------------------------
		case 62 :
		{		
			test_values = 1;

			Display::ColorDemo2();
			//Display::SCREENSHOT();
			//while (1 != 0);
			break;
		}	

		//--------------------------------------------
		// Test Funktion 23 V
		//--------------------------------------------
		case 63 :
		{	
			printf("****************************************************************************************\r\n");
			printf("Test function 23 (Shift + V) - switch FFT status variant - \r\n");

			if (FFT_Layout){ FFT_Layout = false; printf("Status layout with yellow background\r\n");}
			else { FFT_Layout = true; printf("Status layout black design\r\n"); }
			printf("****************************************************************************************\r\n");
				
			Display::RefreshScreen();	
            		config_changed = true;		

			break;
		}		
		
		//--------------------------------------------
		// Test Funktion 24 B
		//--------------------------------------------
		case 64 :
		{		
			if (Command_Mode) Command_Mode = false;
			else Command_Mode = true;
		
			if (Debug_Mode)
			{
				if (Command_Mode) printf("Command Mode enabled\n");
				else printf("Command Mode disabled\n");
			}
		
			config_changed = true;
			break;
		} 

		//--------------------------------------------	
		// Test Funktion 25 N
		//--------------------------------------------
		case 65 :
		{	
		    	//Display::GRIDXY(GRID_XY_XOFFS, GRID_YOFFS, Grid_Plane);

			//printf("Add  : %d\n", nm_math_pfx(0x040A, 0x00643040, 0x00C8FFB0));
			//printf("Sub  : %d\n", nm_math_pfx(0x000A, 0x00643040, 0x00C8FFB0));
			//printf("Mult : %d\n", nm_math_pfx(0x0212, 0x00643040, 0x00C8FFB0));

            		// Multiplikation
            /*
			xm = 0x00010101;
			ym = 0x00010101;
			res_xm = nm_math_pfx(0x0201, xm, ym);
	
			printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult1 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
	
			xm = 0x00010502;
			ym = 0x00010502;
			res_xm = nm_math_pfx(0x0201, xm, ym);

			printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult2 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));

			xm = 0x01F47E92;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0203, xm, ym);

			printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult3 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));

            		xm = 0x01F47E6A;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0203, xm, ym);

            		printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult4 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));

            		xm = 0x01F47E90;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0203, xm, ym);

		    	printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult5 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));

           		xm = 0x01F47E65;
		    	ym = 0x01F47E7D;
		   	res_xm = nm_math_pfx(0x0203, xm, ym);

		    	printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult6 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));

            		xm = 0x01F47E99;
		    	ym = 0x01F47E7D;
		    	res_xm = nm_math_pfx(0x0203, xm, ym);

		    	printf("math op1 : %d z1 : %d op2 : %d z2 : %d mult7 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
            */

            		// Addition
			xm = 0x00010101;
			ym = 0x00010101;
			res_xm = nm_math_pfx(0x0401, xm, ym);

            		printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
            		//printf("mth ad1 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
            		printf("mth ad1 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));

			xm = 0x00010502;
			ym = 0x00010502;
			res_xm = nm_math_pfx(0x0401, xm, ym);

            		printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
            		//printf("mth ad2 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
            		printf("mth ad2 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));

			xm = 0x01F47E92;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0403, xm, ym);

			printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
			//printf("mth ad3 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
			printf("mth ad3 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));
		
			xm = 0x01F47E6A;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0403, xm, ym);

			printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
			//printf("mth ad4 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
			printf("mth ad4 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));
		
			xm = 0x01F47E92;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0403, xm, ym);

			printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
			//printf("mth ad5 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
			printf("mth ad5 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));
		
			xm = 0x01F47E6A;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0403, xm, ym);

			printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
			//printf("mth ad6 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
			printf("mth ad6 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));
		
			xm = 0x01F47E99;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0403, xm, ym);

			printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
			//printf("mth ad7 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
			printf("mth ad7 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));
		
			xm = 0x01F47EA0;
			ym = 0x01F47E7D;
			res_xm = nm_math_pfx(0x0403, xm, ym);

			printf("mth op1: %d z1: %d op2: %d z2: %d delA: %d delB: %d\n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, ((xm & 0xFF00) >> 8) - xm & 0xFF, ((ym & 0xFF00) >> 8) - ym & 0xFF);
			//printf("mth ad8 = %x  res: %d  b1: %d b2: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
			printf("mth ad8 = %x  res: %d  tst : %d \n\n", res_xm, (res_xm & 0xFF), ((res_xm & 0x00000F00) >> 8));



            // Subtraction
            /*		
		    xm = 0x00010101;//0x00643040;
		    ym = 0x00010101;//0x00C8FFB0;
		    res_xm = nm_math_pfx(0x0001, xm, ym);

            printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub1 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
		
		    xm = 0x00010502;//0x00643040;
		    ym = 0x00010502;//0x00C8FFB0;
		    res_xm = nm_math_pfx(0x0001, xm, ym);

		    printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub2 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
		
		    xm = 0x01F47E92;
		    ym = 0x01F47E7D;
		    res_xm = nm_math_pfx(0x0003, xm, ym);

		    printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub3 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
		
            xm = 0x01F47E6A;
		    ym = 0x01F47E7D;
		    res_xm = nm_math_pfx(0x0003, xm, ym);

		    printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub4 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
            			
            xm = 0x01F47E90;
		    ym = 0x01F47E7D;
		    res_xm = nm_math_pfx(0x0003, xm, ym);

		    printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub5 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
		
            xm = 0x01F47E65;
		    ym = 0x01F47E7D;
		    res_xm = nm_math_pfx(0x0003, xm, ym);

		    printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub6 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", xm & 0xFF, (xm & 0xFF00) >> 8, ym & 0xFF, (ym & 0xFF00) >> 8, res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));	
		
            xm = 0x01F47E99;
		    ym = 0x01F47E7D;
		    res_xm = nm_math_pfx(0x0003, xm, ym);

		    printf("math op1 : %d z1 : %d op2 : %d z2 : %d sub7 = %d  res : %d  b1 : %d b2 : %d  test : %d \n", res_xm, (res_xm & 0xFF), (res_xm & 0x100) >> 8, (res_xm & 0x200) >> 9, 255 - ((res_xm & 0x3FC00) >> 10));
            */           	
			break;
		}		
		
		//--------------------------------------------
		// Test Funktion 26 M
		//--------------------------------------------
		case 66 :
		{	
            		// Clear All Planes
            		//for (ix = 0; ix < 153600; ix++) Planes[ix] = 0;	

            		Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);		
            /*	
		   	 Search_Step = 0;
            		
            		if (Search_Mode) Search_Mode = false;
            		else Search_Mode = true;

			if (Debug_Mode)
			{
				if (Search_Mode) printf("Search Mode enabled\n");
				else printf("Search Mode disabled\n");
			}

            		printf("SearchResult : %i\n", Hardware::SearchZeros());
            */
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 27 ;
		//--------------------------------------------
		case 67 :
		{	
			for (ix = 0; ix < 3; ix++)
			{
				printf("QMT %2i = %2i QMC = %2i QMCC = %2i QMSC = %2i QMEI = %2i QMEII = %2i\n", ix, QM_Type[ix], QM_Channel[ix], QM_Changed[ix], QM_Second_Channel[ix], QM_CHI_Edge[ix], QM_CHII_Edge[ix]);
			}
  	
			break;
		}		
		
		//--------------------------------------------
		// Test Funktion 28 :
		//--------------------------------------------
		case 68 :
		{	
		
			for (ix = 0; ix < 32; ix++)
			{
				printf("M %2i =", ix);
		
				for (ix2 = 0; ix2 < 6; ix2++)
				{
					printf("  I %i : %3i", ix2, MenuStatus[ix][ix2]);
		
				}
				printf("\n");
			}

			break;
		}

		//--------------------------------------------
		// Test Funktion 69 ,
		//--------------------------------------------
		case 69 :
		{	
			printf("\r\n");
			printf("*****************************************************************************\r\n");
			printf("* Variables                           *                                     *\r\n");
			printf("*****************************************************************************\r\n");
			printf("* Selected_Timebase       : %5d     * Debug Mode               : %5d    *\r\n", Selected_Timebase, Debug_Mode);
			printf("* SIGNALFaktor_idx        : %5d     * ADC Debug Mode           : %5d    *\r\n", SIGNALFaktor_idx, ADC_Debug_Mode);
			printf("* Timebase_Offset_Pos     : %5d     * Command Debug Mode       : %5d    *\r\n", Timebase_Offset_Pos, Command_Mode);
			printf("* SIGNAL_OFFSET           : %5d     * Calc Mode                : %5d    *\r\n", SIGNAL_OFFSET, Calc_Mode);
			printf("*                                   * ExtraTrg Mode            : %5d    *\r\n",  ExtraTrg_Mode);
			printf("* Signal Start            : %5d     * Search Mode              : %5d    *\r\n", SIG_Start_Stop[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]][0], Search_Mode);
			printf("* Signal Stop             : %5d     * Search Auto              : %5d    *\r\n", SIG_Start_Stop[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]][1], Search_Auto);
			printf("* Signal Start Calc       : %5d     * Connect Vals             : %5d    *\r\n", SIG_Start_Stop[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]][0] + (int)((float) Timebase_Offset_Pos * Offset_Faktor_Table[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]]), Connect_Vals);
			printf("* Signal Stop Calc        : %5d     * Continius                : %5d    *\r\n", SIG_Start_Stop[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]][1] + (int)((float) Timebase_Offset_Pos * Offset_Faktor_Table[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]]), Continius);
			printf("* Zoomfaktor              : "); floatprintf(Zoom_Faktor_Table[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]]);
			printf("* SingleMode               : %5d    *\r\n", SingleMode);
			printf("* Offset Faktor          : "); floatprintf(Offset_Faktor_Table[Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx]]);
			printf("* Single Restart           : %5d    *\n", Single_Restart);
			//BF del printf("* Multiplier Enabled      : %5d     * adc started              : %5d    *\r\n", multi_active, adc_started);
			printf("* ADC_Data_Available      : %5d     * VSync Needed             : %5d    *\r\n", ADC_Data_Available, VSync_Needed);
			printf("* Keyboard_Changed        : %5d     * ZFT_float                :", Keyboard_Changed);
			floatprintf(ZFT_float); printf("  *\r\n");
			printf("* Triggering              : %5d     *        :     *\r\n", triggering );
			printf("* SelectedTriggerSource   : %5d     * SelectedTriggerSourceOld : %5d    *\r\n", Selected_Trigger_Source, Selected_Trigger_Source_Old);
			printf("* UserIface_request       : %5d     * OneShotRestart           : %5d    *\r\n", UI_request, OneShotRestart);
			printf("* ctrl_reg                :  %4x     * adc_ctrl_reg             :  %4x    *\r\n", ctrl_reg, adc_ctrl_reg);
			printf("* pre_reg                 :  %4x     * channel_Adr_add          :  %4x    *\r\n", pre_reg, channel_Adr_add);
			printf("* trg_val_CHI_reg         :  %4x     * trg_val_CHII_reg         :  %4x    *\r\n", trg_val_CHI_reg, trg_val_CHII_reg);
			printf("* trg_val_CHIII_reg       :  %4x     * trg_val_CHIV_reg         :  %4x    *\r\n", trg_val_CHIII_reg, trg_val_CHIV_reg);
			printf("* trig_range_reg          :  %4x     * trig_holdoff_reg         :  %4x    *\r\n", trig_range_reg, trig_holdoff_reg);
			printf("* trig_width_reg          :  %4x     *                                     *\r\n", trig_width_reg);
			printf("* adc_change12_reg        :  %8x * adc_change34_reg         : %8x *\r\n", adc_change12_reg, adc_change34_reg);
			printf("* adc_ctr12_reg           :  %8x * adc_ctr34_reg            : %8x *\r\n", adc_ctr12_reg, adc_ctr34_reg);
		
			printf("* Selected_Timebase       : %5d     * SIGNALFaktor_idx         : %5d    *\r\n", Selected_Timebase, SIGNALFaktor_idx);
			printf("* SIGNAL_StartFr_idx      : %5d     * timebase_reg             : %8x    *\r\n", SIGNAL_StartFr_idx, timebase_reg);
			printf("* Display_Timebase        : %5d     * dmode_Selected_Timebase  : %5d    *\r\n", Display_Timebase, dmode_Selected_Timebase);
			printf("* dmode_SIGNALFaktor_idx  : %5d     * dmode_factor             : %5d    *\r\n", dmode_SIGNALFaktor_idx, dmode_factor);
			printf("* dmode_SIGNAL_StartFr_idx: %5d     * Cursor_Delayed_1         : %5d    *\r\n", dmode_SIGNAL_StartFr_idx, Cursor_Delayed_1);
			printf("* Cursor_Delayed_2        : %5d     * Cursor_Delayed_Size      : %5d    *\r\n", Cursor_Delayed_2, Cursor_Delayed_Size);
			printf("* dmode_Window_Offset_Pos : %5d     *                                   *\r\n", dmode_Window_Offset_Pos);
			printf("* SelectedEdgeExtern      : %5d     * TriggerWay               : %5d    *\r\n", SelectedEdgeExtern, TriggerWay );
			printf("* Trigger_Pos_CH1         : %5d     * Trigger_Pos_CH2          : %5d    *\r\n", Trigger_Pos_CH1, Trigger_Pos_CH2);
			printf("* Trigger_Pos_CH3         : %5d     * Trigger_Pos_CH4          : %5d    *\r\n", Trigger_Pos_CH3, Trigger_Pos_CH4);
			printf("* Trigger_Pos_CHE         : %5d     *                          :        *\r\n", Trigger_Pos_CHE);
			printf("* Selected_Voltage_CH1    : %5d     * CH1_DAC_Offset           : %5d    *\r\n", Selected_Voltage_CH1, CH1_DAC_Offset);
			printf("* Selected_Voltage_CH2    : %5d     * CH2_DAC_Offset           : %5d    *\r\n", Selected_Voltage_CH2, CH2_DAC_Offset);
			printf("* Selected_Voltage_CH3    : %5d     * CH3_DAC_Offset           : %5d    *\r\n", Selected_Voltage_CH3, CH3_DAC_Offset);
			printf("* Selected_Voltage_CH4    : %5d     * CH4_DAC_Offset           : %5d    *\r\n", Selected_Voltage_CH4, CH4_DAC_Offset);
			printf("* Virtual_ZeroLevelCH1    : %5d     * ZeroLevelCH1             : %5d    *\r\n", Virtual_ZeroLevelCH1, ZeroLevelCH1);
			printf("* Virtual_ZeroLevelCH2    : %5d     * ZeroLevelCH2             : %5d    *\r\n", Virtual_ZeroLevelCH2, ZeroLevelCH2);
			printf("* Virtual_ZeroLevelCH3    : %5d     * ZeroLevelCH3             : %5d    *\r\n", Virtual_ZeroLevelCH3, ZeroLevelCH3);
			printf("* Virtual_ZeroLevelCH4    : %5d     * ZeroLevelCH4             : %5d    *\r\n", Virtual_ZeroLevelCH4, ZeroLevelCH4);
			//printf("* CH1 Zero Offset (alpha) : %5d     * signal_zoomed1           : %5d    *\r\n", alpha[0], signal_zoomed1);
			//printf("*                         :         * FirStartCH               : %5d    *\r\n",  FirStartCH);
			printf("* CH1_DAC_1               : %5d     * CH1_DAC_2                : %5d    *\r\n", CH1_DAC_1, CH1_DAC_2);
			printf("* CH1_DAC_3               : %5d     * CH1_DAC_4                : %5d    *\r\n", CH1_DAC_3, CH1_DAC_4);
			printf("* SwitchesCH1             : %5d     * SwitchesCH2              : %5d    *\r\n", SwitchesCH1, SwitchesCH2);
			printf("* SwitchesCH3             : %5d     * SwitchesCH4              : %5d    *\r\n", SwitchesCH3, SwitchesCH4);
			printf("* SwitchesTB              : %5d     *                                   *\r\n", SwitchesTB );
			printf("* HoldOff_Value           : %5d     * trig_holdoff_reg         : %8x    *\r\n", HoldOff_Value, trig_holdoff_reg);
			printf("* CVP_Real1               : %5d     *  CVP_Real2               : %5d    *\r\n", Cursor_Vertical_Position_Real1, Cursor_Vertical_Position_Real2);
			printf("* CVP_RealXY1             : %5d     *  CVP_RealXY2             : %5d    *\r\n", Cursor_Vertical_Position_Real_XY_1, Cursor_Vertical_Position_Real_XY_2);
			printf("* CHP_Real1               : %5d     *  CHP_Real1               : %5d    *\r\n", Cursor_Horizontal_Position_Real1, Cursor_Horizontal_Position_Real2);
			printf("* m2k_filter_Mode         :  %4x     *  kill_adc                :  %4x  *\r\n", m2k_filter_Mode, kill_adc);
			printf("* zeros_filter_Mode       :  %4x     *  tc_hw_version           : %8x   *\r\n", zeros_filter_Mode, tc_hw_version);
			printf("* draw_dm_ixstart         : %5d     *            :     *\r\n", draw_dm_ixstart);
			printf("* draw_dm_ixfactor        : %5d     * draw_dm_ixoffset         : %5d    *\r\n", draw_dm_ixfactor, draw_dm_ixoffset);
			printf("* dmode_Window_Offset_Pos : %5d     * dmode_Zoom_Index_Table   : %5d    *\r\n", dmode_Window_Offset_Pos, Zoom_Index_Table[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx]);
			//printf("* dmode_SIG_Start_Stop    : %5d     * dmode_Offset_Faktor_Tab  : %5f *\r\n", SIG_Start_Stop[Zoom_Index_Table[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx]][0], Offset_Faktor_Table[Zoom_Index_Table[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx]]);
		
			//printf("* ZFT_float               : %3.3f     * ZFT_float_dmode          : %3.3f    *\r\n", ZFT_float, ZFT_float_dmode);
			printf("* ZIT_short               : %5d     * ZIT_short_dmode          : %5d    *\r\n", ZIT_short, ZIT_short_dmode);
			printf("* Trig_Pos_Mem            : %5d     * Trig_Pos_Display         : %5d    *\r\n", Trig_Pos_Mem, Trig_Pos_Display);
			printf("*                         :         * MemWinStart              : %5d    *\r\n", MemWinStart);
			printf("* Trig_Pos_Mem_old        : %5d     * Trig_Pos_Display_old     : %5d    *\r\n", Trig_Pos_Mem_old, Trig_Pos_Display_old);
			//printf("* Trig_Pos_Zoom_old       : %3.3f     * MemWinStart_old         : %5d    *\r\n", Trig_Pos_Zoom_old, MemWinStart_old);
			//printf("* OFT_float               : %3.3f     * OFT_float_old            : %3.3f  *\r\n", OFT_float, OFT_float_old);
			
		//            printf("*                                    *                                    *\n");
			printf("*****************************************************************************\r\n");
			printf("\n");

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 70 .
		//--------------------------------------------
		case 70 :
		{		

			printf("\r\n");
			printf("*****************************************************************************\r\n");
			printf("* Interrupts                          *                                     *\r\n");
			printf("*****************************************************************************\r\n");		
			printf("* ADC Interrupt Edge      : %5d     * Keyboard IRQ Edge        : %5d    *\r\n", acq_ready->np_pioedgecapture, key_int->np_pioedgecapture);
			printf("* ADC Interrupt           : %5d     * Keyboard IRQ             : %5d    *\r\n", acq_ready->np_piodata, acq_ready->np_piodata);
		//            printf("*                                    *                                    *\n");
			printf("*****************************************************************************\r\n");
			printf("\r\n");
		
			break;
		}

		//--------------------------------------------
		// Test Funktion 71 -
		//--------------------------------------------
		case 71 :
		{		
			xm = 100;
			ym = 20;
			res_xm = nm_mult(xm, ym);
	
			printf("mult 100 x 20 = %d\n", res_xm);
	
			xm = -100;
			ym = 20;
			res_xm = nm_mult(xm, ym);
	
			printf("mult -100 x 20 = %d\n", res_xm);		
	
			xm = 54;
			ym = 55;
			res_xm = nm_mult(xm, ym);
	
			printf("mult 74 x 55 = %d\n", res_xm);
			
			xm = -74;
			ym = 55;
			res_xm = nm_mult(xm, ym);
	
			printf("mult -54 x 55 = %d\n", res_xm);		

			break;
		}

		//--------------------------------------------
		// Test Funktion 31 !
		//--------------------------------------------
		case 80 :
		{		
/*			if (multi_active)
			{
				multi_active = false;
				SwitchesCH1 &= 0x7FFF;					
				SetSwitches(1, -1);
			}
			else
			{
				multi_active = true;
				SwitchesCH1 |= 0x8000;					
				SetSwitches(1, -1);
			}


            		printf("CH I Multiplier Active : %d\n", multi_active);
*/
			break;
		}
		
		//--------------------------------------------
		// Test Funktion 31 "
		//--------------------------------------------
		case 81 :
		{		
			pre_reg--;
		
			SetupADC();	
			
			printf("pre_reg : %i\n", pre_reg);

			break;
		}

		//--------------------------------------------
		// Test Funktion 32 §
		//--------------------------------------------
		case 82 :
		{		
			pre_reg++;
		
			SetupADC();	
			
			printf("pre_reg : %i\n", pre_reg);

			break;
		}

		//--------------------------------------------
		// Test Funktion 33 $
		//--------------------------------------------
		case 83 :
		{	
		
			pre_reg -= 10;
		
			SetupADC();	
		
			printf("pre_reg : %i\n", pre_reg);

			break;
		}
		
		//--------------------------------------------
		// Test Funktion 34 %
		//--------------------------------------------
		case 84 :
		{		
			pre_reg += 10;
		
			SetupADC();	
		
			printf("pre_reg : %i\n", pre_reg);

			break;
		}

		//--------------------------------------------
		// Test Funktion 35 &
		//--------------------------------------------
		case 85 :
		{		
			if (XY_Mode) XY_Mode = 0;
			else XY_Mode = 1;
				
			printf("Display Mode %d\n", XY_Mode);

			break;
		}

		//--------------------------------------------
		// Test Funktion 36 /
		//--------------------------------------------
		case 86 :
		{		
			if (SIGNALFaktor_idx == 0) pre_reg = pre_reg - 6;
			else if (SIGNALFaktor_idx == 1) pre_reg = pre_reg - 10;
			else if (SIGNALFaktor_idx == 2) pre_reg = pre_reg - 18;
			else if (SIGNALFaktor_idx == 3) pre_reg = pre_reg - 55;
			else if (SIGNALFaktor_idx == 4) pre_reg = pre_reg - 90;
		
			SetupADC();
		
		
			printf("Test Pre Reg manipulation\n");

			break;
		}

		//--------------------------------------------
		// Test Funktion 37 (
		//--------------------------------------------
		case 87 :
		{	
			printf("MenuPopupStatus\n");
			for (ix2 = 0; ix2 < 30; ix2++)
			{
				printf("MPS[%2d] : ", ix2);
				
				for (ix = 0; ix < 21; ix++)
				{
				printf("%2d ", MenuPopupStatus[ix2][ix]);
				}
				printf("\n");
			}

			break;
		}

		//--------------------------------------------
		// Test Funktion 38 )
		//--------------------------------------------
		case 88 :
		{		
			ix = (int) (Pulse11.Read_Value() * 100000000);			
			printf("PV 11 RV : % d Va : %d St : %d Ex : %d\n", ix, Pulse11_Value, Pulse11_Steps, Pulse11_Expo);
			ix = (int) (Pulse12.Read_Value() * 100000000);			
			printf("PV 12 RV : % d Va : %d St : %d Ex : %d\n", ix, Pulse12_Value, Pulse12_Steps, Pulse12_Expo);
		
			ix = (int) (Pulse21.Read_Value() * 100000000);			
			printf("PV 21 RV : % d Va : %d St : %d Ex : %d\n", ix, Pulse21_Value, Pulse21_Steps, Pulse21_Expo);
			ix = (int) (Pulse22.Read_Value() * 100000000);			
			printf("PV 22 RV : % d Va : %d St : %d Ex : %d\n", ix, Pulse22_Value, Pulse22_Steps, Pulse22_Expo);

			break;
		}

		//--------------------------------------------
		// Test Funktion 39 =
		//--------------------------------------------
		case 89 :
		{
			printf("*****************************************************************************\n");
			printf("* CH 1 V  0 : %3d    CH 2 V  0 : %3d    CH 3 V  0 : %3d    CH 4 V  0 : %3d  *\n",ADC_Offset[0][0],ADC_Offset[1][0],ADC_Offset[2][0],ADC_Offset[3][0]);
			printf("* CH 1 V  1 : %3d    CH 2 V  1 : %3d    CH 3 V  1 : %3d    CH 4 V  1 : %3d  *\n",ADC_Offset[0][1],ADC_Offset[1][1],ADC_Offset[2][1],ADC_Offset[3][1]);
			printf("* CH 1 V  2 : %3d    CH 2 V  2 : %3d    CH 3 V  2 : %3d    CH 4 V  2 : %3d  *\n",ADC_Offset[0][2],ADC_Offset[1][2],ADC_Offset[2][2],ADC_Offset[3][2]);
			printf("* CH 1 V  3 : %3d    CH 2 V  3 : %3d    CH 3 V  3 : %3d    CH 4 V  3 : %3d  *\n",ADC_Offset[0][3],ADC_Offset[1][3],ADC_Offset[2][3],ADC_Offset[3][3]);
		
			printf("*****************************************************************************\n");
			printf("\n");

			break;
		}  	
	
		//--------------------------------------------
		// Test Funktion 40 x
		//--------------------------------------------
		case 91 :
		{		
			printf("****************************************************************************************\r\n");
			printf("Test function 40 (x) - free - \r\n");
			
			

			printf("\r\n****************************************************************************************\r\n");
			
			
			break;
		}
		//--------------------------------------------
		// Test Funktion 41 z
		//--------------------------------------------
		case 92 :
		{		
			printf("****************************************************************************************\r\n");
			printf("Test function 41 (z) - free - \r\n");
			
		
			

			printf("\r\n****************************************************************************************\r\n");
			
			
			break;
		}





	}
	if (Splash_drawed == false) UpdateMenuTextPlane = true;
}	

//######################################################################################################################################################
// BF insert
//Function button 1 pressed
void Hardware::F1_Btnhandler(void)					// Button Handler for function button
{ 

	short pos = 0;
	int ix;

#ifdef _Debug_		
       	printf("F1 Btn start\n");
#endif

	if (MenuPopupActive > 0) ResetTimer();
//	if (ZeroPopupChanged > 0) ResetTimer();

	if ((Active_Menu == 1) && (Channel_1_Active == false)) return;
	if ((Active_Menu == 2) && (Channel_2_Active == false)) return;
	if ((Active_Menu == 3) && (Channel_3_Active == false)) return;
	if ((Active_Menu == 4) && (Channel_4_Active == false)) return;
	if ((Active_Menu == 26) && (Channel_Math_Active == false)) return;	// BF del ???

	if ((Active_Menu == 16) && (Cursor_Enabled == false)) return;
	if ((Active_Menu == 19) && (QM_Enabled == false)) return;
	if ((Active_Menu == 20) && (QM_Enabled == false)) return;
	if ((Active_Menu == 21) && (QM_Enabled == false)) return;
	if ((Active_Menu == 22) && (QM_Enabled == false)) return;

	MenuButtonCheck(0);
	
	switch(Active_Menu)
	{
		// Acquire -> Normal
		case 0 :
		{			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_ACQUIRE][0] == 0)
			{
				MenuStatus[MENU_ACQUIRE][1]   = 0;
				MenuItemChanged[1] = 1;
	
				MenuStatus[MENU_ACQUIRE][0]   = 1;
				MenuItemChanged[0] = 1;

				MenuItemChanged[2] = 1;
				MenuStatus[MENU_ACQUIRE][2] = 0;

				New_Menu = 0;
				Menu_Changed = 1;
				
				if (MenuStatus[MENU_ACQUIRE][1] == 1) Set_LED(5);
				else Reset_LED(5);						
			}
				
			break;	
		}				

		// Channel 1 -> Coupling
		case 1 :
		{

			if (Channel_1_Active == 0) break;

			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 13)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 13)
			{
				pos = -1;
				MenuPopupStep(13, &MenuStatus[MENU_CHANNEL1][0], &pos, &pos, 1, 6, 2);
			}

			New_Menu = 1;
			Menu_Changed = 1;

			Display::DRAWMENUPOPUP(13);
			
			SetSwitches(1, -1);

			//S Display::Update_Channel_Data(1);
		
			break;
		}

		// Channel 2 -> Coupling
		case 2 :
		{
			if (Channel_2_Active == 0) break;
			
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 14)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 14)
			{
				pos = -1;
				MenuPopupStep(14, &MenuStatus[MENU_CHANNEL2][0], &pos, &pos, 2, 6, 2);

			}				

			New_Menu = 2;
			Menu_Changed = 1;
								
			Display::DRAWMENUPOPUP(14);
			
			SetSwitches(1, -1);

			//S Display::Update_Channel_Data(2);
	
			break;
		}

		// Channel 3 -> Coupling
		case 3 :
		{
			if (Channel_3_Active == 0) break;
			
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 15)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 15)
			{
				pos = -1;
				MenuPopupStep(15, &MenuStatus[MENU_CHANNEL3][0], &pos, &pos, 3, 6, 2);
			}				

			New_Menu = 3;
			Menu_Changed = 1;
							
			Display::DRAWMENUPOPUP(15);
			
			SetSwitches(1, -1);

			//S Display::Update_Channel_Data(3);

			break;
		}

		// Channel 4 -> Coupling
		case 4 :
		{
			if (Channel_4_Active == 0) break;
			
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 16)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 16)
			{
				pos = -1;
				MenuPopupStep(16, &MenuStatus[MENU_CHANNEL4][0], &pos, &pos, 4, 6, 2);
			}				

			New_Menu = 4;
			Menu_Changed = 1;
				
			Display::DRAWMENUPOPUP(16);
			
			SetSwitches(1, -1);
			
			//S Display::Update_Channel_Data(4);

			break;
		}						

		// Display -> Persist
		case 5 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_DISPLAY][0] == 240) MenuStatus[MENU_DISPLAY][0] = 241;
			else MenuStatus[MENU_DISPLAY][0] = 240;
			
			New_Menu = 5;
			Menu_Changed = 1;
	
			break;
		}		

		// Utility -> Calibrate Zero Lines
		case 6 :
		{
//BF del   			UserIface_active = 0;
			UI_request = 0;
			Search_Step = 0;
			Search_Mode = true;
#ifdef _Debug_
			if (Debug_Mode)
			{
				if (Search_Mode) printf("Search Mode enabled\n");
				else printf("Search Mode disabled\n");
			}

					//printf("SearchResult : %i\n", );
#endif
			
			Hardware::SearchZeros();
			//Hardware::Calibrate_ZeroOffsets();	

			if (Continius)
			{
				LED_ON[12] = 1;
				LED_ON[13] = 0;
				Send_LED();
			}

			break;		
		}					             	
		
		// Timebase -> Main
		case 10 :
		{			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			if (MenuStatus[MENU_TIMEBASE][0] == 0);	// || XY_Mode == 1)	//Check if main mode is not active
			{
				//dmode_Window_Offset_Pos++; // for removing the cursor from delayed mode
				
				config_changed = 1;

				if (USTB_Mode != USTB_OFF)
				Display::USTB_Clear_Buffer();
			
				if (MenuStatus[MENU_TIMEBASE][1] == 1)		//Delayed mode active?
				{			
					MenuItemChanged[1] = 1;
					MenuStatus[MENU_TIMEBASE][1] = 0;	//switch delayed mode off
									
				}
				else if (MenuStatus[MENU_TIMEBASE][2] == 1)	//XY-mode active?	
				{
					MenuItemChanged[2] = 1;
					MenuStatus[MENU_TIMEBASE][2]  = 0;	//switch XY-mode off
					XY_Mode            = 0; 		//switch XY-mode off, needed in On_Zero

					//BF added for restoring zero levels
					ZeroLevelCH1 = ZeroLevelCH1_Main_bak;
					ZeroLevelCH2 = ZeroLevelCH2_Main_bak;
					ZeroLevelCH3 = ZeroLevelCH3_Main_bak;
					ZeroLevelCH4 = ZeroLevelCH4_Main_bak;
					
					Virtual_ZeroLevelCH1 = Virtual_ZeroLevelCH1_Main_bak;
					Virtual_ZeroLevelCH2 = Virtual_ZeroLevelCH2_Main_bak;
					Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3_Main_bak;
					Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4_Main_bak;

					ON_Zero_Channel_1();
					ON_Zero_Channel_2();
					ON_Zero_Channel_3();	
					ON_Zero_Channel_4();	

				}

				//Draw main grid into grid plane
				Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);		
				GridColor_Val = GridColorArray[GridColorArrayPos];		//Grid intensity
				MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//Menu text item
				SetupADC();							//set intensity
				
				MenuStatus[MENU_TIMEBASE][0] = 1;	//Main mode active
			
				TimebaseChanged     = 1;
				TriggerWayChanged   = 1;
				TriggerModeChanged  = 1;
				TriggerLevelChanged = 1;
	
				SetupADC();

				Display::StatusUpdate();
	
				New_Menu     = 10;
				Menu_Changed = 1;
				ClearPlanes();			
			}
			
			Display::DRAW_ALL_CURSOR();	
			
			UpdateTrigger(20);
				
			break;		
		}

		// Trigger Mode -> Mode
		case 12 :
		{
			//BF add -> no normal trigger for USTB
			if (USTB_Mode != USTB_OFF)
			{
				MenuStatus[MENU_TRIGGERMODE][0] = 93;	//set automode
				return;
			}

			Menu_Popup_visible = 1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 9)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 9)
			{
				pos = -1;
				MenuPopupStep(9, &MenuStatus[MENU_TRIGGERMODE][0], &pos, &pos, 12, 93, 2);	

				New_Menu = 12;
				Menu_Changed = 1;
				TriggerLevelChanged = 1;
				TriggerModeChanged = 1;
		
				UpdateTrigger(4);
				
				Display::StatusUpdate();	
			}				
			
			Display::DRAWMENUPOPUP(9);
			break;
		}			

		// Edge -> Rising/Falling
		case 14 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2) MenuStatus[MENU_TRIGGEREDGE][0] = 3;
			else MenuStatus[MENU_TRIGGEREDGE][0] = 2;
			
			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;
			
			UpdateTrigger(5);					
			
			New_Menu = 14;
			Menu_Changed = 1;

			Display::StatusUpdate();
								
			break;	
		
		}		

		// Pulse Width -> Source
		case 15 :
		{		
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 7)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 7)
			{
				pos = -1;
				MenuPopupStep(7, &MenuStatus[MENU_PULSEWIDTH][0], &pos, &pos, 15, 138, 2);
				
				New_Menu = 15;
				Menu_Changed = 1;
				TriggerWayChanged = 1;
			}				
			
			Display::StatusUpdate();		
			Display::DRAWMENUPOPUP(7);
			
			UpdateTrigger(6);
			
			break;			
		}				
	
		// Cursor -> Source
		case 16 :
		{
			if (!Cursor_Enabled) break;

			if(FFT_Mode != FFT_OFF) break;

			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 1)) Display::DRAWMENUPOPDOWN();
			if (MenuPopupActive == 1)
			{
				pos = -1;
				MenuPopupStep(1, &MenuStatus[MENU_CURSOR][0], &pos, &pos, 16, 27, 2);
				MenuItemChanged[3] = 1;
				MenuItemChanged[4] = 1;
				Display::CALCCURSORDATA();
				
				CursorChanged = 3;
				New_Menu = 16;
				Menu_Changed = 1;
			}
			else if (MenuPopupActive == -1)
			{
				New_Menu = 16;
				Menu_Changed = 1;
			}
			Display::DRAWMENUPOPUP(1);

			break;
		}
		
		// Quick Print -> Print to Printer
		case 17 :
		{		
			if (USB_Connected == false) break;
		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			//if (MenuStatus[MENU_QUICKPRINT][2] == 143) MenuStatus[MENU_QUICKPRINT][2] = 144;
			//else MenuStatus[MENU_QUICKPRINT][2] = 143;

			MenuItemChanged[0] = 1;
							
			New_Menu = 17;
			Menu_Changed = 1;


			if ((USB_Data_Requested == false) && (USB_Data_Trans == false))
			{					
				send_buffer[0] = 150;			// Command Quick Print requested
				send_buffer[1] = 0;                     // Printer ??
				send_buffer[2] = 0;
						
				SendData(send_buffer);					
			}
							
			break;					
		}
		
//BF???				// Getting Started
		case 18 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
//P			Display::PopUp(1);
			break;
		}		
		
		// Quick Measurement -> Source
		case 19 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
		
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 3)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 3)
			{
				pos = -1;
				MenuPopupStep(3, &MenuStatus[MENU_QUICKMEASUREMENT][0], &pos, &pos, 19, 27, 2);
				
				New_Menu = 19;
				Menu_Changed = 1;
			}				
		
			Display::DRAWMENUPOPUP(3);
			break;
		}	
		
		// Quick Measurement Delay Settings
		case 20 :
		{	
		//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
		if (QM_Enabled == 0) break;

			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 5)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 5)
			{
				pos = -1;
				MenuPopupStep(5, &MenuStatus[MENU_QMDELAY][0], &pos, &pos, 20, 27, 2);
				
				New_Menu = 20;
				Menu_Changed = 1;
			}				
		
			Display::DRAWMENUPOPUP(5);
			break;
		}	

		// Quick Measurement Phase Settings
		case 21 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if ((MenuPopupActive > -1) && (MenuPopupActive != 24)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 24)
			{
				pos = -1;
				MenuPopupStep(24, &MenuStatus[21][0], &pos, &pos, 21, 27, 2);
				
				New_Menu = 21;
				Menu_Changed = 1;
			}				
		
			Display::DRAWMENUPOPUP(24);
			break;
		}	

		// Quick Measurement Thresholds
		case 22 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;

			if (QM_Enabled == 0) break;
			if ((MenuPopupActive > -1) && (MenuPopupActive != 26)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 26)
			{
				pos = -1;
				MenuPopupStep(26, &MenuStatus[MENU_QMTHRESHOLDS][0], &pos, &pos, 22, 27, 2);
			}

			New_Menu = 22;
			Menu_Changed = 1;

			Display::DRAWMENUPOPUP(26);					
			
			
			break;
		}	

		// AutoScale -> Undo
		case 23 :
		{
			if (FFT_Mode != FFT_OFF) break;		// no autoscale in FFT-mode

			Selected_Timebase = Selected_Timebase_bak;
			SIGNALFaktor_idx = SIGNALFaktor_idx_bak;
			SIGNAL_StartFr_idx = SIGNAL_StartFr_idx_bak;
			timebase_reg = timebase_reg_bak;
			Display_Timebase = Display_Timebase_bak;

			Selected_Voltage_CH1 = Selected_Voltage_CH1_bak;
			Selected_Voltage_CH2 = Selected_Voltage_CH2_bak;
			Selected_Voltage_CH3 = Selected_Voltage_CH3_bak;
			Selected_Voltage_CH4 = Selected_Voltage_CH4_bak;
	
			ZeroLevelCH1 = ZeroLevelCH1_bak;            	
			ZeroLevelCH2 = ZeroLevelCH2_bak;
			ZeroLevelCH3 = ZeroLevelCH3_bak;
			ZeroLevelCH4 = ZeroLevelCH4_bak;
	
			Virtual_ZeroLevelCH1 = Virtual_ZeroLevelCH1_bak;            	
			Virtual_ZeroLevelCH2 = Virtual_ZeroLevelCH2_bak;
			Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3_bak;
			Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4_bak;
	
			Trigger_Pos_CH1 = Trigger_Pos_CH1_bak;
			Trigger_Pos_CH2 = Trigger_Pos_CH2_bak;
			Trigger_Pos_CH3 = Trigger_Pos_CH3_bak;
			Trigger_Pos_CH4 = Trigger_Pos_CH4_bak;
	
			Timebase_Offset_Pos = Timebase_Offset_Pos_bak;
			//Trigger_Offset_Pos = Trigger_Offset_Pos_bak;	//BF del not used
	
			MenuStatus[MENU_CHANNEL1][0] = AC_CH1_bak;
			MenuStatus[MENU_CHANNEL2][0] = AC_CH2_bak;
			MenuStatus[MENU_CHANNEL3][0] = AC_CH3_bak;
			MenuStatus[MENU_CHANNEL4][0] = AC_CH4_bak;
			
			MenuStatus[MENU_CHANNEL1][2] = Invert_CH1_bak;
			MenuStatus[MENU_CHANNEL2][2] = Invert_CH2_bak;
			MenuStatus[MENU_CHANNEL3][2] = Invert_CH3_bak;
			MenuStatus[MENU_CHANNEL4][2] = Invert_CH4_bak;
	
			MenuStatus[MENU_TIMEBASE][0] = MAINMODE_bak;
			//MenuStatus[MENU_TIMEBASE][2] = ROLLMODE_bak;
	
			MenuStatus[MENU_ACQUIRE][0] = Acquire_bak_0;
			MenuStatus[MENU_ACQUIRE][1] = Acquire_bak_1;		
	
			MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;

			if (MenuStatus[MENU_TRIGGERMODE][0] == 93)
			{
				MenuPopupStatus[9][0] = 3;
				MenuPopupStatus[9][1] = 2;
			}
			else
			{
				MenuPopupStatus[9][0] = 2;
				MenuPopupStatus[9][1] = 3;
			}                    	
	
			if (Channel_1_Active)
			{
				SetDacOffset(1);
				SetCHDacOffset(1);
				SetSwitches(1, Selected_Voltage_CH1);
			}
	
			if (Channel_2_Active)
			{
				SetDacOffset(2);
				SetCHDacOffset(2);
				SetSwitches(2, Selected_Voltage_CH2);
			}

			if (NumberOfChannels > 2)
			{
				if (Channel_3_Active)
				{
					SetDacOffset(3);
					SetCHDacOffset(3);
					SetSwitches(3, Selected_Voltage_CH3);
				}
	
				if (Channel_4_Active)
				{
					SetDacOffset(4);
					SetCHDacOffset(4);
					SetSwitches(4, Selected_Voltage_CH4);
				}
			}

			timebase_reg = tb_value[Selected_Timebase];

			UpdateTrigger(31);
	
			if (Cursor_Enabled)
			{
				Display::CALCCURSORDATA();
				Menu_Changed = 1;
				CursorChanged = 4;
			}
	
			if (QM_Enabled)
			{
				Display::CALCQMDATA();
				Menu_Changed = 1;
			}

			VoltageChangedCh1 = 1;
			Display::DRAWSTATUS(1, 0);
			Rotary_Steps = 0;
			ON_Zero_Channel_1();
	
			VoltageChangedCh2 = 1;
			Display::DRAWSTATUS(2, 0);
			Rotary_Steps = 0;
			ON_Zero_Channel_2();

			if (NumberOfChannels > 2)
			{
				VoltageChangedCh3 = 1;
				Display::DRAWSTATUS(3, 0);
				Rotary_Steps = 0;
				ON_Zero_Channel_3();
	
				VoltageChangedCh4 = 1;
				Display::DRAWSTATUS(4, 0);
				Rotary_Steps = 0;
				ON_Zero_Channel_4();
			}
			Display::DRAWSTATUS(6, 0);


			break;
		}

		// Trigger Mode TV
		case 24 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			break;
		}
	
		// Math - Settings sub menu
		case 26 :
		{			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			MenuItemChanged[2] = 1;
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
	
			if (MenuStatus[MENU_MATH][1] == 1)	New_Menu = 27;		//   Settings Menu
			else if (MenuStatus[MENU_MATH][2] == 1) New_Menu = 29;		// Math Settings Menu
			else if (MenuStatus[MENU_MATH][3] == 1) New_Menu = 29;		// Math Settings Menu
			else if (MenuStatus[MENU_MATH][4] == 1) New_Menu = 29;		// Math Settings Menu						

			Menu_Changed = 1;
		
			//printf("We are here and NewMenu is %d Active_Menu is %d MenuAktive is %d\n", New_Menu, Active_Menu, MenuAktive);
			
			break;
		}

		// FFT - Settings - source channel
		case 27 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
/*
			Channel_1_Active = 1;	
			Channel_2_Active = 1;
			if(NumberOfChannels == 4)
			{
				Channel_3_Active = 1;	
				Channel_4_Active = 1;	
			}
			else
			{
				Channel_3_Active = 0;	
				Channel_4_Active = 0;	
			}
*/
			if ((MenuPopupActive > -1) && (MenuPopupActive != 29))
			{ Display::DRAWMENUPOPDOWN(); }
			
			if (MenuPopupActive == 29)
			{
				pos = -1;
				MenuPopupStep(29, &MenuStatus[MENU_FFT][0], &pos, &pos, 27, 138, 2);
			}

			New_Menu = 27;
			Menu_Changed = 1;

			Display::DRAWMENUPOPUP(29);	
			
			FFT_Set_Channel(0);		// set active channel without backup
			
			Display::FFT_DrawStatus();

			//Save new values to flash
			config_changed = true;

			break;
		}					
		
		// Math Settings Scale
		case 29 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			MathToggle = 0;
			
			Menu_Changed = 1;
			MenuItemChanged[0] = 1;
			MenuItemChanged[1] = 1;
			
			break;
		}				
	}					
#ifdef _Debug_			
			if (Debug_Mode) printf("Function Button 1\n");		
#endif
}
// BF insert end
//######################################################################################################################################################
// BF insert
//Function button 2 pressed
void Hardware::F2_Btnhandler(void)					// Button Handler for function button
{

	short pos = 0;
	int ix, result;

#ifdef _Debug_		
       	printf("F2 Btn start\n");
#endif

	if (MenuPopupActive > 0) ResetTimer();
//	if (ZeroPopupChanged > 0) ResetTimer();

	if ((Active_Menu == 1) && (Channel_1_Active == false)) return;
	if ((Active_Menu == 2) && (Channel_2_Active == false)) return;
	if ((Active_Menu == 3) && (Channel_3_Active == false)) return;
	if ((Active_Menu == 4) && (Channel_4_Active == false)) return;
	//if ((Active_Menu == 26) && (Channel_Math_Active == false)) return;

	if ((Active_Menu == 16) && (Cursor_Enabled == false)) return;
	if ((Active_Menu == 19) && (QM_Enabled == false)) return;
	if ((Active_Menu == 20) && (QM_Enabled == false)) return;
	if ((Active_Menu == 21) && (QM_Enabled == false)) return;
	if ((Active_Menu == 22) && (QM_Enabled == false)) return;

	MenuButtonCheck(1);
			
	switch(Active_Menu)
	{
		// Acquire -> Averaging
		case 0 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_ACQUIRE][1] == 0)
			{
				MenuItemChanged[0] = 1;
				MenuStatus[MENU_ACQUIRE][0] = 0;
		
				MenuItemChanged[1] = 1;
				MenuStatus[MENU_ACQUIRE][1] = 1;

				MenuItemChanged[2] = 1;
				MenuStatus[MENU_ACQUIRE][2] = 0;

				New_Menu = 0;
				Menu_Changed = 1;
			}
				
			break;							
		}

		// Channel 1 -> BW Linit
		case 1 :
		{
			if (Channel_1_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL1][1] == 240) MenuStatus[MENU_CHANNEL1][1] = 241;
			else MenuStatus[MENU_CHANNEL1][1] = 240;					
			
			SetSwitches(1, -1);

			New_Menu = 1;
			Menu_Changed = 1;
			
			break;
		}

		// Channel 2 -> BW Linit
		case 2 :
		{
			if (Channel_2_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL2][1] == 240) MenuStatus[MENU_CHANNEL2][1] = 241;
			else MenuStatus[MENU_CHANNEL2][1] = 240;
			
			SetSwitches(2, -1);

			New_Menu = 2;
			Menu_Changed = 1;
			
			break;
		}

		// Channel 3 -> BW Linit
		case 3 :
		{
			if (Channel_3_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL3][1] == 240) MenuStatus[MENU_CHANNEL3][1] = 241;
			else MenuStatus[MENU_CHANNEL3][1] = 240;
			
			SetSwitches(3, -1);

			New_Menu = 3;
			Menu_Changed = 1;
			
			break;
		}

		// Channel 4 -> BW Limit
		case 4 :
		{
			if (Channel_4_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL4][1] == 240) MenuStatus[MENU_CHANNEL4][1] = 241;
			else MenuStatus[MENU_CHANNEL4][1] = 240;
			
			SetSwitches(4, -1);

			New_Menu = 4;
			Menu_Changed = 1;
			
			break;
		}		

		// Display -> Clear Display
		case 5 :
		{		
			if ((Continius == false) || (MenuStatus[MENU_DISPLAY][0] == 241)) ClearPlanes();
			break;
		}
		
		// Utility
		case 6 :
		{		
			Continius = false;
			ClearPlanes();
			Display::DRAW_SPLASH(false);
			break;
		}				
				
		// Service
		case 7 :
		{		
			//
			break;
		}

		// Save / Recall  - > Save
		case 8 :
		{	
			//&~np_timercontrol_cont_mask;	// Stop Timer
			timer_rotary_busy->np_timercontrol = ((timer_rotary_busy->np_timercontrol & 3) + np_timercontrol_stop_mask);
			timer_rotary_busy->np_timerstatus = 0;
	
			Display::DRAWROUNDBUTTON(250, 200, 140, 40, 0, 0);
			Display::TEXTOUTxvbig("Saving Signals", 260, 212, 1, UI_Plane2);
#ifdef _Debug_
			printf("Lets save a signal %d\n", SavePointer);
#endif
			switch(SavePointer)
			{
				case 1 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A01); break;
				case 2 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A02); break;
				case 3 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A03); break;
				case 4 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A04); break;
				case 5 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A05); break;
				case 6 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A06); break;
				case 7 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A07); break;
				case 8 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A08); break;
				case 9 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A09); break;
				case 10 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A10); break;
				case 11 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A11); break;
				case 12 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A12); break;
				case 13 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A13); break;
				case 14 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A14); break;
				case 15 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A15); break;
				case 16 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_A16); break;
	
				case 17 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B01); break;
				case 18 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B02); break;
				case 19 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B03); break;
				case 20 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B04); break;
				case 21 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B05); break;
				case 22 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B06); break;
				case 23 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B07); break;
				case 24 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B08); break;
				case 25 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B09); break;
				case 26 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B10); break;
				case 27 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B11); break;
				case 28 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B12); break;
				case 29 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B13); break;
				case 30 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B14); break;
				case 31 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B15); break;
				case 32 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_B16); break;
	
				case 33 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C01); break;
				case 34 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C02); break;
				case 35 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C03); break;
				case 36 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C04); break;
				case 37 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C05); break;
				case 38 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C06); break;
				case 39 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C07); break;
				case 40 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C08); break;
				case 41 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C09); break;
				case 42 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C10); break;
				case 43 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C11); break;
				case 44 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C12); break;
				case 45 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C13); break;
				case 46 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C14); break;
				case 47 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C15); break;
				case 48 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_C16); break;
	
				case 49 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D01); break;
				case 50 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D02); break;
				case 51 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D03); break;
				case 52 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D04); break;
				case 53 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D05); break;
				case 54 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D06); break;
				case 55 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D07); break;
				case 56 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D08); break;
				case 57 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D09); break;
				case 58 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D10); break;
				case 59 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D11); break;
				case 60 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D12); break;
				case 61 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D13); break;
				case 62 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D14); break;
				case 63 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D15); break;
				case 64 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_D16); break;
	
				case 65 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E01); break;
				case 66 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E02); break;
				case 67 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E03); break;
				case 68 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E04); break;
				case 69 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E05); break;
				case 70 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E06); break;
				case 71 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E07); break;
				case 72 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E08); break;
				case 73 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E09); break;
				case 74 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E10); break;
				case 75 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E11); break;
				case 76 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E12); break;
				case 77 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E13); break;
				case 78 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E14); break;
				case 79 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E15); break;
				case 80 :	result = AMDFlash::copy_signal_to_flash(SAVE_SIGNAL_NR_E16); break;
	
			}

			Display::DRAWROUNDBUTTON(250, 200, 140, 40, 0, 1);
			Display::TEXTOUTxvbig("Saving Signals", 260, 212, 0, UI_Plane2); 
			break;
		}
		
		// Timebase -> Delayed Mode (function button 2)
		case 10 :
		{			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_TIMEBASE][1] == 0)				//Check delayed mode is not active yet
			{
				if (MenuStatus[MENU_TIMEBASE][0] == 1)			//main mode active?
				{
					MenuItemChanged[0] = 1;
					MenuStatus[MENU_TIMEBASE][0]  = 0;		//switch off main mode
				}			
				else if (MenuStatus[MENU_TIMEBASE][2] == 1)		//XY-mode active?
				{
					MenuItemChanged[2] = 1;
					MenuStatus[MENU_TIMEBASE][2]  = 0;		//switch off XY-mode		
					XY_Mode 	   = 0;

					//BF added for restoring zero levels
					ZeroLevelCH1 = ZeroLevelCH1_Main_bak;
					ZeroLevelCH2 = ZeroLevelCH2_Main_bak;
					ZeroLevelCH3 = ZeroLevelCH3_Main_bak;
					ZeroLevelCH4 = ZeroLevelCH4_Main_bak;
					
					Virtual_ZeroLevelCH1 = Virtual_ZeroLevelCH1_Main_bak;
					Virtual_ZeroLevelCH2 = Virtual_ZeroLevelCH2_Main_bak;
					Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3_Main_bak;
					Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4_Main_bak;

					ON_Zero_Channel_1();
					ON_Zero_Channel_2();
					ON_Zero_Channel_3();
					ON_Zero_Channel_4();

				}
//BF menu logic for FFT must be checked
				else if (MenuStatus[MENU_MATH][1] == 1)			//FFT active?
				{
					MenuItemChanged[1] = 1;
					MenuStatus[MENU_MATH][1]  = 0;			//Switch off FFT
					MenuStatus[MENU_MATH][3]  = 1;			//Set 1 - 2 as default
					MenuItemChanged[3] = 1;
					if (Channel_Math_Active)			//Math function active?
					{
						LED_ON[4] = 0;
						Channel_Math_Active = 0;		//switch off math function
					}
	
					Send_LED();

				}
//BF end

				MenuStatus[MENU_TIMEBASE][1] = 1;

				New_Menu     = 10;
				Menu_Changed = 1;
/*
				Display::GRIDDELAYED(GRID_XOFFS, GRID_YOFFS, Grid_Plane);		//draw grid
				GridColor_Val = GridColorArray[GridColorArrayPos_Delayed];		//grid intensity
				MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos_Delayed + 133;		//menu item text
				SetupADC();								//set intensity
*/
				Display::RefreshScreen();

				config_changed = 1;
			}
			
			dmode_SIGNAL_StartFr_idx = SIGNAL_StartFr_idx;
			dmode_Selected_Timebase  = Selected_Timebase;
			dmode_SIGNALFaktor_idx   = SIGNALFaktor_idx;
	
			if (dmode_SIGNALFaktor_idx == 0)
				dmode_Selected_Timebase--;
			else
				dmode_SIGNALFaktor_idx--;
	
			dmode_factor = Timebase_Delayed_Factor_Matrix[Selected_Timebase][SIGNALFaktor_idx] / Timebase_Delayed_Factor_Matrix[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx];
	
			Cursor_Delayed_1 = ((GRID_WIDTH/2) - (int) (((float) GRID_WIDTH / dmode_factor) / 2)) + dmode_Window_Offset_Pos;
			Cursor_Delayed_2 = Cursor_Delayed_1 + (int) ((float) GRID_WIDTH / dmode_factor);
			Cursor_Delayed_Size = Cursor_Delayed_2 - Cursor_Delayed_1;
	
			Recalc_Vars();
			
			Display::DRAW_ALL_CURSOR();
			ClearPlanes();
	
			TimebaseChanged     = 1;
			SIGNALFaktorChanged = 1;
				
			Display::DRAWSTATUS(0, 1);
				
			break;							
		}
	
		// Trigger Mode -> Coupling
		case 12 :
		{
			Menu_Popup_visible = 1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 10)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 10)
			{
				pos = -1;
				MenuPopupStep(10, &MenuStatus[MENU_TRIGGERMODE][1], &pos, &pos, 12, 95, 2);
				
				New_Menu = 12;
				Menu_Changed = 1;
			}				
			
			UpdateTrigger(23);	
			
			Display::DRAWMENUPOPUP(10);
			break;
		}					
	
		// Edge -> source
		case 14 :
		{	
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 28)) { Display::DRAWMENUPOPDOWN(); }

			if ((MenuPopupStatus[28][0] != 3) && (MenuPopupStatus[28][1] != 3) && (MenuPopupStatus[28][2] != 3) 
				&& (MenuPopupStatus[28][3] != 3))
			{
				if (Channel_1_Active) MenuPopupStatus[28][0] = 3;
				else if (Channel_2_Active) MenuPopupStatus[28][1] = 3;
				else if (Channel_3_Active) MenuPopupStatus[28][2] = 3;
				else if (Channel_4_Active) MenuPopupStatus[28][3] = 3;
			}

			if (MenuPopupActive == 28)
			{
				pos = -1;
				MenuPopupStep(28, &MenuStatus[MENU_TRIGGEREDGE][1], &pos, &pos, 28, 138, 2);
				
				New_Menu = 14;
				Menu_Changed = 1;
			}	

			if (MenuPopupStatus[28][0] == 3) MenuStatus[MENU_TRIGGEREDGE][1] = 138;
			else if (MenuPopupStatus[28][1] == 3) MenuStatus[MENU_TRIGGEREDGE][1] = 139;
			else if (MenuPopupStatus[28][2] == 3) MenuStatus[MENU_TRIGGEREDGE][1] = 140;
			else if (MenuPopupStatus[28][3] == 3) MenuStatus[MENU_TRIGGEREDGE][1] = 141;
	
			MenuItemChanged[1] = 1;	
				
			MenuStatus[MENU_TRIGGEREDGE][2] = 0;
			MenuItemChanged[2] = 1;	
		
			MenuStatus[MENU_TRIGGEREDGE][3] = 0;
			MenuItemChanged[3] = 1;

			Display::DRAWMENUPOPUP(28);
			
			Selected_Trigger_Source = MenuStatus[MENU_TRIGGEREDGE][1] - 137;
			SelectedEdgeExtern = 0;               // No External
			
			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;		
				
			Display::StatusUpdate();
				
			UpdateTrigger(7);					
			
			break;
		}				
		
		// Pulse Width -> Pulse
		case 15 :
		{
			break;
			/*
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_PULSEWIDTH][1] == 2) MenuStatus[MENU_PULSEWIDTH][1] = 3;
			else MenuStatus[MENU_PULSEWIDTH][1] = 2;

			New_Menu = 15;
			Menu_Changed = 1;
			TriggerWayChanged = 1;

			Display::StatusUpdate();
			
			UpdateTrigger(8);
			
			break;	
			*/
		}
	
		// Cursor -> X1
		case 16 :
		{	
			if (Cursor_Enabled == 0) break;
			{
				if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
						
				if (Cursor_Vertical_Active_Old == 2) MenuItemChanged[2] = 1;
				else if (Cursor_Vertical_Active_Old == 4) MenuItemChanged[5] = 1;
				else if (Cursor_Horizontal_Active_Old == 1) MenuItemChanged[3] = 1;
				else if (Cursor_Horizontal_Active_Old == 2) MenuItemChanged[4] = 1;
				else if (Cursor_Horizontal_Active_Old == 4) MenuItemChanged[5] = 1;
						
				Cursor_Vertical_Active = 1;
				Cursor_Horizontal_Active = 3;
	
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();
							
				New_Menu = 16;
				Menu_Changed = 1;
	
				Display::DRAW_ALL_CURSOR();
			}
			break;				
		}
		
		// Quick Print -> Save to BMP
		// BF -> new screenshot function from Niklas 
		case 17 :
		{		
			//BF del if (USB_Connected == false) break;
		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			//if (MenuStatus[MENU_QUICKPRINT][2] == 143) MenuStatus[MENU_QUICKPRINT][2] = 144;
			//else MenuStatus[MENU_QUICKPRINT][2] = 143;

			MenuItemChanged[1] = 1;
							
			New_Menu = 17;
			Menu_Changed = 1;

			Display::SCREENSHOT();
/*
			if ((USB_Data_Requested == false) && (USB_Data_Trans == false))
			{					
				send_buffer[0] = 150;			// Command Quick Print requested
				send_buffer[1] = 1;                     // BMP
				send_buffer[2] = 0;
						
				SendData(send_buffer);					
			}
*/							
			break;					
		}				
			
		// Start screen - disabled
		case 18 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			break;
		}	
	
		// Quick Measurement -> Select
		case 19 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;

			Menu_Popup_visible = 1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 4)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 4)
			{
				MenuPopupStep(4, &MenuStatus[MENU_QUICKMEASUREMENT][1], &MenuStatus[MENU_QUICKMEASUREMENT][2], &MenuStatus[MENU_QMDELAY][4], 19, 52, 2);
				MenuStatus[21][4] = MenuStatus[MENU_QMDELAY][4];
	
				if (((MenuStatus[MENU_QUICKMEASUREMENT][1] - 52) == 4) || ((MenuStatus[MENU_QUICKMEASUREMENT][1] - 52) == 13))
				{
				if (MenuStatus[MENU_QUICKMEASUREMENT][4] == 244) MenuItemChanged[4] = 1;
				MenuStatus[MENU_QUICKMEASUREMENT][4] = 242;
				}
				else
				{
				if (MenuStatus[MENU_QUICKMEASUREMENT][4] == 242) MenuItemChanged[4] = 1;
				MenuStatus[MENU_QUICKMEASUREMENT][4] = 244;
				}
	
				MenuItemChanged[1] = 1;
				MenuItemChanged[2] = 1;		
						
				New_Menu = 19;
				Menu_Changed = 1;
			}				
			
			Display::DRAWMENUPOPUP(4);
			
			ResetTimer();
			
			break;
		}	
	
		// Quick Measurement Settings
		case 20 :
		{		
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_QMDELAY][1] == 2) MenuStatus[MENU_QMDELAY][1] = 3;
			else MenuStatus[MENU_QMDELAY][1] = 2;
		
			New_Menu = 20;
			Menu_Changed = 1;

			break;
		}
	
		// Quick Measurement Thresholds
		case 22 :
		{		
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if ((MenuPopupActive > -1) && (MenuPopupActive != 27)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 27)
			{
				pos = -1;
				MenuPopupStep(27, &MenuStatus[MENU_QMTHRESHOLDS][1], &pos, &pos, 22, 49, 2);

				New_Menu = 22;
				Menu_Changed = 1;
			}				
		
			Display::DRAWMENUPOPUP(27);
			break;
		}


		// Autoscale -> Slow TB
		case 23 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			if (MenuStatus[MENU_AUTOSCALE][1] == 240) MenuStatus[MENU_AUTOSCALE][1] = 241;
			else MenuStatus[MENU_AUTOSCALE][1] = 240;
			
			MenuItemChanged[1] = 1;
			New_Menu = 23;
			Menu_Changed = 1;
			
			break;
		}
	
	
		// Trigger Mode TV
		case 24 :
		{
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_TRIGGERTV][1] == 2) MenuStatus[MENU_TRIGGERTV][1] = 3;
			else MenuStatus[MENU_TRIGGERTV][1] = 2;		
		
			New_Menu = 24;
			Menu_Changed = 1;

			break;	
		}	
	
		// Math - FFT
		case 26 :
		{		

 			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			if (MenuStatus[MENU_MATH][1] == 0)	// execute only when FFT was not active yet
			{
				if (MenuStatus[MENU_MATH][2] == 1)
				{
					MenuItemChanged[2] = 1;
					MenuStatus[MENU_MATH][2] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][3] == 1)
				{
					MenuItemChanged[3] = 1;
					MenuStatus[MENU_MATH][3] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][4] == 1)
				{
					MenuItemChanged[4] = 1;
					MenuStatus[MENU_MATH][4] = 0;
				}

				MenuStatus[MENU_MATH][1] = 1;		//FFT active

				//Backup triggersetting and force auto mode	
				AUTOMODE_bak = MenuStatus[MENU_TRIGGERMODE][0];
				MenuStatus[MENU_TRIGGERMODE][0] = 93;		//set trigger auto mode
				MenuPopupStatus[9][0] = 2;
				MenuPopupStatus[9][1] = 3;
				TriggerLevelChanged = 1;
				TriggerModeChanged = 1;
				UpdateTrigger(4);

				//set zerolevels to the middle of the grid
				Zero_Levels_Center();

				// setting FFT-mode must be done after switching zero levels!
				FFT_Mode = MenuStatus[MENU_FFT][2] - 65;

				//Draw grid for FFT
				//Display::GRIDFFT(GRID_XOFFS_FFT, GRID_YOFFS_FFT, Grid_Plane);	//draw grid
				GridColor_Val = GridColorArray[GridColorArrayPos];		//grid intensity
				MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//menu text item
				SetupADC();							//set intensity

				FFT_Set_Channel(1);		// set active channel with backup

				Display::RefreshScreen();	

				Menu_Changed = 1;
				//MenuAktive = 1;				// activate buttons
				//MenuStatusChanged = 1;
			}
;
			New_Menu = MENU_MATH;

			Display::DRAW_ALL_CURSOR();

			//Save new values to flash
			//config_changed = true;

			break;				
		}

		// FFT - Settings - Window
		case 27 :
		{
			if ((MenuPopupActive > -1) && (MenuPopupActive != 30)) { Display::DRAWMENUPOPDOWN(); }

			if (MenuPopupActive == 30)
			{
				pos = -1;
				MenuPopupStep(30, &MenuStatus[MENU_FFT][1], &pos, &pos, 27, 193, 2);
				New_Menu = MENU_FFT;
				Menu_Changed = 1; 	
			}
			
			Display::DRAWMENUPOPUP(30);	
			
			// set FFT-Window     193 = Rect => -1
			FFT_Windex = MenuStatus[MENU_FFT][1] - 192;
			
			// create window
			for(int i=0,r=0 ;i < FFT_Length; i++)
			{
				win_tab[i] = FFT_Window[FFT_Windex][r];
			
				if (FFT_Length == FFT_512)
				r+=2;
				else
				r++;	
			}
			Display::FFT_DrawStatus();

			//Save new values to flash
			config_changed = true;

			break;
		}
		
/* BF del not needed in new FFT 
		
		// FFT - Settings - Scale	
		case 28 :	// BF Changed case 27 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
		
			FFTToggle = 0;
		
			MenuItemChanged[1] = 1;
			MenuItemChanged[2] = 1;	

			New_Menu = 27;
			Menu_Changed = 1;	

			break;
		}				
*/
/* BF not needed in new FFT 		
		// Math Settings Offset
		case 29 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			MathToggle = 1;
			
			Menu_Changed = 1;
			MenuItemChanged[0] = 1;
			MenuItemChanged[1] = 1;
			
			break;
		}	
*/			
	}					
#ifdef _Debug_			
	if (Debug_Mode) printf("Function Button 2\n");		
#endif

}
// BF insert end
//######################################################################################################################################################
// BF insert
//Function button 3 pressed
void Hardware::F3_Btnhandler(void)					// Button Handler for function button
{
	short pos = 0;
	int ix;

#ifdef _Debug_		
       	printf("F3 Btn start\n");
#endif	

	if (MenuPopupActive > 0) ResetTimer();
//	if (ZeroPopupChanged > 0) ResetTimer();

	if ((Active_Menu == 1) && (Channel_1_Active == false)) return;
	if ((Active_Menu == 2) && (Channel_2_Active == false)) return;
	if ((Active_Menu == 3) && (Channel_3_Active == false)) return;
	if ((Active_Menu == 4) && (Channel_4_Active == false)) return;
	//if ((Active_Menu == 26) && (Channel_Math_Active == false)) return;

	if ((Active_Menu == 16) && (Cursor_Enabled == false)) return;
	if ((Active_Menu == 19) && (QM_Enabled == false)) return;
	if ((Active_Menu == 20) && (QM_Enabled == false)) return;
	if ((Active_Menu == 21) && (QM_Enabled == false)) return;
	if ((Active_Menu == 22) && (QM_Enabled == false)) return;

	
	MenuButtonCheck(2);

	switch(Active_Menu)
	{	
		// Acquire -> Noise suppression
		case 0 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_ACQUIRE][2] == 0)
			{
				MenuItemChanged[0] = 1;
				MenuStatus[MENU_ACQUIRE][0] = 0;
		
				MenuItemChanged[1] = 1;
				MenuStatus[MENU_ACQUIRE][1] = 0;

				MenuItemChanged[2] = 1;
				MenuStatus[MENU_ACQUIRE][2] = 1;

				New_Menu = 0;
				Menu_Changed = 1;
			}
				
			break;							
		}


		// Channel 1 -> Invert
		case 1 :
		{
			if (Channel_1_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL1][2] == 240) MenuStatus[MENU_CHANNEL1][2] = 241;
			else MenuStatus[MENU_CHANNEL1][2] = 240;

			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;
			
			UpdateTrigger(55);						
			Display::StatusUpdate();

			New_Menu = 1;
			Menu_Changed = 1;
			
			break;
		}
	
		// Channel 2 -> Invert
		case 2 :
		{
			if (Channel_2_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL2][2] == 240) MenuStatus[MENU_CHANNEL2][2] = 241;
			else MenuStatus[MENU_CHANNEL2][2] = 240;
			
			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;
			
			UpdateTrigger(56);						
			Display::StatusUpdate();

			New_Menu = 2;
			Menu_Changed = 1;
			
			break;
		}
	
		// Channel 3 -> Invert
		case 3 :
		{
			if (Channel_3_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL3][2] == 240) MenuStatus[MENU_CHANNEL3][2] = 241;
			else MenuStatus[MENU_CHANNEL3][2] = 240;
			
			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;
			
			UpdateTrigger(57);						
			Display::StatusUpdate();

			New_Menu = 3;
			Menu_Changed = 1;
			
			break;
		}
	
		// Channel 4 -> Invert
		case 4 :
		{
			if (Channel_4_Active == 0) break;
			
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_CHANNEL4][2] == 240) MenuStatus[MENU_CHANNEL4][2] = 241;
			else MenuStatus[MENU_CHANNEL4][2] = 240;
			
			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;
			
			UpdateTrigger(58);
			Display::StatusUpdate();

			New_Menu = 4;
			Menu_Changed = 1;
			
			break;
		}		
			
		// Utility->Calibrate ADCs		-> BF added new menu function
		case 6 :
		{		
			UI_request = 0;
			printf("\nCalibrating ADC\n");
			
			Hardware::Calibrate_ADC_ZeroOffsets();	

			break;
		}
					
		// Service
		case 7 :
		{		
			//
			break;
		}

		// Save / Recall  - > Recall Signal
		case 8 :
		{	
			switch(SavePointer)
			{
				case 1 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A01); break;
				case 2 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A02); break;
				case 3 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A03); break;
				case 4 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A04); break;
				case 5 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A05); break;
				case 6 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A06); break;
				case 7 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A07); break;
				case 8 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A08); break;
				case 9 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A09); break;
				case 10 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A10); break;
				case 11 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A11); break;
				case 12 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A12); break;
				case 13 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A13); break;
				case 14 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A14); break;
				case 15 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A15); break;
				case 16 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_A16); break;
	
				case 17 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B01); break;
				case 18 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B02); break;
				case 19 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B03); break;
				case 20 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B04); break;
				case 21 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B05); break;
				case 22 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B06); break;
				case 23 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B07); break;
				case 24 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B08); break;
				case 25 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B09); break;
				case 26 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B10); break;
				case 27 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B11); break;
				case 28 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B12); break;
				case 29 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B13); break;
				case 30 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B14); break;
				case 31 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B15); break;
				case 32 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_B16); break;
	
				case 33 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C01); break;
				case 34 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C02); break;
				case 35 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C03); break;
				case 36 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C04); break;
				case 37 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C05); break;
				case 38 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C06); break;
				case 39 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C07); break;
				case 40 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C08); break;
				case 41 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C09); break;
				case 42 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C10); break;
				case 43 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C11); break;
				case 44 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C12); break;
				case 45 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C13); break;
				case 46 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C14); break;
				case 47 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C15); break;
				case 48 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_C16); break;
	
				case 49 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D01); break;
				case 50 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D02); break;
				case 51 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D03); break;
				case 52 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D04); break;
				case 53 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D05); break;
				case 54 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D06); break;
				case 55 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D07); break;
				case 56 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D08); break;
				case 57 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D09); break;
				case 58 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D10); break;
				case 59 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D11); break;
				case 60 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D12); break;
				case 61 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D13); break;
				case 62 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D14); break;
				case 63 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D15); break;
				case 64 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_D16); break;
	
				case 65 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E01); break;
				case 66 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E02); break;
				case 67 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E03); break;
				case 68 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E04); break;
				case 69 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E05); break;
				case 70 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E06); break;
				case 71 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E07); break;
				case 72 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E08); break;
				case 73 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E09); break;
				case 74 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E10); break;
				case 75 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E11); break;
				case 76 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E12); break;
				case 77 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E13); break;
				case 78 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E14); break;
				case 79 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E15); break;
				case 80 :	AMDFlash::load_signal_from_flash(SAVE_SIGNAL_NR_E16); break;
			}

			break;
		}

		// Print
		case 9 :
		{		
	//
			break;
		}

		// Timebase-> X-Y Mode (function button 3 pressed)
		case 10 :
		{		
			//BF del for ch 3 + 4 support  if ((Channel_1_Active == false) || (Channel_2_Active == false)) break;
			
			//only if channel 1 + 2 or 3 + 4 or all are active, else leave
 			if (!(Channel_1_Active && Channel_2_Active) && !(Channel_3_Active && Channel_4_Active))	break;

			//BF added for restoring zero levels
			ZeroLevelCH1_Main_bak = ZeroLevelCH1;
    			ZeroLevelCH2_Main_bak = ZeroLevelCH2;
			ZeroLevelCH3_Main_bak = ZeroLevelCH3;
			ZeroLevelCH4_Main_bak = ZeroLevelCH4;
			
			Virtual_ZeroLevelCH1_Main_bak = Virtual_ZeroLevelCH1;
			Virtual_ZeroLevelCH2_Main_bak = Virtual_ZeroLevelCH2;
			Virtual_ZeroLevelCH3_Main_bak = Virtual_ZeroLevelCH3;
			Virtual_ZeroLevelCH4_Main_bak = Virtual_ZeroLevelCH4;

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_TIMEBASE][2] == 0)				//Check if XY-mode is not active yet
			{
				if (MenuStatus[MENU_TIMEBASE][0] == 1)			//main mode active?
				{
					MenuItemChanged[0] = 1;
					MenuStatus[MENU_TIMEBASE][0]  = 0;			//switch off main mode
				}
				else if (MenuStatus[MENU_TIMEBASE][1] == 1)		//delayed mode active?
				{				
					MenuItemChanged[1] = 1;
					MenuStatus[MENU_TIMEBASE][1]  = 0;			//switch off delayed mode
				}
				
				if (QM_Enabled)
				{
					QM_Enabled_Old           = QM_Enabled;
					QM_Enabled               = false;
					Quick_Measure_First_Draw = 0;
					MenuStatusChanged        = 1;
		
					// remove the cursor data
					for (ix = 407 * 20; ix < 430 * 20; ix++)
					{
						*(UI_Plane1 + ix) = 0;		// delete
						//*(Buffer_UI2Plane + ix) = 0;	// delete Text	Guido:del
						*(UI_Plane2 + ix) =0;		//Guido add: delete button-text
						*(UI_Plane4 + ix) = 0;		// delete
						*(UI_Plane5 + ix) = 0;		// delete
					}
		
					LED_ON[7] = 0;
						
					//New_Menu = 19;
					Menu_Changed = 1;
					//MenuAktive = 0;
						
					Display::CALCQMDATA();
				}

				if (Channel_Math_Active)		//Math function active?
				{
					LED_ON[4] = 0;
					Channel_Math_Active = 0;	//switch off math function
				}
	
				if (USTB_Mode != USTB_OFF)
				Display::USTB_Clear_Buffer();

				Send_LED();
		
				//Draw XY-grid into the grid plane
				//Display::GRIDXY(GRID_XY_XOFFS, GRID_YOFFS, Grid_Plane);		//draw grid
				//GridColor_Val = GridColorArray[GridColorArrayPos];		//grid intensity
				//MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//menu text item
				//SetupADC();							//set intensity

				MenuStatus[MENU_TIMEBASE][2] = 1;				//Switch XY-mode on
				XY_Mode      = 1;

				New_Menu     = 10;
				Menu_Changed = 1;

				config_changed = 1;

				if(Channel_1_Active && Channel_2_Active)
				{
					//Virtual_ZeroLevelCH1 = 0;
					//Virtual_ZeroLevelCH2 = 0;
					
					ON_Zero_Channel_1();
					ON_Zero_Channel_2();
				}
			

				if(Channel_3_Active && Channel_4_Active)
				{
					//Virtual_ZeroLevelCH3 = 0;
					//Virtual_ZeroLevelCH4 = 0;
					
					ON_Zero_Channel_3();
					ON_Zero_Channel_4();
				}

				SetupADC();
				
				Display::DRAWSTATUS(0, 1);
				ClearPlanes();
			}

			Display::RefreshScreen();
			Display::DRAW_ALL_CURSOR();
				
			break;							
		}

	
		// Trigger Mode -> Reject
		case 12 :
		{
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 12)) { Display::DRAWMENUPOPDOWN(); }
		
			if (MenuPopupActive == 12)
			{
				if (MenuPopupStatus[12][0] == 3)	
				{
					MenuPopupStatus[12][0] = 2;
					MenuPopupStatus[12][1] = 3;
					MenuStatus[MENU_TRIGGERMODE][2] = 98;
				}
				else if (MenuPopupStatus[12][1] == 3)	
				{
					MenuPopupStatus[12][0] = 3;
					MenuPopupStatus[12][1] = 2;
					MenuStatus[MENU_TRIGGERMODE][2]      = 97;
				}

				New_Menu           = 12;
				Menu_Changed       = 1;
				MenuItemChanged[2] = 1;

				//UpdateTrigger();    						
			}

			Display::DRAWMENUPOPUP(12);
			break;
		}

		// Edge -> External
		case 14 :
		{				
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 8)) { Display::DRAWMENUPOPDOWN(); }			

#ifdef _Debug_						
printf("MPA1 %d SEE %d MPS[8][0] %d MPS[8][1] %d MPS[8][2] %d\n", MenuPopupActive, SelectedEdgeExtern, MenuPopupStatus[8][0], MenuPopupStatus[8][1], MenuPopupStatus[8][2]);
#endif	
			if (MenuStatus[MENU_TRIGGEREDGE][2] == 0)
			{				
				MenuItemChanged[1] = 1;
				MenuStatus[MENU_TRIGGEREDGE][1] = 0;
						
				MenuItemChanged[2] = 1;		
				MenuStatus[MENU_TRIGGEREDGE][2] = 1;
				
				MenuItemChanged[3] = 1;
				MenuStatus[MENU_TRIGGEREDGE][3] = 0;		

				TriggerLevelChanged = 1;
				TriggerWayChanged = 1;	

				if (MenuPopupStatus[8][0] == 3)
				{					
					Selected_Trigger_Source = 5;	
					SelectedEdgeExtern = 0;             // External
				}
				else if (MenuPopupStatus[8][1] == 3)
				{					
					Selected_Trigger_Source = 5;	
					SelectedEdgeExtern = 0;             // External
				}
				else if (MenuPopupStatus[8][1] == 3)
				{					
					Selected_Trigger_Source = 6;	
					SelectedEdgeExtern = 1;             // External
				}

				New_Menu = 14;
				Menu_Changed = 1;

				UpdateTrigger(9);

				Display::StatusUpdate();
				Display::DRAWMENUPOPUP(8);
			}
			else
			{				
				if ((MenuPopupActive > -1) && (MenuPopupActive != 8)) { Display::DRAWMENUPOPDOWN(); }
				if (MenuPopupActive == 8)
				{
					if (MenuPopupStatus[8][0] == 3)	
					{
						SelectedEdgeExtern = 0;             // External LF
						Selected_Trigger_Source = 5;
						MenuPopupStatus[8][0] = 2;
						MenuPopupStatus[8][1] = 3;
						MenuPopupStatus[8][2] = 2;
					}
					else if (MenuPopupStatus[8][1] == 3)	
					{
						SelectedEdgeExtern = 1;             // External HF
						Selected_Trigger_Source = 6;
						MenuPopupStatus[8][0] = 2;
						MenuPopupStatus[8][1] = 2;
						MenuPopupStatus[8][2] = 3;
					}
					else if (MenuPopupStatus[8][2] == 3)	
					{
						SelectedEdgeExtern = 0;             // Line
						Selected_Trigger_Source = 5;
						MenuPopupStatus[8][0] = 3;
						MenuPopupStatus[8][1] = 2;
						MenuPopupStatus[8][2] = 2;
					} 			
				}	
#ifdef _Debug_						
printf("MPA2 %d SEE %d MPS[8][0] %d MPS[8][1] %d MPS[8][2] %d\n", MenuPopupActive, SelectedEdgeExtern, MenuPopupStatus[8][0], MenuPopupStatus[8][1], MenuPopupStatus[8][2]);
#endif															
				TriggerLevelChanged = 1;
				TriggerWayChanged = 1;					
				
				New_Menu = 14;
				Menu_Changed = 1;

				UpdateTrigger(10);

				Display::StatusUpdate();
				Display::DRAWMENUPOPUP(8);
			}
			break;
		}
			
		// Pulse Width -> Dir
		case 15 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			if (MenuStatus[MENU_PULSEWIDTH][2] == 2)
			{
				MenuStatus[MENU_PULSEWIDTH][2] = 1;
				PulseToggle = 2;					
			}
			else if (MenuStatus[MENU_PULSEWIDTH][2] == 1)
			{
				MenuStatus[MENU_PULSEWIDTH][2] = 3;
				PulseToggle = 1;			
			}
			else
			{
				MenuStatus[MENU_PULSEWIDTH][2] = 2;
				PulseToggle = 1;
			}
#ifdef _Debug_					
			printf("PW MS[15/2] %d PT %d\n", MenuStatus[MENU_PULSEWIDTH][2], PulseToggle);
#endif					
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
			MenuItemChanged[5] = 1;					
			MenuStatusChanged = 1;
			TriggerWayChanged = 1;
		
			New_Menu = 15;
			Menu_Changed = 1;

			Display::StatusUpdate();
			UpdateTrigger(11);

			break;	
		}		
	
		// Cursor -> X2		
		case 16 :
		{
			if (Cursor_Enabled == 0) break;
			{
				if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

				if (Cursor_Vertical_Active_Old == 1) MenuItemChanged[1] = 1;
				else if (Cursor_Vertical_Active_Old == 4) MenuItemChanged[5] = 1;
				else if (Cursor_Horizontal_Active_Old == 1) MenuItemChanged[3] = 1;
				else if (Cursor_Horizontal_Active_Old == 2) MenuItemChanged[4] = 1;
				else if (Cursor_Horizontal_Active_Old == 4) MenuItemChanged[5] = 1;

				Cursor_Vertical_Active = 2;
				Cursor_Horizontal_Active = 3;
	
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();

							
				New_Menu = 16;
				Menu_Changed = 1;
	
				Display::DRAW_ALL_CURSOR();
			}
			break;		
		}
		
		// Quick Print -> Save to JPEG
		// BF -> new screenshot function from Niklas 
		case 17 :
		{	
			//BF del if (USB_Connected == false) break;

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			//if (MenuStatus[MENU_QUICKPRINT][2] == 143) MenuStatus[MENU_QUICKPRINT][2] = 144;
			//else MenuStatus[MENU_QUICKPRINT][2] = 143;
	
			MenuItemChanged[2] = 1;
							
			New_Menu = 17;
			Menu_Changed = 1;

			Display::SCREENSHOT_BW();

/* BF del because next to useless
			if ((USB_Data_Requested == false) && (USB_Data_Trans == false))
			{					
				send_buffer[0] = 150;			// Command Quick Print requested
				send_buffer[1] = 2;  	      	 	// JPEG
				send_buffer[2] = 0;
						
				SendData(send_buffer);					
			}
*/							
			break;					
		}					
	
		// About Oscilloscope
		case 18 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			//Display::PopUp(3);
			break;
		}	

		// Quick Measurement -> Add Measurement
		case 19 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }				
			
			QM_Type_Old[0] = QM_Type[0];
			QM_Type_Old[1] = QM_Type[1];
			QM_Type_Old[2] = QM_Type[2];

			if (QM_Type[0] == 0)
			{
				QM_Type[0] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
				QM_Changed[0] = 1;
				QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
			}
			else if (QM_Type[1] == 0)
			{
				if ((QM_Type[0] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[0] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[1] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
					QM_Changed[1] = 1;
					QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				}
			}
			else if (QM_Type[2] == 0)
			{
				if ((QM_Type[1] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[1] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[2] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
					QM_Changed[2] = 1;
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				}
			}
			else
			{
				if ((QM_Type[2] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[2] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[0] = QM_Type[1];
					QM_Type[1] = QM_Type[2];
					QM_Type[2] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
		
					QM_Channel[0] = QM_Channel[1];
					QM_Channel[1] = QM_Channel[2];
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
		
					QM_Changed[0] = 1;
					QM_Changed[1] = 1;
					QM_Changed[2] = 1;
				}
			}

			if (NumberOfChannels == 2)
			{
				if (QM_Channel[0] == 3) QM_Channel[0] = 5;
				if (QM_Channel[1] == 3) QM_Channel[1] = 5;
				if (QM_Channel[2] == 3) QM_Channel[2] = 5;
			}

			Quick_Measure_First_Draw = 1;

			New_Menu = 19;
			Menu_Changed = 1;
#ifdef _Debug_
if (Debug_Mode) printf("QT1 : %d QT2 : %d QT3 : %d MS19,1 : %d\n", QM_Type[0], QM_Type[1], QM_Type[2], MenuStatus[MENU_QUICKMEASUREMENT][1]);
#endif
			//QM_Vertical_Active = 0;
			//QM_Horizontal_Active = 0;

			Display::CALCQMDATA();

			break;
		}
		
		// Quick Measurement Delay Settings
		case 20 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if ((MenuPopupActive > -1) && (MenuPopupActive != 6)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 6)
			{
				pos = -1;
				MenuPopupStep(6, &MenuStatus[MENU_QMDELAY][2], &pos, &pos, 20, 27, 2);
				
				New_Menu = 20;
				Menu_Changed = 1;
			}				
				
			Display::DRAWMENUPOPUP(6);
			break;
		}	
		
		// Quick Measurement Phase Settings
		case 21 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if ((MenuPopupActive > -1) && (MenuPopupActive != 25)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 25)
			{
				pos = -1;
				MenuPopupStep(25, &MenuStatus[21][2], &pos, &pos, 21, 27, 2);
				
				New_Menu = 21;
				Menu_Changed = 1;
			}				
				
			Display::DRAWMENUPOPUP(25);
			break;
		}

		// Quick Measurement Threshold -> Lower
		case 22 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			if (Quick_Measure_Threshold_btn_select == 2) MenuItemChanged[3] = 1;
			else if (Quick_Measure_Threshold_btn_select == 3) MenuItemChanged[4] = 1;

			Quick_Measure_Threshold_btn_select = 1;

			New_Menu = 22;
			Menu_Changed = 1;

			break;
		} 

		// Trigger Mode TV
		case 24 :
		{
			if ((MenuPopupActive > -1) && (MenuPopupActive != 21)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 21)
			{
				pos = -1;
				MenuPopupStep(21, &MenuStatus[MENU_TRIGGERTV][2], &pos, &pos, 24, 114, 2);
				
				New_Menu = 24;
				Menu_Changed = 1;
			}				
			
			Display::DRAWMENUPOPUP(21);	
			break;
		}

		// Math - 1 * 2
		case 26 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_MATH][2] == 0)
			{
				// If math menu was active and FFT was active bevore - switch back to old settings
				if (Channel_Math_Active && (Active_Menu == MENU_MATH) && (MenuStatus[MENU_MATH][1] == 1))
				{
					FFT_Mode = FFT_OFF;
/*
					// refresh screen
					if (MenuStatus[MENU_TIMEBASE][1] == 1) 			//delayed mode
					 Display::GRIDDELAYED(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
					else if (MenuStatus[MENU_TIMEBASE][0] == 1) 		//main mode
					 Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);	
*/					
					GridColor_Val = GridColorArray[GridColorArrayPos];		//grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//menu text item
					SetupADC();							//set intensity

					//restore channel setting
					FFT_Restore_Channels();
					
					// restore zerolevels
					Zero_Levels_Restore();	

					//restore triggermode
					MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;	
					MenuPopupStatus[9][0] = 2;
					MenuPopupStatus[9][1] = 3;
					TriggerLevelChanged = 1;
					TriggerModeChanged = 1;
					UpdateTrigger(4);

					Display::RefreshScreen();

				}

				if (MenuStatus[MENU_MATH][1] == 1)
				{
					MenuItemChanged[1] = 1;
					MenuStatus[MENU_MATH][1] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][3] == 1)
				{
					MenuItemChanged[3] = 1;
					MenuStatus[MENU_MATH][3] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][4] == 1)
				{
					MenuItemChanged[4] = 1;
					MenuStatus[MENU_MATH][4] = 0;
				}
														
				MenuStatus[MENU_MATH][2] = 1;

				New_Menu = MENU_MATH;
				Menu_Changed = 1;
			}
				
			break;
		}

		// FFT - Settings - FFT-Mode
		case 27 :
		{					
			if ((MenuPopupActive > -1) && (MenuPopupActive != 31)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 31)
			{
				pos = -1;
				MenuPopupStep(31, &MenuStatus[MENU_FFT][2], &pos, &pos, 27, 66, 2);
			}

			New_Menu = 27;
			Menu_Changed = 1;

			Display::DRAWMENUPOPUP(31);	

			FFT_Mode = MenuStatus[MENU_FFT][2] - 65;
			
			Display::RefreshScreen();

			//Save new values to flash
			config_changed = true;

			break;	
		}


/* BF -> not needed for the new FFT		
		
		// FFT - Settings - Offset
		case 27 :
		{					
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
	
			FFTToggle = 1;
		
			MenuItemChanged[1] = 1;
			MenuItemChanged[2] = 1;					

			New_Menu = 27;
			Menu_Changed = 1;

			break;
		}
*/

	}
#ifdef _Debug_						
			if (Debug_Mode) printf("Function Button 3\n");
#endif
}
// BF insert end
//######################################################################################################################################################
// BF insert
//Function button 4 pressed
void Hardware::F4_Btnhandler(void)					// Button Handler for function button
{
			
	short pos = 0;
	int ix;
	int buf_int;

#ifdef _Debug_		
       	printf("F4 Btn start\n");
#endif	
	
	if (MenuPopupActive > 0) ResetTimer();
//	if (ZeroPopupChanged > 0) ResetTimer();
	
	if ((Active_Menu == 1) && (Channel_1_Active == false)) return;
	if ((Active_Menu == 2) && (Channel_2_Active == false)) return;
	if ((Active_Menu == 3) && (Channel_3_Active == false)) return;
	if ((Active_Menu == 4) && (Channel_4_Active == false)) return;
	//if ((Active_Menu == 26) && (Channel_Math_Active == false)) return;
				
	if ((Active_Menu == 16) && (Cursor_Enabled == false)) return;
	if ((Active_Menu == 19) && (QM_Enabled == false)) return;
	if ((Active_Menu == 20) && (QM_Enabled == false)) return;
	if ((Active_Menu == 21) && (QM_Enabled == false)) return;
	if ((Active_Menu == 22) && (QM_Enabled == false)) return;

	MenuButtonCheck(3);
			
	switch(Active_Menu)
	{				
		// Display -> Grid
		case 5 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			if(MenuStatus[MENU_DISPLAY][3] == 240)	//Check if Vectors are off
			{ MenuStatus[MENU_DISPLAY][3] = 241; }	//switch vectors on
			else
			{ MenuStatus[MENU_DISPLAY][3] = 240; }	//switch vectors off
			
			New_Menu = 5;
			Menu_Changed = 1;
			break;
		}	

		// Utility -> Calibrate DAC		-> BF added new menu function
		case 6 :
		{	
			UI_request = 0;
			printf("\nCalibrating ADC\n");

			Calibrate_DAC_ZeroOffsets();
			break;
		}
	
		// Service - RS-232 Setup
		case 7 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }	
			
			New_Menu = 21;
			Menu_Changed = 1;

			break;
		}	

		// Save / Recall
		case 8 :
		{
			Set_Vars_Default();
			// BF insert - Recalc vars			
			Recalc_Vars();
			// BF insert - init display
			Display::RefreshScreen();

			UpdateChannel(1, 1);
			UpdateChannel(2, 1);
			
			VoltageChangedCh1 = 1;
			VoltageChangedCh2 = 1;
			
			LED_ON[0] = 1;
			LED_ON[1] = 1;
			LED_ON[5] = 1;
			LED_ON[6] = 0;
	
			Rotary_Steps = 0;
			ON_Zero_Channel_1();
			Rotary_Steps = 0;
			ON_Zero_Channel_2();
	
			SetSwitches(1, Selected_Voltage_CH1);
			SetSwitches(2, Selected_Voltage_CH2);
	
			if (NumberOfChannels > 2)
			{
				UpdateChannel(3, 1);
				UpdateChannel(4, 1);
	
				VoltageChangedCh3 = 1;
				VoltageChangedCh4 = 1;
			
				LED_ON[2] = 1;
				LED_ON[3] = 1;
			
				Rotary_Steps = 0;
				ON_Zero_Channel_3();
				Rotary_Steps = 0;
				ON_Zero_Channel_4();
	
				SetSwitches(3, Selected_Voltage_CH3);
				SetSwitches(4, Selected_Voltage_CH4);
	
			}
			else
			{
				UpdateChannel(3, 0);
				UpdateChannel(4, 0);
			}

			TriggerLevelChanged = 1;
			TriggerModeChanged  = 1;	
			TriggerWayChanged   = 1;
			TimebaseChanged     = 1;
			TimeOffsetChanged   = 1;
			MenuStatusChanged   = 1;
			MenuAktive          = 1;

			Cursor_Data_First_Draw   = 0;
			Quick_Measure_First_Draw = 0;

			// remove the cursor data
			for (ix = 408 * 20; ix < 430 * 20; ix++)
			{
				*(UI_Plane1 + ix) = 0;		// delete
				*(Buffer_UI2Plane + ix) = 0;	// delete Text				
				*(UI_Plane4 + ix) = 0;		// delete
				*(UI_Plane5 + ix) = 0;		// delete
			}				

			UpdateTrigger(12);
			Display::CALCPRETRIGGER();
			Display::DRAW_ALL_CURSOR();

/* BF del	
			Display::DRAWSQUAREBUTTON(2, 1, 14, 16, btnPushed, btnDraw);				// Button
			Display::TEXTOUTvbig("1", 6, 4, 1, Channel_Plane1);					// Draw Voltage Text
	//                    Display::TEXTOUTvbig("1", 6, 4, 1, Buffer_Plane1);				// Draw Voltage Text
	
			Display::DRAWSQUAREBUTTON(78, 1, 14, 16, btnPushed, btnDraw);				// Button
			Display::TEXTOUTvbig("2", 82, 4, 1, Channel_Plane2);					// Draw Voltage Text
	//                    Display::TEXTOUTvbig("2", 82, 4, 1, Buffer_Plane2);				// Draw Voltage Text
	
			Display::StatusUpdate();
	
			if (NumberOfChannels > 2)
			{
				Display::DRAWSQUAREBUTTON(154, 1, 14, 16, btnPushed, btnDraw);			// Button
				Display::TEXTOUTvbig("3", 158, 4, 1, Channel_Plane3);				// Draw Voltage Text
	//                        Display::TEXTOUTvbig("3", 158, 4, 1, Buffer_Plane3);				// Draw Voltage Text
	
				Display::DRAWSQUAREBUTTON(230, 1, 14, 16, btnPushed, btnDraw);			// Button		
				Display::TEXTOUTvbig("4", 234, 4, 1, Channel_Plane4);				// Draw Voltage Text
	//                        Display::TEXTOUTvbig("4", 234, 4, 1, Buffer_Plane4);				// Draw Voltage Text
			}
	
			Display::DRAWSTATUS(6, 0);
*/		
			// BF insert - init display
			Display::RefreshScreen();
			
			Send_LED();
			config_changed = true;  			// TMW changed (added save paramter on default)
			//BF del AMDFlash::Write_Config_Flash();	// TMW changed (added save paramter on default)
				
			break;
		}	
	
		
		// USTB-Rollmode
		case 10 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_TIMEBASE][3] == 0)
			{
				MenuStatus[MENU_TIMEBASE][3] = 1;	//set roll mode to on 
				MenuStatus[MENU_TIMEBASE][4] = 0;	//set shift mode to off

				New_Menu = MENU_TIMEBASE;
				Menu_Changed = 1;

				MenuItemChanged[3] = 1;
				MenuItemChanged[4] = 1;		

				Display::DRAWSTATUS(0, 1);

				if(USTB_Mode != USTB_OFF)
				{
					Display::USTB_Clear_Buffer();
					USTB_Mode = USTB_ROLL;
				}
				//ClearPlanes();
			}
			//Display::DRAW_ALL_CURSOR();
							
			break;							
		}		
					
		// Trigger Mode  -> Holdoff
		case 12 :
		{
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }	
		
			if (EdgeToggle == 0)
			{		
				buf_int = (int) (HoldOff.Read_Value() * 100000000);	

				printf("HF bi : %d\n", buf_int);
		
				if (Rotary_Direction_mem_pulse == 1)
				{	
					if (buf_int == 0)
					{
						HoldOff.Write_Value(0.000000040);
		
						HoldOff_Value = 120;
						HoldOff_Steps = 40;
						HoldOff_Expo = 1;
					}
					else if ((buf_int >= 1) && (buf_int < 100))
					{
						HoldOff.Write_Value(0.000001);
		
						HoldOff_Value = 1;
						HoldOff_Steps = 1;
						HoldOff_Expo = 2;
					}
					else if ((buf_int >= 100) && (buf_int < 1000))
					{
						HoldOff.Write_Value(0.00001);
		
						HoldOff_Value = 10;
						HoldOff_Steps = 1;
						HoldOff_Expo = 2;
					}
					else if ((buf_int >= 1000) && (buf_int < 10000))
					{
						HoldOff.Write_Value(0.0001);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 2;
					}
					else if ((buf_int >= 10000) && (buf_int < 100000))
					{
						HoldOff.Write_Value(0.001);
		
						HoldOff_Value = 1;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
					else if ((buf_int >= 100000) && (buf_int < 1000000))
					{
						HoldOff.Write_Value(0.01);
		
						HoldOff_Value = 10;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
					else if ((buf_int >= 1000000) && (buf_int < 10000000))
					{
						HoldOff.Write_Value(0.1);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
					else if ((buf_int >= 10000000) && (buf_int < 100000000))
					{
						HoldOff.Write_Value(1);
		
						HoldOff_Value = 1;
						HoldOff_Steps = 1;
						HoldOff_Expo = 4;
					}
					else if ((buf_int >= 100000000) && (buf_int < 1000000000))
					{
						HoldOff.Write_Value(10);
		
						HoldOff_Value = 10;
						HoldOff_Steps = 1;
						HoldOff_Expo = 4;
					}
					else if ((((int) (HoldOff.Read_Value() * 1000000)) >= 10000000) && (((int) (HoldOff.Read_Value() * 1000000)) < 100000000))
					{
						HoldOff.Write_Value(100);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 4;
					}
					else
					{
						HoldOff.Write_Value(0);
		
						HoldOff_Value = 0;
						HoldOff_Steps = 40;
						HoldOff_Expo = 1;
					}
				}
				else 	                 		
				{
					if (buf_int == 0)
					{
						HoldOff.Write_Value(100);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 4;
					}
					else if (buf_int == 4)
					{
						HoldOff.Write_Value(0);
		
						HoldOff_Value = 0;
						HoldOff_Steps = 40;
						HoldOff_Expo = 1;
					}
					else if (buf_int == 12)
					{
						HoldOff.Write_Value(0.000000040);
		
						HoldOff_Value = 40;
						HoldOff_Steps = 40;
						HoldOff_Expo = 1;
					}
					else if ((buf_int > 10) && (buf_int <= 100))
					{
						HoldOff.Write_Value(0.000000120);
		
						HoldOff_Value = 120;
						HoldOff_Steps = 40;
						HoldOff_Expo = 1;
					}
					else if ((buf_int > 100) && (buf_int <= 1000))
					{
						HoldOff.Write_Value(0.000001);
		
						HoldOff_Value = 1;
						HoldOff_Steps = 1;
						HoldOff_Expo = 2;
					}
					else if ((buf_int > 1000) && (buf_int <= 10000))
					{
						HoldOff.Write_Value(0.00001);
		
						HoldOff_Value = 10;
						HoldOff_Steps = 1;
						HoldOff_Expo = 2;
					}
					else if ((buf_int > 10000) && (buf_int <= 100000))
					{
						HoldOff.Write_Value(0.0001);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 2;
					}
		
					else if ((buf_int > 100000) && (buf_int <= 1000000))
					{
						HoldOff.Write_Value(0.001);
		
						HoldOff_Value = 1;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
					else if ((buf_int > 1000000) && (buf_int <= 10000000))
					{
						HoldOff.Write_Value(0.01);
		
						HoldOff_Value = 10;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
					else if ((buf_int > 10000000) && (buf_int <= 100000000))
					{
						HoldOff.Write_Value(0.1);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
					else if ((buf_int > 100000000) && (buf_int <= 1000000000))
					{
						HoldOff.Write_Value(1);
		
						HoldOff_Value = 1;
						HoldOff_Steps = 1;
						HoldOff_Expo = 4;
					}
					else if ((((int) (HoldOff.Read_Value() * 1000000)) > 10000000) && (((int) (HoldOff.Read_Value() * 1000000)) <= 100000000))
					{
						HoldOff.Write_Value(10);
		
						HoldOff_Value = 10;
						HoldOff_Steps = 1;
						HoldOff_Expo = 4;
					}
					else
					{
						HoldOff.Write_Value(0.1);
		
						HoldOff_Value = 100;
						HoldOff_Steps = 1;
						HoldOff_Expo = 3;
					}
				}

		
				HoldOff.RenderText();				
			}
		
			EdgeToggle = 0;
			New_Menu = 12;
			Menu_Changed = 1;
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
	
			UpdateTrigger(13);


			break;
		}	


		// Edge -> TV
		case 14 :
		{	
			Menu_Popup_visible =1; // TMW added to repair multiple records after menu popup

			if ((MenuPopupActive > -1) && (MenuPopupActive != 11)) { Display::DRAWMENUPOPDOWN(); }			

			if (MenuStatus[MENU_TRIGGEREDGE][3] == 0)
			{				
				MenuItemChanged[1] = 1;
				MenuStatus[MENU_TRIGGEREDGE][1] = 0;
						
				MenuItemChanged[2] = 1;								
				MenuStatus[MENU_TRIGGEREDGE][2] = 0;
				
				MenuItemChanged[3] = 1;
				MenuStatus[MENU_TRIGGEREDGE][3] = 1;						
				
				New_Menu = 14;
				Menu_Changed = 1;

									
			}
			else
			{
				if (MenuPopupActive == 11)
				{
					if (MenuPopupStatus[11][0] == 3)	
					{
						MenuPopupStatus[11][0] = 2;
						MenuPopupStatus[11][1] = 3;
					}
					else
					{
						MenuPopupStatus[11][0] = 3;
						MenuPopupStatus[11][1] = 2;
					}
				}
			}
			
			TriggerLevelChanged = 1;
			TriggerWayChanged = 1;		
			Selected_Trigger_Source = 6;
			SelectedEdgeExtern = 2;               // TV CH 1	

			Display::StatusUpdate();
				
			UpdateTrigger(14);	
			
			Display::DRAWMENUPOPUP(11);

			break;
		} 
	
		// Pulse Width
		case 15 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			if (MenuStatus[MENU_PULSEWIDTH][2] == 1) break;

			if (MenuStatus[MENU_PULSEWIDTH][2] == 3)
			{					
				if (PulseToggle == 1)
				{					
					buf_int = (int) (Pulse11.Read_Value() * 100000000);	
					
					if (Rotary_Direction_mem_pulse == 1)
					{				
						if ((buf_int >= 1) && (buf_int < 10))
						{
							Pulse11.Write_Value(0.000000104);
			
							Pulse11_Value = 104;
							Pulse11_Steps = 8;
							Pulse11_Expo = 1;
						}
						else if ((buf_int >= 10) && (buf_int < 100))
						{
							Pulse11.Write_Value(0.000001);
			
							Pulse11_Value = 1;
							Pulse11_Steps = 1;
							Pulse11_Expo = 2;
						}
						else if ((buf_int >= 100) && (buf_int < 1000))
						{
							Pulse11.Write_Value(0.00001);
			
							Pulse11_Value = 10;
							Pulse11_Steps = 1;
							Pulse11_Expo = 2;
						}
						else if ((buf_int >= 1000) && (buf_int < 10000))
						{
							Pulse11.Write_Value(0.0001);
			
							Pulse11_Value = 100;
							Pulse11_Steps = 1;
							Pulse11_Expo = 2;
						}
						else if ((buf_int >= 10000) && (buf_int < 100000))
						{
							Pulse11.Write_Value(0.001);
			
							Pulse11_Value = 1;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
						else if ((buf_int >= 100000) && (buf_int < 1000000))
						{
							Pulse11.Write_Value(0.01);
			
							Pulse11_Value = 10;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
						else if ((buf_int >= 1000000) && (buf_int < 10000000))
						{
							Pulse11.Write_Value(0.1);
			
							Pulse11_Value = 100;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
						else
						{
							Pulse11.Write_Value(0.000000016);
			
							Pulse11_Value = 16;
							Pulse11_Steps = 8;
							Pulse11_Expo = 1;
						}
					}
					else 	
					{
						if (buf_int == 1)
						{
							Pulse11.Write_Value(0.1);
			
							Pulse11_Value = 100;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
						else if (buf_int == 10)
						{
							Pulse11.Write_Value(0.000000016);
			
							Pulse11_Value = 16;
							Pulse11_Steps = 8;
							Pulse11_Expo = 1;
						}
						else if ((buf_int > 10) && (buf_int <= 100))
						{
							Pulse11.Write_Value(0.000000104);
			
							Pulse11_Value = 104;
							Pulse11_Steps = 8;
							Pulse11_Expo = 1;
						}
						else if ((buf_int > 100) && (buf_int <= 1000))
						{
							Pulse11.Write_Value(0.000001);
			
							Pulse11_Value = 1;
							Pulse11_Steps = 1;
							Pulse11_Expo = 2;
						}
						else if ((buf_int > 1000) && (buf_int <= 10000))
						{
							Pulse11.Write_Value(0.00001);
			
							Pulse11_Value = 10;
							Pulse11_Steps = 1;
							Pulse11_Expo = 2;
						}
						else if ((buf_int > 10000) && (buf_int <= 100000))
						{
							Pulse11.Write_Value(0.0001);
			
							Pulse11_Value = 100;
							Pulse11_Steps = 1;
							Pulse11_Expo = 2;
						}
						else if ((buf_int > 100000) && (buf_int <= 1000000))
						{
							Pulse11.Write_Value(0.001);
			
							Pulse11_Value = 1;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
						else if ((buf_int > 1000000) && (buf_int <= 10000000))
						{
							Pulse11.Write_Value(0.01);
			
							Pulse11_Value = 10;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
						else
						{
							Pulse11.Write_Value(0.1);
			
							Pulse11_Value = 100;
							Pulse11_Steps = 1;
							Pulse11_Expo = 3;
						}
					}					
		
					Pulse11.RenderText();
					trig_width_reg = (unsigned int) (Pulse11.Read_Value() / (float) 0.000000008);
				}
				else PulseToggle = 1;
			}
			else
			{
				if (PulseToggle == 1)
				{					
					buf_int = (int) (Pulse21.Read_Value() * 100000000);	
					
					if (Rotary_Direction_mem_pulse == 1)
					{				
						if ((buf_int >= 1) && (buf_int < 10))
						{
							Pulse21.Write_Value(0.000000104);
			
							Pulse21_Value = 104;
							Pulse21_Steps = 8;
							Pulse21_Expo = 1;
						}
						else if ((buf_int >= 10) && (buf_int < 100))
						{
							Pulse21.Write_Value(0.000001);
			
							Pulse21_Value = 1;
							Pulse21_Steps = 1;
							Pulse21_Expo = 2;
						}
						else if ((buf_int >= 100) && (buf_int < 1000))
						{
							Pulse21.Write_Value(0.00001);
			
							Pulse21_Value = 10;
							Pulse21_Steps = 1;
							Pulse21_Expo = 2;
						}
						else if ((buf_int >= 1000) && (buf_int < 10000))
						{
							Pulse21.Write_Value(0.0001);
			
							Pulse21_Value = 100;
							Pulse21_Steps = 1;
							Pulse21_Expo = 2;
						}
		
						else if ((buf_int >= 10000) && (buf_int < 100000))
						{
							Pulse21.Write_Value(0.001);
			
							Pulse21_Value = 1;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
						else if ((buf_int >= 100000) && (buf_int < 1000000))
						{
							Pulse21.Write_Value(0.01);
			
							Pulse21_Value = 10;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
						else if ((buf_int >= 1000000) && (buf_int < 10000000))
						{
							Pulse21.Write_Value(0.1);
			
							Pulse21_Value = 100;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
						else
						{
						Pulse21.Write_Value(0.000000016);
		
						Pulse21_Value = 16;
						Pulse21_Steps = 8;
						Pulse21_Expo = 1;
						}
					}
					else 
					{
						if (buf_int == 1)
						{
							Pulse21.Write_Value(0.1);
			
							Pulse21_Value = 100;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
						else if (buf_int == 10)
						{
							Pulse21.Write_Value(0.000000016);
			
							Pulse21_Value = 16;
							Pulse21_Steps = 8;
							Pulse21_Expo = 1;
						}
						else if ((buf_int > 10) && (buf_int <= 100))
						{
							Pulse21.Write_Value(0.000000104);
			
							Pulse21_Value = 104;
							Pulse21_Steps = 8;
							Pulse21_Expo = 1;
						}
						else if ((buf_int > 100) && (buf_int <= 1000))
						{
							Pulse21.Write_Value(0.000001);
			
							Pulse21_Value = 1;
							Pulse21_Steps = 1;
							Pulse21_Expo = 2;
						}
						else if ((buf_int > 1000) && (buf_int <= 10000))
						{
							Pulse21.Write_Value(0.00001);
			
							Pulse21_Value = 10;
							Pulse21_Steps = 1;
							Pulse21_Expo = 2;
						}
						else if ((buf_int > 10000) && (buf_int <= 100000))
						{
							Pulse21.Write_Value(0.0001);
			
							Pulse21_Value = 100;
							Pulse21_Steps = 1;
							Pulse21_Expo = 2;
						}
		
						else if ((buf_int > 100000) && (buf_int <= 1000000))
						{
							Pulse21.Write_Value(0.001);
			
							Pulse21_Value = 1;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
						else if ((buf_int > 1000000) && (buf_int <= 10000000))
						{
							Pulse21.Write_Value(0.01);
			
							Pulse21_Value = 10;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
						else
						{
							Pulse21.Write_Value(0.1);
			
							Pulse21_Value = 100;
							Pulse21_Steps = 1;
							Pulse21_Expo = 3;
						}
					}			
			
					Pulse21.RenderText();
					trig_width_reg = (unsigned int) ((Pulse21.Read_Value() / (float) 0.000000008));
				}
				else PulseToggle = 1;
			}

			
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
								
			New_Menu = 15;
			Menu_Changed = 1;
			TriggerWayChanged = 1;
			UpdateTrigger(27);

			Display::StatusUpdate();

			break;	
		}

		// Cursor -> Y1
		case 16 :
		{	
			if (Cursor_Enabled == 0) break;
			{
				if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }		

				if (Cursor_Vertical_Active_Old == 1) MenuItemChanged[1] = 1;
				else if (Cursor_Vertical_Active_Old == 4) MenuItemChanged[5] = 1;
				else if (Cursor_Vertical_Active_Old == 2) MenuItemChanged[2] = 1;
				else if (Cursor_Horizontal_Active_Old == 2) MenuItemChanged[4] = 1;
				else if (Cursor_Horizontal_Active_Old == 4) MenuItemChanged[5] = 1;
	
				Cursor_Vertical_Active = 3;
				Cursor_Horizontal_Active = 1; 			
	
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();

								
				New_Menu = 16;
				Menu_Changed = 1;
	
				Display::DRAW_ALL_CURSOR();
			}
			break;						
		}
		
		// Quick Print -> Save to CSV
		case 17 :
		{	
			//if (USB_Connected == false) break;
	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			//if (MenuStatus[MENU_QUICKPRINT][2] == 143) MenuStatus[MENU_QUICKPRINT][2] = 144;
			//else MenuStatus[MENU_QUICKPRINT][2] = 143;

			MenuItemChanged[3] = 1;
							
			New_Menu = 17;
			Menu_Changed = 1;
			
			Display::DUMPCSV();

/*
			if ((USB_Data_Requested == false) && (USB_Data_Trans == false))
			{					
				send_buffer[0] = 150;						// Command Quick Print requested
				send_buffer[1] = 3;                         // XLS
				send_buffer[2] = 0;
						
				SendData(send_buffer);					
			}
*/							
			break;					
		}				

		// Quick Measurement -> Clear
		case 19 :
		{		
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }				
		
			QM_Type_Old[0] = QM_Type[0];
			QM_Type_Old[1] = QM_Type[1];
			QM_Type_Old[2] = QM_Type[2];

			QM_Type[0] = 0;
			QM_Type[1] = 0;
			QM_Type[2] = 0;
	
			QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
			QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
			QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
	
			QM_Changed[0] = 0;
			QM_Changed[1] = 0;
			QM_Changed[2] = 0;
	
			Quick_Measure_First_Draw = 1;

			New_Menu = 19;
			Menu_Changed = 1;
	
			QM_Vertical_Active = 0;
			QM_Horizontal_Active = 0;
	
			Display::CALCQMDATA();

			break;
		}
	
		// Quick Measurement Settings
		case 20 :
		{		
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }	
			if (MenuStatus[MENU_QMDELAY][3] == 2) MenuStatus[MENU_QMDELAY][3] = 3;
			else MenuStatus[MENU_QMDELAY][3] = 2;
		
			New_Menu = 20;
			Menu_Changed = 1;

			break;
		}	

		// Quick Measurement Threshold -> Middle
		case 22 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			if (Quick_Measure_Threshold_btn_select == 1) MenuItemChanged[2] = 1;
			else if (Quick_Measure_Threshold_btn_select == 3) MenuItemChanged[4] = 1;

			Quick_Measure_Threshold_btn_select = 2;
			
			New_Menu = 22;
			Menu_Changed = 1;

			break;
		}
	
		// Trigger Mode TV
		case 24 :
		{
			if ((MenuPopupActive > -1) && (MenuPopupActive != 22)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 22)
			{
				pos = -1;
				MenuPopupStep(22, &MenuStatus[MENU_TRIGGERTV][3], &pos, &pos, 24, 119, 2);
				
				New_Menu = 24;
				Menu_Changed = 1;
			}				
			
			Display::DRAWMENUPOPUP(22);	
			break;
		}		

		// Math  1 - 2
		case 26 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_MATH][3] == 0)
			{
				// If math menu was active and FFT was active bevore - switch back to old settings
				if (Channel_Math_Active && (Active_Menu == MENU_MATH) && (MenuStatus[MENU_MATH][1] == 1))
				{
					FFT_Mode = FFT_OFF;
/*
					// refresh screen
					if (MenuStatus[MENU_TIMEBASE][1] == 1) 		//delayed mode
					 Display::GRIDDELAYED(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
					else if (MenuStatus[MENU_TIMEBASE][0] == 1) 	//main mode
					 Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
*/
					GridColor_Val = GridColorArray[GridColorArrayPos];		//grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//menu text item
					SetupADC();							//set intensity

					//restore channel setting
					FFT_Restore_Channels();

					// restore zerolevels
					Zero_Levels_Restore();	

					//restore triggermode
					MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;	
					MenuPopupStatus[9][0] = 2;
					MenuPopupStatus[9][1] = 3;
					TriggerLevelChanged = 1;
					TriggerModeChanged = 1;
					UpdateTrigger(4);

					Display::RefreshScreen();
	
				}
			
				if (MenuStatus[MENU_MATH][1] == 1)
				{
					MenuItemChanged[1] = 1;
					MenuStatus[MENU_MATH][1] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][2] == 1)
				{
					MenuItemChanged[2] = 1;
					MenuStatus[MENU_MATH][2] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][4] == 1)
				{
					MenuItemChanged[4] = 1;
					MenuStatus[MENU_MATH][4] = 0;
				}

				MenuStatus[MENU_MATH][3] = 1;

				New_Menu = MENU_MATH;
				Menu_Changed = 1;
			}
				
			break;
		}	
		
		// FFT - Settings - FFT-Length
		case 27 :
		{					
			if ((MenuPopupActive > -1) && (MenuPopupActive != 32)) { Display::DRAWMENUPOPDOWN(); }
			if (MenuPopupActive == 32)
			{
				pos = -1;
				MenuPopupStep(32, &MenuStatus[MENU_FFT][3], &pos, &pos, 27, 83, 2);
			}

			New_Menu = 27;
			Menu_Changed = 1;

			Display::DRAWMENUPOPUP(32);	

			if (MenuStatus[MENU_FFT][3] == 83)
			{
				 //if (FFT_Length !=  FFT_512)
				{ FFT_Length = FFT_512; FFT_Level = 9; Display::FFT_BuildTrigoTables(); }
			 }
			else if (MenuStatus[MENU_FFT][3] == 84)
			{
				//if (FFT_Length !=  FFT_1024)
				{ FFT_Length = FFT_1024; FFT_Level = 10; Display::FFT_BuildTrigoTables(); }
 			}

			//Display::RefreshScreen();
			Display::FFT_DrawStatus();

			//Save new values to flash
			config_changed = true;

			break;	
		}

	}	
#ifdef _Debug_		
	if (Debug_Mode) printf("Function Button 4\n");		
#endif


}
// BF insert end
//######################################################################################################################################################
// BF insert
//Function button 5 pressed
void Hardware::F5_Btnhandler(void)					// Button Handler for function button
{
	int buf_int;

#ifdef _Debug_		
       	printf("F5 Btn start\n");
#endif	
			
	if (MenuPopupActive > 0) ResetTimer();
//	if (ZeroPopupChanged > 0) ResetTimer();
			
	if ((Active_Menu == 1) && (Channel_1_Active == false)) return;
	if ((Active_Menu == 2) && (Channel_2_Active == false)) return;
	if ((Active_Menu == 3) && (Channel_3_Active == false)) return;
	if ((Active_Menu == 4) && (Channel_4_Active == false)) return;
	//if ((Active_Menu == 26) && (Channel_Math_Active == false)) return;
				
	if ((Active_Menu == 16) && (Cursor_Enabled == false)) return;
	if ((Active_Menu == 19) && (QM_Enabled == false)) return;
	if ((Active_Menu == 20) && (QM_Enabled == false)) return;
	if ((Active_Menu == 21) && (QM_Enabled == false)) return;
	if ((Active_Menu == 22) && (QM_Enabled == false)) return;
			
	MenuButtonCheck(4);
			
	switch(Active_Menu)
	{
		// Display -> Switch grid from dotted to solid	
		case 5 :
		{
			if(dotted_grid)
			dotted_grid = 0;
			else
			dotted_grid = 1;
			
/*
			if (MenuStatus[MENU_TIMEBASE][1] == 1)		//Delayed mode active?
			Display::GRIDDELAYED(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
			else if (MenuStatus[MENU_TIMEBASE][2] == 1)	//XY-mode active?
			Display::GRIDXY(GRID_XY_XOFFS, GRID_YOFFS, Grid_Plane);
			else if (FFT_Mode != FFT_OFF) // FFT mode
			Display::GRIDFFT(GRID_XOFFS_FFT, GRID_YOFFS_FFT, Grid_Plane);	// Draw FFT grid into gridplane
			else	//main
			Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
*/
			Display::RefreshScreen();

			GridColor_Val = GridColorArray[GridColorArrayPos];		//grid intensity
			MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//menu text item
			SetupADC();							//set intensity

			New_Menu = Active_Menu;
			config_changed = true;

			break;
		}	
		

		//Utility -> test signal generator
		case 6 :
		{		
			if(test_signal)
			test_signal = 0;
			else
			test_signal = 1;

			break;
		}

		//  Save / Recall - > Clear Display
		case 8 :
		{		
			if ((Continius == false) || (MenuStatus[MENU_DISPLAY][0] == 241)) ClearPlanes();	
			break;	
		}				

		// USTB-Shiftmode
		case 10 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_TIMEBASE][4] == 0)
			{
				MenuStatus[MENU_TIMEBASE][4] = 1;	//set shift mode to on
				MenuStatus[MENU_TIMEBASE][3] = 0;	//set roll mode to off 
				
				New_Menu = MENU_TIMEBASE;
				Menu_Changed = 1;
				
				MenuItemChanged[3] = 1;
				MenuItemChanged[4] = 1;

				Display::DRAWSTATUS(0, 1);

				if(USTB_Mode != USTB_OFF)
				{
					Display::USTB_Clear_Buffer();
					USTB_Mode = USTB_SHIFT;
				}

				//ClearPlanes();
			}
			//Display::DRAW_ALL_CURSOR();
							
			break;							
		}		

		
		// Trigger Mode  -> Probe
		case 12 :
		{
			EdgeToggle = 1;
			New_Menu = 12;
			Menu_Changed = 1;
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;

			break;
		}	
		
	
		// Pulse Width
		case 15 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			if (MenuStatus[MENU_PULSEWIDTH][2] == 2) break;

			if (MenuStatus[MENU_PULSEWIDTH][2] == 3)
			{					
				if (PulseToggle == 2)
				{					
					buf_int = (int) (Pulse12.Read_Value() * 100000000);	
					
					if (Rotary_Direction_mem_pulse == 1)
					{				
						if ((buf_int >= 1) && (buf_int < 10))
						{
							Pulse12.Write_Value(0.000000104);
			
							Pulse12_Value = 104;
							Pulse12_Steps = 8;
							Pulse12_Expo = 1;
						}
						else if ((buf_int >= 10) && (buf_int < 100))
						{
							Pulse12.Write_Value(0.000001);
			
							Pulse12_Value = 1;
							Pulse12_Steps = 1;
							Pulse12_Expo = 2;
						}
						else if ((buf_int >= 100) && (buf_int < 1000))
						{
							Pulse12.Write_Value(0.00001);
			
							Pulse12_Value = 10;
							Pulse12_Steps = 1;
							Pulse12_Expo = 2;
						}
						else if ((buf_int >= 1000) && (buf_int < 10000))
						{
							Pulse12.Write_Value(0.0001);
			
							Pulse12_Value = 100;
							Pulse12_Steps = 1;
							Pulse12_Expo = 2;
						}
						else if ((buf_int >= 10000) && (buf_int < 100000))
						{
							Pulse12.Write_Value(0.001);
			
							Pulse12_Value = 1;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
						else if ((buf_int >= 100000) && (buf_int < 1000000))
						{
							Pulse12.Write_Value(0.01);
			
							Pulse12_Value = 10;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
						else if ((buf_int >= 1000000) && (buf_int < 10000000))
						{
							Pulse12.Write_Value(0.1);
			
							Pulse12_Value = 100;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
						else
						{
							Pulse12.Write_Value(0.000000016);
			
							Pulse12_Value = 16;
							Pulse12_Steps = 8;
							Pulse12_Expo = 1;
						}
					}
					else	
					{
						if (buf_int == 1)
						{
							Pulse12.Write_Value(0.1);
			
							Pulse12_Value = 100;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
						else if (buf_int == 10)
						{
							Pulse12.Write_Value(0.000000016);
			
							Pulse12_Value = 16;
							Pulse12_Steps = 8;
							Pulse12_Expo = 1;
						}
						else if ((buf_int > 10) && (buf_int <= 100))
						{
							Pulse12.Write_Value(0.000000104);
			
							Pulse12_Value = 104;
							Pulse12_Steps = 8;
							Pulse12_Expo = 1;
						}
						else if ((buf_int > 100) && (buf_int <= 1000))
						{
							Pulse12.Write_Value(0.000001);
			
							Pulse12_Value = 1;
							Pulse12_Steps = 1;
							Pulse12_Expo = 2;
						}
						else if ((buf_int > 1000) && (buf_int <= 10000))
						{
							Pulse12.Write_Value(0.00001);
			
							Pulse12_Value = 10;
							Pulse12_Steps = 1;
							Pulse12_Expo = 2;
						}
						else if ((buf_int > 10000) && (buf_int <= 100000))
						{
							Pulse12.Write_Value(0.0001);
			
							Pulse12_Value = 100;
							Pulse12_Steps = 1;
							Pulse12_Expo = 2;
						}
						else if ((buf_int > 100000) && (buf_int <= 1000000))
						{
							Pulse12.Write_Value(0.001);
			
							Pulse12_Value = 1;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
						else if ((buf_int > 1000000) && (buf_int <= 10000000))
						{
							Pulse12.Write_Value(0.01);
			
							Pulse12_Value = 10;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
						else
						{
							Pulse12.Write_Value(0.1);
			
							Pulse12_Value = 100;
							Pulse12_Steps = 1;
							Pulse12_Expo = 3;
						}
					}

					Pulse12.RenderText();
					trig_range_reg = (unsigned int) (Pulse12.Read_Value() / (float) 0.000000008);
				}
				else PulseToggle = 2;
			}
			else
			{
				if (PulseToggle == 2)
				{					
					buf_int = (int) (Pulse22.Read_Value() * 100000000);	
					
					if (Rotary_Direction_mem_pulse == 1)
					{		
						if ((buf_int >= 1) && (buf_int < 10))
						{
							Pulse22.Write_Value(0.000000104);
			
							Pulse22_Value = 104;
							Pulse22_Steps = 8;
							Pulse22_Expo = 1;
						}
						else if ((buf_int >= 10) && (buf_int < 100))
						{
							Pulse22.Write_Value(0.000001);
			
							Pulse22_Value = 1;
							Pulse22_Steps = 1;
							Pulse22_Expo = 2;
						}
						else if ((buf_int >= 100) && (buf_int < 1000))
						{
							Pulse22.Write_Value(0.00001);
			
							Pulse22_Value = 10;
							Pulse22_Steps = 1;
							Pulse22_Expo = 2;
						}
						else if ((buf_int >= 1000) && (buf_int < 10000))
						{
							Pulse22.Write_Value(0.0001);
			
							Pulse22_Value = 100;
							Pulse22_Steps = 1;
							Pulse22_Expo = 2;
						}
		
						else if ((buf_int >= 10000) && (buf_int < 100000))
						{
							Pulse22.Write_Value(0.001);
			
							Pulse22_Value = 1;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
						else if ((buf_int >= 100000) && (buf_int < 1000000))
						{
							Pulse22.Write_Value(0.01);
			
							Pulse22_Value = 10;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
						else if ((buf_int >= 1000000) && (buf_int < 10000000))
						{
							Pulse22.Write_Value(0.1);
			
							Pulse22_Value = 100;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
						else
						{
							Pulse22.Write_Value(0.000000016);
			
							Pulse22_Value = 16;
							Pulse22_Steps = 8;
							Pulse22_Expo = 1;
						}
					}
					else 	
					{
						if (buf_int == 1)
						{
							Pulse22.Write_Value(0.1);
			
							Pulse22_Value = 100;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
						else if (buf_int == 10)
						{
							Pulse22.Write_Value(0.000000016);
			
							Pulse22_Value = 16;
							Pulse22_Steps = 8;
							Pulse22_Expo = 1;
						}
						else if ((buf_int > 10) && (buf_int <= 100))
						{
							Pulse22.Write_Value(0.000000104);
			
							Pulse22_Value = 104;
							Pulse22_Steps = 8;
							Pulse22_Expo = 1;
						}
						else if ((buf_int > 100) && (buf_int <= 1000))
						{
							Pulse22.Write_Value(0.000001);
			
							Pulse22_Value = 1;
							Pulse22_Steps = 1;
							Pulse22_Expo = 2;
						}
						else if ((buf_int > 1000) && (buf_int <= 10000))
						{
							Pulse22.Write_Value(0.00001);
			
							Pulse22_Value = 10;
							Pulse22_Steps = 1;
							Pulse22_Expo = 2;
						}
						else if ((buf_int > 10000) && (buf_int <= 100000))
						{
							Pulse22.Write_Value(0.0001);
			
							Pulse22_Value = 100;
							Pulse22_Steps = 1;
							Pulse22_Expo = 2;
						}
		
						else if ((buf_int > 100000) && (buf_int <= 1000000))
						{
							Pulse22.Write_Value(0.001);
			
							Pulse22_Value = 1;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
						else if ((buf_int > 1000000) && (buf_int <= 10000000))
						{
							Pulse22.Write_Value(0.01);
			
							Pulse22_Value = 10;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
						else
						{
							Pulse22.Write_Value(0.1);
			
							Pulse22_Value = 100;
							Pulse22_Steps = 1;
							Pulse22_Expo = 3;
						}
					}		
		
					Pulse22.RenderText();
					trig_width_reg = (unsigned int) ((Pulse22.Read_Value() / (float) 0.000000008));
				}
				else PulseToggle = 2;
			}

			
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
		
			New_Menu = 15;
			Menu_Changed = 1;
			TriggerWayChanged = 1;
	
			UpdateTrigger(31);

			Display::StatusUpdate();

			break;	
		}	
	
		// Cursor -> Y2
		case 16 :
		{		
			if (Cursor_Enabled == 0) break;
			{
				if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
	
				if (Cursor_Vertical_Active_Old == 1) MenuItemChanged[1] = 1;
				else if (Cursor_Vertical_Active_Old == 2) MenuItemChanged[2] = 1;					
				else if (Cursor_Vertical_Active_Old == 4) MenuItemChanged[5] = 1;
				else if (Cursor_Horizontal_Active_Old == 1) MenuItemChanged[3] = 1;
				else if (Cursor_Horizontal_Active_Old == 4) MenuItemChanged[5] = 1;

				Cursor_Vertical_Active = 3;
				Cursor_Horizontal_Active = 2;
					
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();

								
				New_Menu = 16;
				Menu_Changed = 1;

				Display::DRAW_ALL_CURSOR();
			}
			break;			
		}
		
		// Quick Print -> Print start XLS
		case 17 :
		{		/*
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			//if (MenuStatus[MENU_QUICKPRINT][2] == 143) MenuStatus[MENU_QUICKPRINT][2] = 144;
			//else MenuStatus[MENU_QUICKPRINT][2] = 143;

			//MenuItemChanged[4] = 1;
							
			New_Menu = 17;
			Menu_Changed = 1;


			if ((USB_Data_Requested == false) && (USB_Data_Trans == false))
			{					
				send_buffer[0] = 150;						// Command Quick Print requested
				send_buffer[1] = 4;                         //
				send_buffer[2] = 0;
						
				SendData(send_buffer);					
			}  */
							
			break;					
		}				
	
		// Quick Measurement -> Settings
		case 19 :
		{		
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if ((MenuStatus[MENU_QUICKMEASUREMENT][1] - 52) == 4)
			{
				New_Menu = 20;
				Menu_Changed = 1;
			}
			if ((MenuStatus[MENU_QUICKMEASUREMENT][1] - 52) == 13)
			{
				New_Menu = 21;
				Menu_Changed = 1;
			}

			break;
		}
		
		// Quick Measurement -> Add Measurement
		case 20 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }				

			QM_Type_Old[0] = QM_Type[0];
			QM_Type_Old[1] = QM_Type[1];
			QM_Type_Old[2] = QM_Type[2];

			if (QM_Type[0] == 0)
			{
				QM_Type[0] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
				QM_Changed[0] = 1;
				QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
			}
			else if (QM_Type[1] == 0)
			{
				if ((QM_Type[0] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[0] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[1] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
					QM_Changed[1] = 1;
					QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				}
			}
			else if (QM_Type[2] == 0)
			{
				if ((QM_Type[1] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[1] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[2] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
					QM_Changed[2] = 1;
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				}
			}
			else
			{
				if ((QM_Type[2] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[2] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[0] = QM_Type[1];
					QM_Type[1] = QM_Type[2];
					QM_Type[2] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
		
					QM_Channel[0] = QM_Channel[1];
					QM_Channel[1] = QM_Channel[2];
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
		
					QM_Changed[0] = 1;
					QM_Changed[1] = 1;
					QM_Changed[2] = 1;
				}
			}

			Quick_Measure_First_Draw = 1;

			New_Menu = 20;
			Menu_Changed = 1;

			//QM_Vertical_Active = 0;
			//QM_Horizontal_Active = 0;
	
			Display::CALCQMDATA();

			break;
		}

		// Quick Measurement -> Add Measurement
		case 21 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
			
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }				

			QM_Type_Old[0] = QM_Type[0];
			QM_Type_Old[1] = QM_Type[1];
			QM_Type_Old[2] = QM_Type[2];

			if (QM_Type[0] == 0)
			{
				QM_Type[0] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
				QM_Changed[0] = 1;
				QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
			}
			else if (QM_Type[1] == 0)
			{
				if ((QM_Type[0] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[0] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[1] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
					QM_Changed[1] = 1;
					QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				}
			}
			else if (QM_Type[2] == 0)
			{
				if ((QM_Type[1] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[1] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[2] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
					QM_Changed[2] = 1;
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
				}
			}
			else
			{
				if ((QM_Type[2] != (MenuStatus[MENU_QUICKMEASUREMENT][1] - 51)) || (QM_Channel[2] != (MenuStatus[MENU_QUICKMEASUREMENT][0] - 26)))
				{
					QM_Type[0] = QM_Type[1];
					QM_Type[1] = QM_Type[2];
					QM_Type[2] = MenuStatus[MENU_QUICKMEASUREMENT][1] - 51;
		
					QM_Channel[0] = QM_Channel[1];
					QM_Channel[1] = QM_Channel[2];
					QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
		
					QM_Changed[0] = 1;
					QM_Changed[1] = 1;
					QM_Changed[2] = 1;
				}
			}

			Quick_Measure_First_Draw = 1;

			New_Menu = 21;
			Menu_Changed = 1;

			//QM_Vertical_Active = 0;
			//QM_Horizontal_Active = 0;
	
			Display::CALCQMDATA();

			break;
		}

		// Quick Measurement Threshold -> Upper
		case 22 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			if (Quick_Measure_Threshold_btn_select == 1) MenuItemChanged[2] = 1;
			else if (Quick_Measure_Threshold_btn_select == 2) MenuItemChanged[3] = 1;

			Quick_Measure_Threshold_btn_select = 3;
			New_Menu = 22;
			Menu_Changed = 1;

			break;
		} 	
	
		// Math  1 + 2
		case 26 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			if (MenuStatus[MENU_MATH][4] == 0)
			{
				// If math menu was active and FFT was active bevore - switch back to old settings
				if (Channel_Math_Active && (Active_Menu == MENU_MATH) && (MenuStatus[MENU_MATH][1] == 1))
				{
					FFT_Mode = FFT_OFF;
/*
					// refresh screen
					if (MenuStatus[MENU_TIMEBASE][1] == 1) 		//delayed mode
					 Display::GRIDDELAYED(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
					else if (MenuStatus[MENU_TIMEBASE][0] == 1) 	//main mode
					 Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);
*/	
					GridColor_Val = GridColorArray[GridColorArrayPos];		//grid intensity
					MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		//menu text item
					SetupADC();							//set intensity
					
					//restore channel setting
					FFT_Restore_Channels();

					// restore zerolevels
					Zero_Levels_Restore();	

					//restore triggermode
					MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;	
					MenuPopupStatus[9][0] = 2;
					MenuPopupStatus[9][1] = 3;
					TriggerLevelChanged = 1;
					TriggerModeChanged = 1;
					UpdateTrigger(4);
					
					Display::RefreshScreen();

				}

				if (MenuStatus[MENU_MATH][1] == 1)
				{
					MenuItemChanged[1] = 1;
					MenuStatus[MENU_MATH][1] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][2] == 1)
				{
					MenuItemChanged[2] = 1;
					MenuStatus[MENU_MATH][2] = 0;
				}
				
				else if (MenuStatus[MENU_MATH][3] == 1)
				{
					MenuItemChanged[3] = 1;
					MenuStatus[MENU_MATH][3] = 0;
				}
														
				MenuStatus[MENU_MATH][4] = 1;

				New_Menu = 26;
				Menu_Changed = 1;
			}
				
			break;
		}	
	
		// FFT Settings - Layout
		case 27 :
		{				
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			if(FFT_Layout)
			FFT_Layout = 0;
			else
			FFT_Layout = 1; 

			Display::RefreshScreen();	
            		config_changed = true;	

			New_Menu = 27;
			Menu_Changed = 1;
			break;
		}
	}
#ifdef _Debug_		
	if (Debug_Mode) printf("Function Button 5\n");		
#endif			

}
// BF insert end
//######################################################################################################################################################
// BF insert
//Function button 6 pressed
void Hardware::F6_Btnhandler(void)					// Button Handler for function button
{

	int ix;

#ifdef _Debug_		
       	printf("F6 Btn start\n");
#endif


	if (MenuPopupActive > 0) ResetTimer();
//	if (ZeroPopupChanged > 0) ResetTimer();
				
	if ((Active_Menu == 1) && (Channel_1_Active == false)) return;
	if ((Active_Menu == 2) && (Channel_2_Active == false)) return;
	if ((Active_Menu == 3) && (Channel_3_Active == false)) return;
	if ((Active_Menu == 4) && (Channel_4_Active == false)) return;
	//if ((Active_Menu == 26) && (Channel_Math_Active == false)) return;
							
	if ((Active_Menu == 16) && (Cursor_Enabled == false)) return;
	if ((Active_Menu == 19) && (QM_Enabled == false)) return;
	if ((Active_Menu == 20) && (QM_Enabled == false)) return;
	if ((Active_Menu == 21) && (QM_Enabled == false)) return;
	if ((Active_Menu == 22) && (QM_Enabled == false)) return;

	MenuButtonCheck(5);
			
	switch(Active_Menu)
	{	

		//Display -> Switch drawing from pixel connect to line drawing
		case 5 :
		{		

			if(draw_mode)
			{
				draw_mode = 0;	//pixel connecting
	
				Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 0);
				Display::TEXTOUTxvbig("     Fast drawing with", 247, 200, 1, UI_Plane2);
				Display::TEXTOUTxvbig("vertical pixel connection.", 247, 220, 1, UI_Plane2);
				//Display::TEXTOUTxvbig("connection.", 247, 232, 1, UI_Plane2);
				
				nr_delay(800);

				//Delete popup
				Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 1);
				Display::TEXTOUTxvbig("     Fast drawing with", 247, 200, 0, UI_Plane2);
				Display::TEXTOUTxvbig("vertical pixel connection.", 247, 220, 0, UI_Plane2);
				//Display::TEXTOUTxvbig("connection.", 247, 232, 0, UI_Plane2);


			}
			else
			{
				draw_mode = 1;	//line() drawing

				Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 0);
				Display::TEXTOUTxvbig("Accurate drawing with", 247, 200, 1, UI_Plane2);
				Display::TEXTOUTxvbig("    Line() function.", 247, 220, 1, UI_Plane2);
				//Display::TEXTOUTxvbig("connection.", 247, 232, 1, UI_Plane2);
				
				nr_delay(800);

				//Delete popup
				Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 1);
				Display::TEXTOUTxvbig("Accurate drawing with", 247, 200, 0, UI_Plane2);
				Display::TEXTOUTxvbig("    Line() function.", 247, 220, 0, UI_Plane2);
				//Display::TEXTOUTxvbig("connection.", 247, 232, 0, UI_Plane2);

			}
			config_changed = true;
			break;
		}

/* BF transferred to display menu above
		//Utility -> Switch drawing from pixel connect to line drawing
		case 6 :
		{		
			if(draw_mode)
			draw_mode = 0;	//pixel connecting
			else
			draw_mode = 1;	//line() drawing
			
			config_changed = true;
			break;
		}
*/
		//Timebase menu -> browse   BF transferred from display menu
		case 10 :
		{	
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }

			if (MenuStatus[MENU_TIMEBASE][5] == 241)
			MenuStatus[MENU_TIMEBASE][5] = 240;
			else
			MenuStatus[MENU_TIMEBASE][5] = 241;

			if (FFT_Mode == FFT_OFF)
			{
				if (MenuStatus[MENU_TIMEBASE][5] == 241)
				Display::DRAWMEMORY(0, 1, 1);
				else
				{
					Display::DRAWMEMORY(1, 0, 0);			
					Display::DRAW_ALL_CURSOR();
				}
			}
			New_Menu = MENU_TIMEBASE;
			Menu_Changed = 1;				

			break;

		}



		// Cursor -> X1X2/Y1Y2
		case 16 :
		{		
			if (Cursor_Enabled == 0) break;
			
			{
				if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
	
				if (Cursor_Vertical_Active_Old == 1) MenuItemChanged[1] = 1;
				else if (Cursor_Vertical_Active_Old == 2) MenuItemChanged[2] = 1;
				else if (Cursor_Horizontal_Active_Old == 1) MenuItemChanged[3] = 1;
				else if (Cursor_Horizontal_Active_Old == 2) MenuItemChanged[4] = 1;
	
				Cursor_Both_Selected_Old = Cursor_Both_Selected;

				if ((Cursor_Vertical_Active == 4) || (Cursor_Horizontal_Active == 4))
				{
					if (Cursor_Both_Selected == 0)
					{
						Cursor_Both_Selected = 1;
						Cursor_Vertical_Active = 3;
						Cursor_Horizontal_Active = 4;
					}
					else
					{
						Cursor_Both_Selected = 0;
						Cursor_Vertical_Active = 4;
						Cursor_Horizontal_Active = 3;
					}
				}
				else
				{
					if (Cursor_Both_Selected == 0)
					{
						Cursor_Vertical_Active = 4;
						Cursor_Horizontal_Active = 3;
					}
					else
					{
						Cursor_Vertical_Active = 3;
						Cursor_Horizontal_Active = 4;
					}
				}
					
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();

								
				New_Menu = 16;
				Menu_Changed = 1;

				Display::DRAW_ALL_CURSOR();
			}
			break;	
		}	
						
		// Quick Measurement -> Thresholds
		case 19 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
			
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }	
			
			New_Menu = 22;
			Menu_Changed = 1;
			break;		
		}				
			
		// Quick Measurement Delay Settings
		case 20 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
			
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }	
			
			New_Menu = 19;
			Menu_Changed = 1;
			break;		
		}
		
		// Quick Measurement Phase Settings
		case 21 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }	
			
			New_Menu = 19;
			Menu_Changed = 1;
			break;		
		}				
		
		// Quick Measurement Thresholds
		case 22 :
		{		
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;
		
			if (QM_Enabled == 0) break;
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu = 19;
			Menu_Changed = 1;
			break;
		}	
	
		// FFT settings
		case 27 :
		{	
			//if (MenuStatus[MENU_TIMEBASE][2] == 1) break;

			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu = 26;
			Menu_Changed = 1;
			break;	
		}		

		// More FFT settings
		case 28 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu = 27;
			Menu_Changed = 1;
			break;		
		}	
					
		// Math settings
		case 29 :
		{		
			if (MenuPopupActive > -1) { Display::DRAWMENUPOPDOWN(); }
			
			New_Menu = 26;
			Menu_Changed = 1;
			break;		
		}		
				
		// TMW changed; added Setup Default Button in Edge Menu
		// Edge -> Default Setup
		case 14 :
		{
			Set_Vars_Default();
			// BF insert - Recalc vars			
			Recalc_Vars();
			// BF insert - init display
			Display::RefreshScreen();

			UpdateChannel(1, 1);
			UpdateChannel(2, 1);
			
			VoltageChangedCh1 = 1;
			VoltageChangedCh2 = 1;				
			
			LED_ON[0] = 1;
			LED_ON[1] = 1; 				
			LED_ON[5] = 1;
			LED_ON[6] = 0;
	
			Rotary_Steps = 0;
			ON_Zero_Channel_1();
			Rotary_Steps = 0;
			ON_Zero_Channel_2();
	
			SetSwitches(1, Selected_Voltage_CH1);
			SetSwitches(2, Selected_Voltage_CH2);

			if (NumberOfChannels > 2)
			{
				UpdateChannel(3, 1);
				UpdateChannel(4, 1);
	
				VoltageChangedCh3 = 1;
				VoltageChangedCh4 = 1;
			
				LED_ON[2] = 1;
				LED_ON[3] = 1;
			
				Rotary_Steps = 0;
				ON_Zero_Channel_3();
				Rotary_Steps = 0;
				ON_Zero_Channel_4();
	
				SetSwitches(3, Selected_Voltage_CH3);
				SetSwitches(4, Selected_Voltage_CH4);
	
			}
			else
			{
				UpdateChannel(3, 0);
				UpdateChannel(4, 0);
			} 	

			TriggerLevelChanged = 1;
			TriggerModeChanged = 1;	
			TriggerWayChanged = 1;
			TimebaseChanged = 1;
			TimeOffsetChanged = 1;
			MenuStatusChanged = 1;
			MenuAktive = 1;

			Cursor_Data_First_Draw = 0;
			Quick_Measure_First_Draw = 0;   				    	

			// remove the cursor data
			for (ix = 408 * 20; ix < 430 * 20; ix++)
			{
				*(UI_Plane1 + ix) = 0;	// delete
				*(Buffer_UI2Plane + ix) = 0;	// delete Text	
				*(UI_Plane4 + ix) = 0;	// delete
				*(UI_Plane5 + ix) = 0;	// delete
			}				

			UpdateTrigger(12);
			Display::CALCPRETRIGGER();
			Display::DRAW_ALL_CURSOR();

			Display::DRAWSQUAREBUTTON(2, 1, 14, 16, btnPushed, btnDraw);					// Button
			Display::TEXTOUTvbig("1", 6, 4, 1, Channel_Plane1);						// Draw Voltage Text
	//                    Display::TEXTOUTvbig("1", 6, 4, 1, Buffer_Plane1);					// Draw Voltage Text

			Display::DRAWSQUAREBUTTON(78, 1, 14, 16, btnPushed, btnDraw);					// Button
			Display::TEXTOUTvbig("2", 82, 4, 1, Channel_Plane2);						// Draw Voltage Text
	//                    Display::TEXTOUTvbig("2", 82, 4, 1, Buffer_Plane2);					// Draw Voltage Text

			Display::StatusUpdate();

			if (NumberOfChannels > 2)
			{
				Display::DRAWSQUAREBUTTON(154, 1, 14, 16, btnPushed, btnDraw);				// Button
				Display::TEXTOUTvbig("3", 158, 4, 1, Channel_Plane3);					// Draw Voltage Text
	//                        Display::TEXTOUTvbig("3", 158, 4, 1, Buffer_Plane3);					// Draw Voltage Text
	
				Display::DRAWSQUAREBUTTON(230, 1, 14, 16, btnPushed, btnDraw);				// Button		
				Display::TEXTOUTvbig("4", 234, 4, 1, Channel_Plane4);					// Draw Voltage Text
	//                        Display::TEXTOUTvbig("4", 234, 4, 1, Buffer_Plane4);					// Draw Voltage Text
			}
				
			Display::DRAWSTATUS(6, 0);
		
			Send_LED();
			config_changed = true;  	// TMW changed (added save paramter on default)
			//BF del AMDFlash::Write_Config_Flash();	// TMW changed (added save paramter on default)

			break;
		} // TMW change ends
	}			
#ifdef _Debug_		
	if (Debug_Mode) printf("Function Button 6\n");
#endif			


}
// BF insert end
//######################################################################################################################################################

char Hardware::MenuButtonCheck(char BtnNr)
{
	char ct, found = 0;
	
	for (ct = 0; ct < 6; ct++)
	{
		if (MenuItemPushed[ct] == 1) { found = 1; MenuItemPushed[ct] = 0; MenuItemPushed_old[ct] = 1; MenuItemChanged[ct] = 1;}
	}
	
	if (found) ResetTimer();

	if (BtnNr > -1)
	{
		MenuItemChanged[BtnNr] = 1;
		MenuItemPushed[BtnNr] = 1;	
	}
	return found;
}

void Hardware::MenuPopupStep(int MenuPopupNr, short *MenuStatusNr, short *MenuStatusNr2, short *MenuStatusNr3, int DrawMenuNr, int start, char dir)
{
	int x, pos = 0;
	int newpos = 0;
	
	unsigned short count = 0;
	
	count = MenuPopupDef[MenuPopupActive][1];
	
	for (x = 0; x < count; x++)
	{
		if (MenuPopupStatus[MenuPopupNr][x] == 3) pos = x;
	}
	
	
	if (dir == 2)
	{
		newpos = -1;
		for (x = pos; x < count; x++)
		{
			if (MenuPopupStatus[MenuPopupNr][x] == 2)
			{
				newpos = x;
				break;
			}
		}	
		
		if (newpos == -1)
		{
			for (x = 0; x < pos; x++)
			{
				if (MenuPopupStatus[MenuPopupNr][x] == 2)
				{
					newpos = x;
					break;
				}
			}
		}
	}
	else
	{
		newpos = -1;
		for (x = pos; x >= 0; x--)
		{
	//            printf("DoStep (%d) down to %d = %d\n", MenuPopupNr, x, MenuPopupStatus[MenuPopupNr][x]);
			if (MenuPopupStatus[MenuPopupNr][x] == 2)
			{
				newpos = x;
				break;
			}
		}	
		
		if (newpos == -1)
		{
	//            printf("Nothing found\n");
			for (x = count; x > pos; x--)
			{
				if (MenuPopupStatus[MenuPopupNr][x] == 2)
				{
				newpos = x;
				break;
				}
			}
		}
    	}    	
    
//    printf("Pos : %2d NewPos : %2d dir : %2d\n", pos, newpos, dir);
	
    if (newpos == -1) return;	
	
	MenuPopupStatus[MenuPopupNr][pos] = 2;
	MenuPopupStatus[MenuPopupNr][newpos] = 3;
	
	MenuStatusNr[0] = start + newpos;
    if (MenuStatusNr2[0] > -1) { MenuStatusNr2[0] = start + newpos; }
    if (MenuStatusNr3[0] > -1) { MenuStatusNr3[0] = start + newpos; }	
}		

void Hardware::UpdateChannel(int channel, char active)
{
	char *iipos = 0;
	char *iiipos = 0;	
	int x= 0;
	int pos = 0;
	int bufchannel = channel;
	char lednr = 0;
	
	switch(channel)
	{
		case 1:
		{
			iipos = &Channel_1_Active;
			iiipos = &Channel_1_Active_Old;
			lednr = 0;
			break;
		}	
		case 2:
		{
			iipos = &Channel_2_Active;
			iiipos = &Channel_2_Active_Old;
			lednr = 1;
			break;
		}
		case 3:
		{
			iipos = &Channel_3_Active;
			iiipos = &Channel_3_Active_Old;
			lednr = 2;
			break;
		}
		case 4:
		{
			iipos = &Channel_4_Active;
			iiipos = &Channel_4_Active_Old;
			lednr = 3;
			break;
		}
		case 5:
		{
			iipos = &Channel_Math_Active;
			iiipos = &Channel_Math_Active_Old;
			lednr = 4;
			
			if (NumberOfChannels == 2) bufchannel = 3;
			break;
		}		
	}
						
	if (active == 1)
	{
		*iiipos = *iipos;
		*iipos = 1;
/*		
		// FFT Source
		if (MenuPopupStatus[29][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_FFT][0] == 91)
			{
				MenuPopupStatus[29][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_FFT][0] = 138 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[29][0 + (bufchannel - 1)] = 2;			
		} 		
*/		
		// Edge Source
		if (MenuPopupStatus[28][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_TRIGGEREDGE][1] == 91)
			{
				MenuPopupStatus[28][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_TRIGGEREDGE][1] = 138 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[28][0 + (bufchannel - 1)] = 2;			
		} 		
		
		// Cursor Source
		if (MenuPopupStatus[1][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_CURSOR][0] == 91)
			{
				MenuPopupStatus[1][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_CURSOR][0] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[1][0 + (bufchannel - 1)] = 2;			
		}
		
		// Quick Measurement Source
		if (MenuPopupStatus[3][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_QUICKMEASUREMENT][0] == 91)
			{
				MenuPopupStatus[3][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_QUICKMEASUREMENT][0] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[3][0 + (bufchannel - 1)] = 2;			
		}		
		
		// Quick Measurement Delay Settings Source1
		if (MenuPopupStatus[5][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_QMDELAY][0] == 91)
			{
				MenuPopupStatus[5][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_QMDELAY][0] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[5][0 + (bufchannel - 1)] = 2;			
		}	
		
		// Quick Measurement Delay Settings Source2
		if (MenuPopupStatus[6][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_QMDELAY][2] == 91)
			{
				MenuPopupStatus[6][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_QMDELAY][2] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[6][0 + (bufchannel - 1)] = 2;			
		}	
		
		// Quick Measurement Phase Settings Source1
		if (MenuPopupStatus[24][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[21][0] == 91)
			{
				MenuPopupStatus[24][0 + (bufchannel - 1)] = 3;
				MenuStatus[21][0] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[24][0 + (bufchannel - 1)] = 2;			
		}	
		
		// Quick Measurement Phase Settings Source2
		if (MenuPopupStatus[25][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[21][2] == 91)
			{
				MenuPopupStatus[25][0 + (bufchannel - 1)] = 3;
				MenuStatus[21][2] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[25][0 + (bufchannel - 1)] = 2;			
		}		
		
		// Quick Measurement Thresholds Source
		if (MenuPopupStatus[26][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_QMTHRESHOLDS][0] == 91)
			{
				MenuPopupStatus[26][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_QMTHRESHOLDS][0] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[26][0 + (bufchannel - 1)] = 2;			
		}			
		
		// Pulse Width Source
		if (MenuPopupStatus[7][0 + (bufchannel - 1)] == 1)
		{
			if (MenuStatus[MENU_PULSEWIDTH][0] == 91)
			{
				MenuPopupStatus[7][0 + (bufchannel - 1)] = 3;
				MenuStatus[MENU_PULSEWIDTH][0] = 27 + (bufchannel - 1);		
			}			
			else MenuPopupStatus[7][0 + (bufchannel - 1)] = 2;			
		}
		Set_LED(lednr);
	}
	else
	{
		*iiipos = *iipos;
		*iipos = 0;      		
		
		if ((Channel_Math_Active) && ((bufchannel == 1) || (bufchannel == 2)) && (MenuStatus[MENU_MATH][1] == 0))
		{
			Channel_Math_Active = 0;
			RemovePlane |= 0x10;
			ClearPlanes();	
			Reset_LED(4);		
		}
/*BF test del		
		// Switch from XY to Main if channels are not active
		if ((XY_Mode == 1) && ((bufchannel == 1) || (bufchannel == 2)))
		{
		    	MenuStatus[MENU_TIMEBASE][0] = 1;
			MenuStatus[MENU_TIMEBASE][2] = 246;
			XY_Mode = 0;	//Main

			// Draw main grid into gridplane
			Display::GRID(GRID_XOFFS, GRID_YOFFS, Grid_Plane);

			GridColor_Val = GridColorArray[GridColorArrayPos];
			SetupADC();
							
			MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;		
		}
*/
/*		
		// FFT Source
		if (MenuPopupStatus[29][0 + (bufchannel - 1)] == 3)
		{	
			MenuPopupStatus[29][0 + (bufchannel - 1)] = 1;
				
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[29][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[29][pos] = 3;
				MenuStatus[MENU_FFT][0] = 138 + pos;
			}
			else
			{
				MenuStatus[MENU_FFT][0] = 91;						//None
			}
		}
		else MenuPopupStatus[29][0 + (bufchannel - 1)] = 1;		
*/		
		// Edge Source
		if (MenuPopupStatus[28][0 + (bufchannel - 1)] == 3)
		{	
			MenuPopupStatus[28][0 + (bufchannel - 1)] = 1;
				
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[28][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[28][pos] = 3;
				MenuStatus[MENU_TRIGGEREDGE][1] = 138 + pos;
			}
			else
			{
				MenuStatus[MENU_TRIGGEREDGE][1] = 91;						//None
			}
		}
		else MenuPopupStatus[28][0 + (bufchannel - 1)] = 1;

		Selected_Trigger_Source	= MenuStatus[MENU_TRIGGEREDGE][1] - 137;
		TriggerWayChanged = true;	
		TriggerLevelChanged = 1;
	
		Display::StatusUpdate();
		UpdateTrigger(45);
			
		// Cursor Source
		if (MenuPopupStatus[1][0 + (bufchannel - 1)] == 3)
		{	
			MenuPopupStatus[1][0 + (bufchannel - 1)] = 1;
				
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[1][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[1][pos] = 3;
				MenuStatus[MENU_CURSOR][0] = 27 + pos;
			}
			else
			{
				MenuStatus[MENU_CURSOR][0] = 91;						//None
			}
		}
		else MenuPopupStatus[1][0 + (bufchannel - 1)] = 1;
		
		// Quick Measurement Source
		if (MenuPopupStatus[3][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[3][0 + (bufchannel - 1)] = 1;
			
			pos = -1;
			for (x = 0;x < 4;x++)
			{
				if (MenuPopupStatus[3][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[3][pos] = 3;
				MenuStatus[MENU_QUICKMEASUREMENT][0] = 27 + pos;
			}
			else
			{
				MenuStatus[MENU_QUICKMEASUREMENT][0] = 91;						//None
			}
		}
		else MenuPopupStatus[3][0 + (bufchannel - 1)] = 1;
		
		// Quick Measurement Delay Settings Source1
		if (MenuPopupStatus[5][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[5][0 + (bufchannel - 1)] = 1;
			
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[5][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[5][pos] = 3;
				MenuStatus[MENU_QMDELAY][0] = 27 + pos;
			}
			else
			{
				MenuStatus[MENU_QMDELAY][0] = 91;						//None
			}
		}
		else MenuPopupStatus[5][0 + (bufchannel - 1)] = 1;
		
		// Quick Measurement Delay Settings Source2
		if (MenuPopupStatus[6][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[6][0 + (bufchannel - 1)] = 1;
			
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[6][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[6][pos] = 3;
				MenuStatus[MENU_QMDELAY][2] = 27 + pos;
			}
			else
			{
				MenuStatus[MENU_QMDELAY][2] = 91;						//None
			}
		}
		else MenuPopupStatus[6][0 + (bufchannel - 1)] = 1;
		
        	// Quick Measurement Phase Settings Source1
		if (MenuPopupStatus[24][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[24][0 + (bufchannel - 1)] = 1;
			
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[24][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[24][pos] = 3;
				MenuStatus[21][0] = 27 + pos;
			}
			else
			{
				MenuStatus[21][0] = 91;						//None
			}
		}
		else MenuPopupStatus[24][0 + (bufchannel - 1)] = 1;
		
		// Quick Measurement Phase Settings Source2
		if (MenuPopupStatus[25][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[25][0 + (bufchannel - 1)] = 1;
			
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[25][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[25][pos] = 3;
				MenuStatus[21][2] = 27 + pos;
			}
			else
			{
				MenuStatus[21][2] = 91;						//None
			}
		}
		else MenuPopupStatus[25][0 + (bufchannel - 1)] = 1;		
		
        	// Quick Measurement Thresholds Source
		if (MenuPopupStatus[26][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[26][0 + (bufchannel - 1)] = 1;
			
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[26][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[26][pos] = 3;
				MenuStatus[MENU_QMTHRESHOLDS][0] = 27 + pos;
			}
			else
			{
				MenuStatus[MENU_QMTHRESHOLDS][0] = 91;						//None
			}
		}
		else MenuPopupStatus[26][0 + (bufchannel - 1)] = 1;
		
		// Pulse Width Source
		if (MenuPopupStatus[7][0 + (bufchannel - 1)] == 3)
		{		
			MenuPopupStatus[7][0 + (bufchannel - 1)] = 1;		
		
			pos = -1;
			for (x = 0;x < 5;x++)
			{
				if (MenuPopupStatus[7][x] == 2)
				{
					pos = x;
					break;	
				}
			}
			if (pos > -1)
			{
				MenuPopupStatus[7][pos] = 3;
				MenuStatus[MENU_PULSEWIDTH][0] = 27 + pos;
			}
			else
			{
				MenuStatus[MENU_PULSEWIDTH][0] = 91;						//None
			}
		}	
		else MenuPopupStatus[7][0 + (bufchannel - 1)] = 1;
		
		Reset_LED(lednr);
	}	
	
	MenuPopupStatus[28][0] = 2;
	MenuPopupStatus[28][1] = 2;
	
	if (NumberOfChannels > 2)
	{
        MenuPopupStatus[28][2] = 2;
        MenuPopupStatus[28][3] = 2;
    }
	
	if (MenuStatus[MENU_TRIGGEREDGE][1] == 138) MenuPopupStatus[28][0] = 3;
	else if (MenuStatus[MENU_TRIGGEREDGE][1] == 139) MenuPopupStatus[28][1] = 3;
	else if (MenuStatus[MENU_TRIGGEREDGE][1] == 140) MenuPopupStatus[28][2] = 3;
	else if (MenuStatus[MENU_TRIGGEREDGE][1] == 141) MenuPopupStatus[28][3] = 3;
	
    if (Cursor_Enabled)
    {
        CursorChanged = 3;
        Cursor_Data_First_Draw = 1;
	
	if(FFT_Mode != FFT_OFF)
	Display::FFT_CalcCursorData();
	else
	Display::CALCCURSORDATA();

        Display::DRAWCURSORDATA(0);
    }

    // Check Measurements

    QM_Type_Old[0] = QM_Type[0];
    QM_Type_Old[1] = QM_Type[1];
    QM_Type_Old[2] = QM_Type[2];

    pos = -1;
    for (x = 0; x < 3; x++)
    {
        if (QM_Type[x] > 0)
        {
            if ((QM_Channel[x] == 1) && (Channel_1_Active == 0)) { QM_Type[x] = 0; pos = 1; }
            if ((QM_Channel[x] == 2) && (Channel_2_Active == 0)) { QM_Type[x] = 0; pos = 1; }
            if ((QM_Channel[x] == 3) && (Channel_3_Active == 0)) { QM_Type[x] = 0; pos = 1; }
            if ((QM_Channel[x] == 4) && (Channel_4_Active == 0)) { QM_Type[x] = 0; pos = 1; }
            if ((QM_Channel[x] == 5) && (Channel_Math_Active == 0)) { QM_Type[x] = 0; pos = 1; }
        }
    }

    if (pos == 1)
    {
        QM_Channel[0] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
        QM_Channel[1] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;
        QM_Channel[2] = MenuStatus[MENU_QUICKMEASUREMENT][0] - 26;

        QM_Changed[0] = 0;
        QM_Changed[1] = 0;
        QM_Changed[2] = 0;

        Quick_Measure_First_Draw = 1;

        New_Menu = 19;
        Menu_Changed = 1;
    }

    printf("********  Update channel %d done  ***********\r\n", bufchannel);
}
//#####################################################################################################################################################
//BF 
void Hardware::UpdateTrigger(char nr)
{
    	int trg_buf, p_mul_value;
	int lVirtual_Zero; 
    //if (AutoTimerOff) return;

	Selected_Trigger_Source_Old = Selected_Trigger_Source;
	
	adc_ctrl_reg &= 0xFFF0;
    //ctrl_reg &= 0xC17F;  // remove holdoff and pulse bits
    	ctrl_reg &= 0xC17D;  // remove holdoff and pulse bits and internal bit
    	
	if (HoldOff_Value)
	{
		trig_holdoff_reg = (unsigned long) (HoldOff.Read_Value() / (float) 0.000000008);
		ctrl_reg |= 0x2000;
	}
	else trig_holdoff_reg = 0x00000000;
                    	
  //  if (TriggerWay == 1)
    	{
		if (MenuStatus[MENU_TRIGGEREDGE][1] == 138)	//Source = channel 1
		{
			triggering = 1;
			ctrl_reg |= 0x0002;
			adc_ctrl_reg |= 0x0001;
				
			trg_val_CHI_reg = (int)((float)(Trigger_Pos_CH1 - (GRID_HEIGHT/2)) / scale_factor[Selected_Voltage_CH1]) + ADC_ZERO;	//Stefan

			trg_val_CHI_reg	= 255 - trg_val_CHI_reg;
				
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2)	//rising
			{ 	
				ctrl_reg |= 0x0004;
				if (Trigger_Pos_CH1 > ZeroLevelCH1)	//BF correction
				trg_val_CHI_reg += 10;			//BF correction
			}
			else if (MenuStatus[MENU_TRIGGEREDGE][0] == 3)	//falling
			{ 	
				ctrl_reg &= 0xFFFB;
				if (Trigger_Pos_CH1 < ZeroLevelCH1)	//BF correction
				trg_val_CHI_reg -= 15;			//BF correction
				else
				trg_val_CHI_reg -= 5;			//BF correction
			}
		}
		else if (MenuStatus[MENU_TRIGGEREDGE][1] == 139)	//Source = channel 2
		{
			triggering = 2;
			ctrl_reg |= 0x0002;
			adc_ctrl_reg |= 0x0002;
						
			trg_val_CHII_reg = (int)((float)(Trigger_Pos_CH2 - (GRID_HEIGHT/2)) / scale_factor[Selected_Voltage_CH2])+ADC_ZERO;	//Stefan
		
			trg_val_CHII_reg = 255 - trg_val_CHII_reg;
						
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2)	//rising
			{ 
				ctrl_reg |= 0x0004;
				if (Trigger_Pos_CH2 > ZeroLevelCH2)	//BF correction
				trg_val_CHII_reg += 10;			//BF correction
 			}
			else if (MenuStatus[MENU_TRIGGEREDGE][0] == 3)	//falling
			{ 
				ctrl_reg &= 0xFFFB;
				if (Trigger_Pos_CH2 < ZeroLevelCH2)	//BF correction
				trg_val_CHII_reg -= 15;			//BF correction
				else
				trg_val_CHII_reg -= 5;			//BF correction
			 }
		}
		else if (MenuStatus[MENU_TRIGGEREDGE][1] == 140)	//Source = channel 3
		{
			triggering = 3;
			ctrl_reg |= 0x0002;
			adc_ctrl_reg |= 0x0004;
					
			trg_val_CHIII_reg = (int)((float)(Trigger_Pos_CH3 - (GRID_HEIGHT/2)) / scale_factor[Selected_Voltage_CH3])+ADC_ZERO;	//Stefan

			trg_val_CHIII_reg = 255 - trg_val_CHIII_reg;
						
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2)	//rising
			{ 
				ctrl_reg |= 0x0004;
				if (Trigger_Pos_CH3 > ZeroLevelCH3)	//BF correction
				trg_val_CHIII_reg += 10;		//BF correction
			}
			else if (MenuStatus[MENU_TRIGGEREDGE][0] == 3)	//falling
			{ 
				ctrl_reg &= 0xFFFB;
				if (Trigger_Pos_CH3 < ZeroLevelCH3)	//BF correction
				trg_val_CHIII_reg -= 15;		//BF correction
				else
				trg_val_CHIII_reg -= 5;			//BF correction
			}
		}
		else if (MenuStatus[MENU_TRIGGEREDGE][1] == 141)	//Source = channel 4
		{
			triggering = 4;
			ctrl_reg |= 0x0002;
			adc_ctrl_reg |= 0x0008;
					
			trg_val_CHIV_reg = (int)((float)(Trigger_Pos_CH4 - (GRID_HEIGHT/2)) / scale_factor[Selected_Voltage_CH4])+ADC_ZERO;	//Stefan
		
			trg_val_CHIV_reg = 255 - trg_val_CHIV_reg;
						
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2)	//rising
			{
			 	ctrl_reg |= 0x0004;
				if (Trigger_Pos_CH4 > ZeroLevelCH4)	//BF correction
				trg_val_CHIV_reg += 10;			//BF correction
 			}
			else if (MenuStatus[MENU_TRIGGEREDGE][0] == 3)	//falling
			{
				ctrl_reg &= 0xFFFB; 
				if (Trigger_Pos_CH4 < ZeroLevelCH4)	//BF correction
				trg_val_CHIV_reg -= 15;			//BF correction
				else
				trg_val_CHIV_reg -= 5;			//BF correction
			}
		}

		if (MenuStatus[MENU_TRIGGEREDGE][2] == 1)	//Source = extern
		{
			triggering = 5;
						
			ctrl_reg &= 0xFFFD;
			adc_ctrl_reg &= 0xFFF0;
		
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2) ctrl_reg |= 0x0004;
			else if (MenuStatus[MENU_TRIGGEREDGE][0] == 3) ctrl_reg &= 0xFFFB;
		
			SwitchesTB = 0x00;
			
			if (MenuPopupStatus[8][0] == 3) SwitchesTB = 0x40;
			else if (MenuPopupStatus[8][1] == 3) SwitchesTB = 0xC0;
			else if (MenuPopupStatus[8][2] == 3) SwitchesTB = 0x80;
		
			if (MenuStatus[MENU_TRIGGERMODE][1] == 95) SwitchesTB |= 0x04;
			else SwitchesTB &= 0xFB;
										
			SetSwitches(5, SwitchesTB);
#ifdef _Debug_
	printf("TE %d\n", Trigger_Pos_CHE);
#endif
			ext_trg_val_reg = Extern_Trigger_Values[Trigger_Pos_CHE];
			
			printf("extern level %d \n", ext_trg_val_reg);
		
			serdata->np_piodata = ext_trg_val_reg;
			serstartpwm->np_piodata = 1;
			serstartpwm->np_piodata = 0;
		}
        
		if (MenuStatus[MENU_TRIGGEREDGE][3] == 1)			//TV Ch1
		{
			triggering = 5;
						
			ctrl_reg &= 0xFFFD;
			adc_ctrl_reg &= 0xFFF0;
		
			if (MenuStatus[MENU_TRIGGEREDGE][0] == 2) ctrl_reg |= 0x0004;		//rising/falling
			else if (MenuStatus[MENU_TRIGGEREDGE][0] == 3) ctrl_reg &= 0xFFFB;	//rising/falling
		
			SwitchesTB = 0x00;
			
			if (MenuPopupStatus[11][0] == 3) SwitchesTB = 0x01;		//BF unused menu
			else if (MenuPopupStatus[11][1] == 3) SwitchesTB = 0x02;	//BF unused menu
		
			if (MenuStatus[MENU_TRIGGERMODE][1] == 95) SwitchesTB |= 0x04;		//coupling
			else SwitchesTB &= 0xFB;
										
			SetSwitches(5, SwitchesTB);
		#ifdef _Debug_
			printf("TE %d\n", Trigger_Pos_CHE);
		#endif
			ext_trg_val_reg = Extern_Trigger_Values[Trigger_Pos_CHE];
		
			serdata->np_piodata = ext_trg_val_reg;
			serstartpwm->np_piodata = 1;
			serstartpwm->np_piodata = 0;
		}
    	}

	if (TriggerWay == 2)
	{
		if (MenuStatus[MENU_PULSEWIDTH][2] == 1) ctrl_reg |= 0x1200;
		else if (MenuStatus[MENU_PULSEWIDTH][2] == 2) ctrl_reg |= 0x1400;
		else if (MenuStatus[MENU_PULSEWIDTH][2] == 3) ctrl_reg |= 0x1800;
	}

    	// Autotrigger
	if ((MenuStatus[MENU_TRIGGERMODE][0] == 93) && (TriggerWay == 1)) ctrl_reg |= 0x0040;
	else ctrl_reg &= 0xFFBF;
		
	Selected_Trigger_Source = triggering;
			
	MenuPopupStatus[28][0] = 2;
	MenuPopupStatus[28][1] = 2;
	
	if (NumberOfChannels > 2)
	{
		MenuPopupStatus[28][2] = 2;
		MenuPopupStatus[28][3] = 2;
    	}
	
	if (MenuStatus[MENU_TRIGGEREDGE][1] == 138) MenuPopupStatus[28][0] = 3;
	else if (MenuStatus[MENU_TRIGGEREDGE][1] == 139) MenuPopupStatus[28][1] = 3;
	else if (MenuStatus[MENU_TRIGGEREDGE][1] == 140) MenuPopupStatus[28][2] = 3;
	else if (MenuStatus[MENU_TRIGGEREDGE][1] == 141) MenuPopupStatus[28][3] = 3;			

        	
#ifdef _Debug_	
	if (Debug_Mode) printf("Trigger Updated Nr : %d MS12 %i MS14 %i actrl %x ctrl %x trv1 %x trv2 %x\n", nr, MenuStatus[MENU_TRIGGERMODE][0], MenuStatus[MENU_TRIGGEREDGE][1], adc_ctrl_reg, ctrl_reg, trg_val_CHI_reg, trg_val_CHII_reg);
#endif	
	SetupADC();
}

void Hardware::Set_LED(int LED)
{
	LED_ON[LED] = 1;
	Send_LED();
}

void Hardware::Reset_LED(int LED)
{
	LED_ON[LED] = 0;
	Send_LED();
}

void Hardware::Clear_LED(void)
{
	int ct;
	
	for (ct = 0; ct < 13;ct++) LED_ON[ct] = 0;
}

void Hardware::Send_LED(void)
{
	int led_value = 0xFFFF;
	
	if (LED_ON[0] == 1) led_value = led_value & 0xBFFF;			// Select Channel 1
	if (LED_ON[1] == 1) led_value = led_value & 0xEFFF;			// Select Channel 2
	
	//if (NumberOfChannels > 2)
	//{
	   if (LED_ON[2] == 1) led_value = led_value & 0xFEFF;			// Select Channel 3
	   if (LED_ON[3] == 1) led_value = led_value & 0x7FFF;			// Select Channel 4
    	//}
	if (LED_ON[4] == 1) led_value = led_value & 0xDFFF;		// Select Channel Math
	if (LED_ON[5] == 1) led_value = led_value & 0xFDFF;		// General
	if (LED_ON[6] == 1) led_value = led_value & 0xFBFF;		// Cursor						
	if (LED_ON[7] == 1) led_value = led_value & 0xF7FF;		// Quick Measure
	if (LED_ON[8] == 1) led_value = led_value & 0xFFBF;		// Edge
	if (LED_ON[9] == 1) led_value = led_value & 0xFFFD;		// Pattern - Not Used
	if (LED_ON[10] == 1) led_value = led_value & 0xFF7F;		// Pulse Width
	if (LED_ON[11] == 1) led_value = led_value & 0xFFFE;		// More - Not Used
	if (LED_ON[12] == 1) led_value = led_value & 0xFFDF;		// Run/Stop Green
	if (LED_ON[13] == 1) led_value = led_value & 0xFFEF;		// Run/Stop Red
	if (LED_ON[14] == 1) led_value = led_value & 0xFFF7;		// Single Red					
	if (LED_ON[15] == 1) led_value = led_value & 0xFFFB;		// Single Green
	
	serdata->np_piodata = led_value;
	serstartled->np_piodata = 0x01;
	serstartled->np_piodata = 0x00;	
#ifdef _Debug_	
	if (Debug_Mode) printf("LED VAL : %x \n", led_value);
#endif
}

void Hardware::DoEnableRotInterrupt(void)						// Enable service routine
{
	rot_int->np_pioedgecapture = 0x00; 							// clear all existing IRQ conditions
	rot_int->np_piodirection = 0x00;							// set all bits to input
	rot_int->np_piointerruptmask = 0x01;						// enable Button IRQs

	key_reset->np_piodata = 0;
	nr_delay(1);
	key_reset->np_piodata = 1;

	rot_int->np_pioedgecapture = 0x00; 							// clear all existing IRQ conditions
	
	nr_installuserisr(na_rot_interrupt_irq,ISR_ROT,(int)rot_int);	// Install ISR for parallel I/Os
#ifdef _Debug_IRQ_
	if (Debug_Mode) printf("\nRot interrupt enabled.\n");  						// print on console
#endif	
}
	
void Hardware::DoDisableRotInterrupt(void)						// Disable parallel I/O service routine
{
	nr_installuserisr(na_rot_interrupt_irq,0,0); 				// Install empty routine for pio irq
	rot_int->np_piointerruptmask = 0x00;						// disable all IRQs
}

void Hardware::ISR_ROT(int context)							// Parallel I/O Interrupt subroutine
{
	int ct;
	int KeyData = key->np_piodata;								// Get interrupt data to asign respective ISR
	int Rot_Dir = KeyData & 0x000FFF;							// Get interrupt data to asign respective ISR
		
	ADC_Data_Available_cnt = 2;
		
	Rotary_Switch = (KeyData & 0xFFF000) >> 12;

	for (ct = 0; ct < 100; ct++){};
	
	rot_speed_read->np_piodata = 1;
	Rotary_Steps = key->np_piodata & 0x000FFF;							// Get interrupt data to asign respective ISR

	
	//printf("\nkeydata : %3x RotSW %3x RotDir %i RotaryDirec %i RotDirMem %i RotSpe : %i \n\n", key->np_piodata, Rotary_Switch, Rot_Dir, Rotary_Direction, Rotary_Direction_mem, Rotary_Steps);	

	rot_speed_read->np_piodata = 0;

	key_reset->np_piodata = 0;
	for (ct = 0; ct < 100; ct++){};
	key_reset->np_piodata = 1;

	Rotary_Changed = 1;
	UI_request = 1;
		
	rot_int->np_pioedgecapture = 0;								// clear IRQ conditions		

	if (Rotary_Switch == Rot_Dir) Rotary_Direction = 1;
	else Rotary_Direction = 0;

#ifdef _Debug_IRQ_
    if (Debug_Mode) printf("RotSW %3x RotDir %i RotaryDirec %i RotDirMem %i RotSpe : %i \n", Rotary_Switch, Rot_Dir, Rotary_Direction, Rotary_Direction_mem, Rotary_Steps);	
#endif
	Rotary_Direction_mem = Rotary_Direction;
	
	if (SingleMode == 1)
	{
		SingleMode = 0;
	
		LED_ON[14] = 0;
		LED_ON[15] = 0;
	}

}
//########################################################################################################################################################
// call wheel handler routines depending on used wheel
void Hardware::Rotary_Interface(void)
{
	if (Rotary_Changed == 0) return;
	Rotary_Changed = 0;
	
	UI_request = 0;		//reset UI-request flag	

	//    ClearPlanes();
	
	if (Splash_drawed)
	{
		Display::REMOVE_SPLASH();
		Display::DrawInitialScreen();	//Display::RefreshScreen();???
		Splash_drawed = false;
	
		TimebaseChanged = 1;
		TimeOffsetChanged = 1;
		TriggerLevelChanged = 1;
		TriggerModeChanged = 1;
		TriggerWayChanged = 1;
		VoltageChangedCh1 = 1;									// Was Voltage changed
		VoltageChangedCh2 = 1;									// Was Voltage changed
		VoltageChangedCh3 = 1;									// Was Voltage changed
		VoltageChangedCh4 = 1;									// Was Voltage changed          		
			
		Display::StatusUpdate();
		
		CursorChanged = 3;
		Cursor_Data_First_Draw = 1;
		Display::DRAWCURSORDATA(0);
	
		Quick_Measure_First_Draw = 1;
		Display::DRAWQMDATA(0); 	
	
		Display::DRAW_ALL_CURSOR();
	
		if (Continius) Start_Record();
	
		return;
	}
	
	if ((Active_Menu == 12) || (Active_Menu == 15)) Rotary_Direction_mem_pulse = Rotary_Direction;



#ifdef _Debug_
    if (Debug_Mode) printf("Steps = %i Dir = %i \n", Rotary_Steps, Rotary_Direction);
#endif
	if ((Rotary_Switch & 0x00000001) == 0x00000001) { ResetTimer(); ON_Rotary_Position(); }     // ON Trigger Position
	else if ((Rotary_Switch & 0x00000002) == 0x00000002) { ResetTimer(); ON_Trigger_Level(); }
	else if ((Rotary_Switch & 0x00000004) == 0x00000004) { ResetTimer(); ON_Main_Wheel(); }
	else if ((Rotary_Switch & 0x00000008) == 0x00000008) { ResetTimer(); ON_Timebase(); }
	else if ((Rotary_Switch & 0x00000010) == 0x00000010) { ResetTimer(); ON_Zero_Channel_2(); }
	else if ((Rotary_Switch & 0x00000020) == 0x00000020) { ResetTimer(); ON_Voltage_Channel_2(); }
	else if ((Rotary_Switch & 0x00000040) == 0x00000040) { ResetTimer(); ON_Voltage_Channel_1(); }
	else if ((Rotary_Switch & 0x00000080) == 0x00000080) { ResetTimer(); ON_Zero_Channel_1(); }
	else if ((Rotary_Switch & 0x00000100) == 0x00000100) { ResetTimer(); ON_Zero_Channel_4(); }
	else if ((Rotary_Switch & 0x00000200) == 0x00000200) { ResetTimer(); ON_Voltage_Channel_4(); }
	else if ((Rotary_Switch & 0x00000400) == 0x00000400) { ResetTimer(); ON_Voltage_Channel_3(); }
	else if ((Rotary_Switch & 0x00000800) == 0x00000800) { ResetTimer(); ON_Zero_Channel_3(); }
	
	Rotary_Steps = 0;

}

void Hardware::ON_Rotary_Position(void)
{
	int pos = 0;
	int cd_size_buf = (int) (Cursor_Delayed_Size / 2);
	int rot_buf = Rotary_Steps;


	// BF -> if ultra slow timebase active leave
	if (USTB_Mode != USTB_OFF) return;
	if (FFT_Mode != FFT_OFF) return;

	if ((MenuStatus[MENU_TIMEBASE][1] == 0) || (MenuStatus[MENU_TIMEBASE][1] == 246))
	{
		//rot_buf = ((int) ((float)rot_buf * ZFT_float));
	
		//rot_buf = (rot_buf * rot_buf) + rot_buf; 		//BF new square function characteristic X² + X
		rot_buf = (rot_buf * rot_buf * rot_buf) + rot_buf; 	//BF new cubic function characteristic X³ + X
	
	
	/*BF del
		if ((rot_buf > ((int) ((float)5 * ZFT_float))) && (rot_buf < ((int) ((float)11 * ZFT_float)))) rot_buf = rot_buf * 3;
		else if (rot_buf > ((int) ((float)10 * ZFT_float))) rot_buf = rot_buf * 7;	
	*/
		//if ((rot_buf > 5) && (rot_buf < 11)) rot_buf = rot_buf * 15;
		//else if (rot_buf > 10) rot_buf = rot_buf * 40;	
		
		if (Rotary_Direction)
		{
		if (Selected_Timebase < 9)
		{
			if ((MemWinStart + SIG_Size[ZIT_short] + rot_buf) < 16250)
			{ MemWinStart = MemWinStart + rot_buf; }
			else
			{ MemWinStart = 16250 - SIG_Size[ZIT_short]; }
		}
		else
		{
			if ((MemWinStart + SIG_Size[ZIT_short] + rot_buf) < 4070)
			{ MemWinStart = MemWinStart + rot_buf; }
			else
			{ MemWinStart = 4070 - SIG_Size[ZIT_short]; }
		}
		}
		else
		{
		if ((MemWinStart - rot_buf) > 100)
		{ MemWinStart = MemWinStart - rot_buf; }
		else
		{ MemWinStart = 100; }
		}
	
	}    		
	else  // Delayed mode
	{
		if ((rot_buf > 5) && (rot_buf < 11)) rot_buf = rot_buf * 3;
		else if (rot_buf > 10) rot_buf = rot_buf * 7;	
		
		if (Rotary_Direction)
		{
		if ((dmode_Window_Offset_Pos + rot_buf) < (300 - cd_size_buf)) dmode_Window_Offset_Pos = dmode_Window_Offset_Pos + rot_buf;
		else dmode_Window_Offset_Pos = 300 - cd_size_buf;
		}
		else
		{
		if ((dmode_Window_Offset_Pos - rot_buf) > (-300 + cd_size_buf)) dmode_Window_Offset_Pos = dmode_Window_Offset_Pos - rot_buf;
		else dmode_Window_Offset_Pos = (-300 + cd_size_buf);
		}
	}

    	Recalc_Vars();
    
 // TMW changed 
	if ((MenuStatus[MENU_TIMEBASE][1] == 0) || (MenuStatus[MENU_TIMEBASE][1] == 246)) 
	{
        	if (Memory_Window_visible)
            	  Display::DRAWMEMORY(0, 0, 1);
        	else
	          Display::DRAWMEMORY(0, 1, 1);
     	}
// TMW change ends
    
    
    Display::CALCPRETRIGGER();
    Display::DRAW_ALL_CURSOR();

    //Display::DRAWSTATUS(5, 1);									// Draw Pre Trigger

 
#ifdef _Debug_Memory_
    if (Debug_Mode) printf("TB Offset = %d\n", Timebase_Offset_Pos);
#endif
}

void Hardware::ON_Trigger_Level(void)
{
	if (MenuStatus[MENU_TRIGGEREDGE][3] == 1) return;
	if ((MenuPopupStatus[8][2] == 3) && (MenuStatus[MENU_TRIGGEREDGE][2] == 1)) return;
	if (XY_Mode) return;

/*BF del
    if ((Rotary_Steps > 5) && (Rotary_Steps < 11)) Rotary_Steps = Rotary_Steps * 3;
    else if (Rotary_Steps > 10) Rotary_Steps = Rotary_Steps * 7;
*/
	Rotary_Steps = ((Rotary_Steps * Rotary_Steps) >> 2) + Rotary_Steps; 	//BF new square function characteristic 1/4 * X² + x


	if (Rotary_Direction == 0)
	{
		//if (triggering == 0) return;
		if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
			
		switch(Selected_Trigger_Source)
		{
			case 1: if ((Trigger_Pos_CH1 + Rotary_Steps) < GRID_HEIGHT) Trigger_Pos_CH1 = Trigger_Pos_CH1 + Rotary_Steps; else Trigger_Pos_CH1 = GRID_HEIGHT; Trigger_Pos_CH1_os = 0; break;
			case 2: if ((Trigger_Pos_CH2 + Rotary_Steps) < GRID_HEIGHT) Trigger_Pos_CH2 = Trigger_Pos_CH2 + Rotary_Steps; else Trigger_Pos_CH2 = GRID_HEIGHT; Trigger_Pos_CH2_os = 0; break;
			case 3: if ((Trigger_Pos_CH3 + Rotary_Steps) < GRID_HEIGHT) Trigger_Pos_CH3 = Trigger_Pos_CH3 + Rotary_Steps; else Trigger_Pos_CH3 = GRID_HEIGHT; Trigger_Pos_CH3_os = 0; break;
			case 4: if ((Trigger_Pos_CH4 + Rotary_Steps) < GRID_HEIGHT) Trigger_Pos_CH4 = Trigger_Pos_CH4 + Rotary_Steps; else Trigger_Pos_CH4 = GRID_HEIGHT; Trigger_Pos_CH4_os = 0; break;
			case 5: if ((Trigger_Pos_CHE + 1) < 32) Trigger_Pos_CHE = Trigger_Pos_CHE + 1; else Trigger_Pos_CHE = 32; break;
		}
			
		UpdateTrigger(16);
	
	}

	else
	{
		//if (triggering == 0) return;
		if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
		
		switch(Selected_Trigger_Source)
		{
			case 1: if ((Trigger_Pos_CH1 - Rotary_Steps) > 0) Trigger_Pos_CH1 = Trigger_Pos_CH1 - Rotary_Steps; else Trigger_Pos_CH1 = 0; break;
			case 2: if ((Trigger_Pos_CH2 - Rotary_Steps) > 0) Trigger_Pos_CH2 = Trigger_Pos_CH2 - Rotary_Steps; else Trigger_Pos_CH2 = 0; break;
			case 3: if ((Trigger_Pos_CH3 - Rotary_Steps) > 0) Trigger_Pos_CH3 = Trigger_Pos_CH3 - Rotary_Steps; else Trigger_Pos_CH3 = 0; break;
			case 4: if ((Trigger_Pos_CH4 - Rotary_Steps) > 0) Trigger_Pos_CH4 = Trigger_Pos_CH4 - Rotary_Steps; else Trigger_Pos_CH4 = 0; break;
			case 5: if ((Trigger_Pos_CHE - 1) > 0) Trigger_Pos_CHE = Trigger_Pos_CHE - 1; else Trigger_Pos_CHE = 0; break;
		}
			
		UpdateTrigger(17);
	
	}

		Display::DRAWSTATUS(6, 1);			// Draw Trigger Level
		VS_TrigLevelChanged = 1;

}
//##########################################################################################################################################
// Main wheel dispatcher
void Hardware::ON_Main_Wheel(void)
{
    if (Rotary_Direction)
    {
        HandleMainWheel(1);
    }
    else
    {
        HandleMainWheel(0);
    }
}
//##########################################################################################################################################
// Timebase wheel handler
void Hardware::ON_Timebase(void)
{
	int rbuf = Rotary_Steps;
	
	//    reset_watchdog->np_piodata = 0x00;
	
	//printf("On_TB_1_%d : rbuf : %d distb :%d = Sel %d + idx %d\n", Rotary_Direction, rbuf, Display_Timebase, Selected_Timebase, SIGNALFaktor_idx);
	
	if (FFT_Mode != FFT_OFF)
	{
		if (Selected_Timebase == 23 && !Rotary_Direction)		// no FFT for ultra slow timebases
		{
			Rotary_Steps = 0;
			return;
		}
	}

	Display_Timebase_Old = Display_Timebase;
	Selected_Timebase_Old = Selected_Timebase;
	SIGNALFaktor_idx_Old = SIGNALFaktor_idx;

	//BF added for new start/stop logic
	Stop_Record();
			
	if (Rotary_Direction)	//clockwise -> decrement timebase
	{
//		if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }          	
		
		// Delayed Mode
		if (MenuStatus[MENU_TIMEBASE][1] == 1)
		{
			if (Continius == 0)
			{
				while (rbuf > 0)
				{
					if (dmode_SIGNALFaktor_idx > 0)
					{	
						dmode_SIGNALFaktor_idx--;
						SIGNALFaktorChanged = 1;
					}
					else if ((dmode_Selected_Timebase > 2) && (dmode_Selected_Timebase < 5) && (dmode_SIGNALFaktor_idx == 0) && (Selected_Timebase < 5))
					{
						dmode_Selected_Timebase--;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					rbuf--;
				}
			}
			else	//Continius == 1
			{
				while (rbuf > 0)
				{
					if ((dmode_Selected_Timebase > 4) && (dmode_SIGNALFaktor_idx == 4))
					{
						dmode_Selected_Timebase--;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					else if (dmode_SIGNALFaktor_idx > 0)
					{	
						dmode_SIGNALFaktor_idx--;
						SIGNALFaktorChanged = 1;
					}
					else if ((dmode_Selected_Timebase > 2) && (dmode_SIGNALFaktor_idx == 0) && (Selected_Timebase < 5))
					{
						dmode_Selected_Timebase--;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					rbuf--;
				}
			}			
		}
		// Main Mode
		else		
		{	  	
			if (Continius == 0)
			{
				while (rbuf > 0)
				{
				if (SIGNALFaktor_idx > 0)
				{	
					SIGNALFaktor_idx--;
					SIGNALFaktorChanged = 1;
				}
				//BF test delete   else if ((Selected_Timebase > 2) && (Selected_Timebase < 5) && (SIGNALFaktor_idx == 0))
				else if ((Selected_Timebase > 0) && (Selected_Timebase < 5) && (SIGNALFaktor_idx == 0)) //BF new timebase 5nS + 2nS
				{
					Selected_Timebase--;
					TimebaseChanged = 1;
					SIGNALFaktorChanged = 1;
				}
				rbuf--;
				}
			}
			else	//Continius == 1
			{
				while (rbuf > 0)
				{
					if ((Selected_Timebase > 4) && (SIGNALFaktor_idx == 4))
					{
						Selected_Timebase--;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					else if ((Selected_Timebase > 6) && (SIGNALFaktor_idx == 2))
					{
						Selected_Timebase--;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					else if (SIGNALFaktor_idx > 0)
					{	
						SIGNALFaktor_idx--;
						SIGNALFaktorChanged = 1;
					}
					
					//BF test delete   else if ((Selected_Timebase > 2) && (SIGNALFaktor_idx == 0))
					else if ((Selected_Timebase > 0) && (SIGNALFaktor_idx == 0)) //BF new timebase 5nS + 2nS
 					{
						Selected_Timebase--;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					
					if ((Selected_Timebase == 7) && (SIGNALFaktor_idx == 4))
					{
						if (Selected_Timebase_Old < 6)
						{
							Selected_Timebase = 9;
							SIGNALFaktor_idx = 2;
						}
					}
			
					if ((Selected_Timebase == 8) && (SIGNALFaktor_idx == 2))
					{
						if (Selected_Timebase_Old == 9)
						{
							Selected_Timebase = 6;
							SIGNALFaktor_idx = 4;
						}
					}
			
					rbuf--;
				}
				
			}		
		}
	}
	else	//direction is counterclockwise -> increment timebase
	{
		if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }

        	// Delayed Mode
		if (MenuStatus[MENU_TIMEBASE][1] == 1)
		{	
			if (Continius == 0)
			{
				while (rbuf > 0)
				{
					if ((dmode_Selected_Timebase > 1) && (dmode_Selected_Timebase < 4) && (dmode_SIGNALFaktor_idx == 0) && (dmode_Selected_Timebase < (Selected_Timebase - 1)))
					{
						dmode_Selected_Timebase++;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
				
					else if ((dmode_SIGNALFaktor_idx < 4) && (dmode_SIGNALFaktor_idx < (SIGNALFaktor_idx - 1)) && (dmode_Selected_Timebase == Selected_Timebase))
					{	
						dmode_SIGNALFaktor_idx++;
						SIGNALFaktorChanged = 1;
					}
					
					rbuf--;
				}
			}	
			else	//Continius == 1
            		{
				while (rbuf > 0)
				{
					if ((dmode_Selected_Timebase > 1) && (dmode_Selected_Timebase < 5) && (((dmode_SIGNALFaktor_idx == 0) && (dmode_Selected_Timebase < (Selected_Timebase - 1)))  || ((SIGNALFaktor_idx > 0) && (dmode_Selected_Timebase < Selected_Timebase)) ))
					{
						dmode_Selected_Timebase++;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
				
					else if ((dmode_SIGNALFaktor_idx < 4) && (dmode_SIGNALFaktor_idx < (SIGNALFaktor_idx - 1)) && (dmode_Selected_Timebase == Selected_Timebase))
					{	
						dmode_SIGNALFaktor_idx++;
						SIGNALFaktorChanged = 1;
					}
			
					rbuf--;
				}
				UI_request = 0;
			}
		}  
		// Main Mode
		else
		{        		                                                             		
			if (Continius == 0)
			{
				while (rbuf > 0)
				{
					if ((Selected_Timebase < 4) && (SIGNALFaktor_idx == 0))
					{
						Selected_Timebase++;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					else if ((Selected_Timebase < 8) && (SIGNALFaktor_idx < 4))
					{	
						SIGNALFaktor_idx++;
						SIGNALFaktorChanged = 1;
					}
					else if ((Selected_Timebase > 7) && (SIGNALFaktor_idx < 2))
					{	
						SIGNALFaktor_idx++;
						SIGNALFaktorChanged = 1;
					}
			
					rbuf--;
				}
			}	
			else	//Continius == 1
			{
				//printf("Here we are %d %d %d\n", Selected_Timebase, SIGNALFaktor_idx, Selected_Timebase_Old);
						
				while (rbuf > 0)
				{
					if (Selected_Timebase < 4)
					{
						Selected_Timebase++;
						TimebaseChanged = 1;
						SIGNALFaktorChanged = 1;
					}
					else if ((Selected_Timebase < 7) && (SIGNALFaktor_idx < 4))
					{	
						SIGNALFaktor_idx++;
						SIGNALFaktorChanged = 1;
					}
					else if ((Selected_Timebase > 6) && (SIGNALFaktor_idx < 2))
					{	
						SIGNALFaktor_idx++;
						SIGNALFaktorChanged = 1;
					}
					else if ((Selected_Timebase < 7) && (SIGNALFaktor_idx == 4))
					{
						if (Selected_Timebase < 31)
						{
							Selected_Timebase++;
							TimebaseChanged = 1;
							SIGNALFaktorChanged = 1;
						}
					}
					else if ((Selected_Timebase > 6) && (SIGNALFaktor_idx == 2))
					{
						if (Selected_Timebase < 31)
						{
							Selected_Timebase++;
							TimebaseChanged = 1;
							SIGNALFaktorChanged = 1;
						}
					}
					
					if ((Selected_Timebase == 7) && (SIGNALFaktor_idx == 4))
					{
						if (Selected_Timebase_Old < 7)
						{
							Selected_Timebase = 9;
							SIGNALFaktor_idx = 2;
						}
					}
			
					if ((Selected_Timebase == 8) && (SIGNALFaktor_idx == 2))
					{
						if (Selected_Timebase_Old > 8)
						{
							Selected_Timebase = 6;
							SIGNALFaktor_idx = 4;
						}
					}
			
					rbuf--;
				}
				
			//printf("Here we are2 %d %d %d\n", Selected_Timebase, SIGNALFaktor_idx, Selected_Timebase_Old);		
			}
		}		
	}

	//activate new settings
	timebase_reg = tb_value[Selected_Timebase];
    	Display_Timebase = Selected_Timebase + SIGNALFaktor_idx;
    
	if (Selected_Timebase > 7)
	{ adc_change12_reg |= 0x01000000; }
	else
	{ adc_change12_reg &= 0xFEFFFFFF; }

   	Recalc_Vars();

	UI_request = 0;
	config_changed = 1;

	//------------------------------------------------------------
	//BF add new FFT mode
	//------------------------------------------------------------
	if (FFT_Mode != FFT_OFF)
	{
		Display::FFT_DrawStatus();		// redraw FFT status informations 
	}


	//------------------------------------------------------------
	//BF add new ultra slow timebase mode
	//------------------------------------------------------------
	if (Selected_Timebase > 23) 	//timebase > 500mS/Div?
	{
		
		Display::USTB_Clear_Buffer();	//clear all buffers
		
		Reset_Timer2();

		if(USTB_Mode == USTB_OFF)
		{
			//restore roll/shift mode setting in menu
			if (USTB_Mode_bak == USTB_ROLL)
			{
				MenuStatus[MENU_TIMEBASE][3] = 1;
				MenuStatus[MENU_TIMEBASE][4] = 0;
			}
			else if (USTB_Mode_bak == USTB_SHIFT)
			{
				MenuStatus[MENU_TIMEBASE][3] = 0;
				MenuStatus[MENU_TIMEBASE][4] = 1;
			}
			//set USTB-mode to previous setting
			USTB_Mode = USTB_Mode_bak;

			if (Active_Menu == MENU_TIMEBASE)	// main/delayed menu active?
			{
				Menu_Changed = 1;
				MenuItemChanged[3] = 1;
				MenuItemChanged[4] = 1;
				New_Menu = Active_Menu;
			}
		}

		//if(MenuStatus[MENU_TIMEBASE][3] == 1)	//roll mode? 
		//USTB_Mode = 1;			//roll mode
		//else if(MenuStatus[MENU_TIMEBASE][4] == 1)	//or shift mode?
		//USTB_Mode = 2;			//shift mode
	
		//Backup triggersetting and force auto mode	
		AUTOMODE_bak = MenuStatus[MENU_TRIGGERMODE][0];
		MenuStatus[MENU_TRIGGERMODE][0] = 93;		//set trigger auto mode
		MenuPopupStatus[9][0] = 2;
		MenuPopupStatus[9][1] = 3;
		if (Active_Menu == MENU_TRIGGERMODE)	
		{
			Menu_Changed = 1;
			MenuItemChanged[0] = 1;
			New_Menu = Active_Menu;
		}
		TriggerLevelChanged = 1;
		TriggerModeChanged = 1;
		UpdateTrigger(4);
		

	
	}
	else	//normal timebase
	{
		if (USTB_Mode != USTB_OFF)	//was USTB mode active?
		{
			Stop_Timer2();

			//backup and deactivate roll/shift mode setting in menu
			USTB_Mode_bak = USTB_Mode;
			MenuStatus[MENU_TIMEBASE][3] = 246;
			MenuStatus[MENU_TIMEBASE][4] = 246;
			
			if (Active_Menu == MENU_TIMEBASE)	// main/delayed menu active?
			{
				Menu_Changed = 1;
				MenuItemChanged[3] = 1;
				MenuItemChanged[4] = 1;
				New_Menu = Active_Menu;
			}
			
			USTB_Mode = USTB_OFF;				//switch off USTB mode
			
			//restore triggermode
			MenuStatus[MENU_TRIGGERMODE][0] = AUTOMODE_bak;	
			MenuPopupStatus[9][0] = 2;
			MenuPopupStatus[9][1] = 3;
			
			if (Active_Menu == MENU_TRIGGERMODE)	
			{
				Menu_Changed = 1;
				MenuItemChanged[0] = 1;
				New_Menu = Active_Menu;
			}
			TriggerLevelChanged = 1;
			TriggerModeChanged = 1;
			UpdateTrigger(4);
			
		}
	} 


	//No delayed mode for timebase 5ns and USTB-timebases
	if (Selected_Timebase == 1 || USTB_Mode != USTB_OFF)
	{ MenuStatus[MENU_TIMEBASE][1] = 246; }	
	else
	{
		if(MenuStatus[MENU_TIMEBASE][0] == 1 || MenuStatus[MENU_TIMEBASE][2] == 1)
		MenuStatus[MENU_TIMEBASE][1] = 0;
		else
		MenuStatus[MENU_TIMEBASE][1] = 1;
	}
/*BF XY-mode is supported now	
	//No XY mode for  USTB-timebases
	if (USTB_Mode != 0)
	{ MenuStatus[MENU_TIMEBASE][2] = 246; }	
	else
	{
		if(MenuStatus[MENU_TIMEBASE][0] == 1 || MenuStatus[MENU_TIMEBASE][1] == 1)
		MenuStatus[MENU_TIMEBASE][2] = 0;
		else
		MenuStatus[MENU_TIMEBASE][2] = 1;
	}
*/

	if (Active_Menu == MENU_TIMEBASE)	// main/delayed menu active?
	{
		MenuButtonCheck(-1);
		if (MenuPopupActive > -1)
	 	{ Display::DRAWMENUPOPDOWN(); }
		New_Menu = Active_Menu;
		Menu_Changed = 1;
		MenuItemChanged[1] = 1;
		//MenuItemChanged[2] = 1;
	}
	
	//--------------------------------------------
	//         memory window
	//--------------------------------------------
	if (USTB_Mode == USTB_OFF && FFT_Mode == FFT_OFF)	//USTB mode off?
	{
		if (Memory_Window_visible) 		// if Memory Window visible
			Display::DRAWMEMORY(0, 0, 1); 	// redraw Memory Window
		else
			Display::DRAWMEMORY(0, 1, 1); 	// if Memory Window not visible yet, make it visible.
	}
	else
	{
		if (Memory_Window_visible) 
		Display::DRAWMEMORY(1, 0, 0);		//close memory window
	}

 	//-------------------------------------------------
	//         Cursor
	//-------------------------------------------------
	if (Cursor_Enabled)
	{
		//BF redundant Display::CALCCURSORDATA();
	
		if (Active_Menu == 16)
		{
			MenuItemChanged[1] = 1;
			MenuItemChanged[2] = 1;
			New_Menu = Active_Menu;
		}
		Menu_Changed = 1;
		CursorChanged = 1;
	}
	
	MenuStatusChanged = 1;
	
	Display::CALCPRETRIGGER();
	
	if(FFT_Mode != FFT_OFF)
	Display::FFT_CalcCursorData();
	else
	Display::CALCCURSORDATA();

	Display::DRAW_ALL_CURSOR();

	Display::StatusUpdate();
	Display::DRAWSTATUS(0, 1);
	SetupADC();	

	//BF add for new start/stop logic
	//Start_Record();
	
	//BF add new start/stop logic
	if ((!SingleMode) && (Continius) && (!OneShotRestart))
	{ Start_Record(); } 

}

//##########################################################################################################################################
void Hardware::Recalc_Vars(void)
{
	ZIT_short_old       = ZIT_short;
	ZIT_short_dmode_old = ZIT_short_dmode;
	ZFT_float_old       = ZFT_float;
	ZFT_float_dmode_old = ZFT_float_dmode;
	OFT_float_old       = OFT_float;
    	
	ZIT_short       = Zoom_Index_Table[Selected_Timebase][SIGNALFaktor_idx];
	ZIT_short_dmode = Zoom_Index_Table[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx];
	
	ZFT_float       = Zoom_Faktor_Table[ZIT_short];
	ZFT_float_dmode = Zoom_Faktor_Table[ZIT_short_dmode];
	
	OFT_float = Offset_Faktor_Table[ZIT_short];

	// Correct the Trigger Position
	Trig_Pos_Mem = (int)((float) Trig_Pos_Mem * (ZFT_float / ZFT_float_old));
	
	// Correct the Memory Position
	MemWinStart = (int)((float) (MemWinStart) * (ZFT_float / ZFT_float_old));
 
   
        if (MemWinStart < MemStartOffs) 
        {
        	Trig_Pos_Mem = Trig_Pos_Mem + (MemStartOffs - MemWinStart);
        	MemWinStart = MemStartOffs;
        }

	if (Selected_Timebase < 9)
	{
		if ((MemWinStart + SIG_Size[ZIT_short]) > 16250) MemWinStart = 16250 - SIG_Size[ZIT_short];
	}
	else
	{
		if ((MemWinStart + SIG_Size[ZIT_short]) > 4070) MemWinStart = 4070 - SIG_Size[ZIT_short];
	}


	if (MenuStatus[MENU_TIMEBASE][1] == 1)
	{
		dmode_factor = Timebase_Delayed_Factor_Matrix[Selected_Timebase][SIGNALFaktor_idx] / Timebase_Delayed_Factor_Matrix[dmode_Selected_Timebase][dmode_SIGNALFaktor_idx];
	
		Cursor_Delayed_1 = ((GRID_WIDTH / 2) - (int) (((float) GRID_WIDTH / dmode_factor) / 2)) + dmode_Window_Offset_Pos;
		Cursor_Delayed_2 = Cursor_Delayed_1 + (int) ((float) GRID_WIDTH / dmode_factor);
		Cursor_Delayed_Size = Cursor_Delayed_2 - Cursor_Delayed_1;
	}
    
    	Recalc_Trigger();

    ////if (Selected_Timebase < 4) FirStartCH = (int)((float) MemWinStart * OFT_float) + 20;
    //BF -> not used if (Selected_Timebase < 4) FirStartCH = MemWinStart + 40;

	//printf("ZIT short : %d      ", ZIT_short);
	//printf("ZFT float : ");Display::floatprintf(ZFT_float);printf("\r\n");

}

void Hardware::Recalc_Trigger(void)
{
    //BF -> not used FirStartCH_delayed = (short) (ZFT_float * (float) (Cursor_Delayed_1 + (Cursor_Delayed_Size >> 1))) - 10;
    
//    printf("C1 pre : %x TPM : %d TMP : %d - %d\n\n", pre_reg, Trig_Pos_Mem, MemWinStart, Trig_Pos_Display);
    
    Trig_Pos_Display = (int) ((float)(Trig_Pos_Mem - MemWinStart) / ZFT_float);
    Trig_Pos_Display_dmode = (int) (((float)(Trig_Pos_Mem - MemWinStart) / ZFT_float_dmode) - ((float) Cursor_Delayed_1 * (ZFT_float / ZFT_float_dmode)));
    
    if (Selected_Timebase < 9) pre_reg = (Trig_Pos_Mem >> 2) + PreReg_Offset;
    else pre_reg = (Trig_Pos_Mem) + PreReg_Offset;

//    printf("C2 pre : %x TPM : %d TMP : %d - %d\n\n", pre_reg, Trig_Pos_Mem, MemWinStart, Trig_Pos_Display);
    
    if (pre_reg > 4096)
    {
    	printf("pre overrun \n");
        Trig_Pos_Mem = GRID_WIDTH / 2;
        MemWinStart = MemStartOffs;

        Trig_Pos_Display = (int) ((float)(Trig_Pos_Mem - MemWinStart) / ZFT_float);

        if (Selected_Timebase < 9) pre_reg = (Trig_Pos_Mem >> 2) + PreReg_Offset;
        else pre_reg = (Trig_Pos_Mem) + PreReg_Offset;
    }
    
//    printf("C3 pre : %x TPM : %d TMP : %d - %d\n\n", pre_reg, Trig_Pos_Mem, MemWinStart, Trig_Pos_Display);
}

//##########################################################################################################################################
// Set voltage range for channel 1
void Hardware::ON_Voltage_Channel_1(void)
{
	int cnt;
	float fvolt_factor = 0;
	float fvolt_factor2 = 0;
	
	int shift_cnt = 0;
	
	if (Channel_1_Active == false) return;

	//Adjust voltage range
	if (Rotary_Direction == 1)
	{
		//if (Selected_Voltage_CH1 == 3) return;	//BF del
		if (Selected_Voltage_CH1 == 0) return;		//BF test
	//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
			if ((Selected_Voltage_CH1 - Rotary_Steps) > 3)
			{
				Selected_Voltage_CH1 -= Rotary_Steps;
			}
			else Selected_Voltage_CH1 = 3;
			
			SetSwitches(1, Selected_Voltage_CH1);
			VoltageChangedCh1 = 1;
	
		if (Cursor_Enabled)
		{
			if(FFT_Mode != FFT_OFF)
			Display::FFT_CalcCursorData();
			else
			Display::CALCCURSORDATA();

			Menu_Changed = 1;
			CursorChanged = 4;
		}
	
		if (QM_Enabled)
		{
			Display::CALCQMDATA();
			Menu_Changed = 1;
		}
				
		Display::DRAWSTATUS(1, 1);											// Draw Voltage Channel 1
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
		if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
		{
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
					
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}
		if (Active_Menu == 19)
		{
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}	
		/*
		if (Continius == false)
		{
			if (signal_zoomed1 == false) for (cnt = 0; cnt < 16383; cnt++) SIGNAL1_IntBuf_YZoom[cnt] = (int) SIGNAL1[cnt];
	
			Voltage_Zoom(&SIGNAL1[0], &SIGNAL1_IntBuf_YZoom[0], Selected_Voltage_CH1, Selected_Voltage_CH1_Old, ZeroLevelCH1);
	
			UserIface_active = 0;
			signal_zoomed1 = true;
		}*/			
	}
	else
	{
		if (Selected_Voltage_CH1 == 11) return;

//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
		if ((Selected_Voltage_CH1 + Rotary_Steps) < 11)
		{
			Selected_Voltage_CH1 += Rotary_Steps;       			
		}
		else Selected_Voltage_CH1 = 11;	
	
		SetSwitches(1, Selected_Voltage_CH1);
		VoltageChangedCh1 = 1;
				
		if (Cursor_Enabled)
		{
			if(FFT_Mode != FFT_OFF)
			Display::FFT_CalcCursorData();
			else
			Display::CALCCURSORDATA();

			Menu_Changed = 1;
			CursorChanged = 4;
		}
		
		if (QM_Enabled)
		{
			Display::CALCQMDATA();
			Menu_Changed = 1;
		}
				
		Display::DRAWSTATUS(1, 1);											// Draw Voltage Channel 1
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
			
		if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
		{
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}
		if (Active_Menu == 19)
		{
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}
			/*
		if (Continius == false)
		{
			if (signal_zoomed1 == false) for (cnt = 0; cnt < 16383; cnt++) SIGNAL1_IntBuf_YZoom[cnt] = (int) SIGNAL1[cnt];
	
			Voltage_Zoom(&SIGNAL1[0], &SIGNAL1_IntBuf_YZoom[0], Selected_Voltage_CH1, Selected_Voltage_CH1_Old, ZeroLevelCH1);
	
			UserIface_active = 0;
			signal_zoomed1 = true;
		}   */
	}

	Rotary_Steps = 0;
	ON_Zero_Channel_1();
}
//##########################################################################################################################################
//set zerolevel for channel 1 (zero wheel handler)
void Hardware::ON_Zero_Channel_1(void)
{
	//int lCH1_DAC_Correction_1, lCH1_DAC_Correction_2, lCH1_DAC_Correction_3, Virtual_ZeroLevel_Buf;
	
	int rotbuf;
	
	if (FFT_Mode != FFT_OFF)
	{
		Rotary_Steps = 0;
		return;
	}
	//If XY-mode leave function
	//BF del    if (XY_Mode) return;
/*	
	if ((Rotary_Steps > 5) && (Rotary_Steps < 11)) rotbuf = Rotary_Steps * 3;
	else if (Rotary_Steps > 10) rotbuf = Rotary_Steps * 7;
	else rotbuf = Rotary_Steps;
*/
	//rotbuf = ((Rotary_Steps * Rotary_Steps) >> 1) + 1; 	//BF new square function characteristic 1/2 * X²
	rotbuf = ((Rotary_Steps * Rotary_Steps) >> 2) + Rotary_Steps; 	//BF new square function characteristic 1/4 * X² + x
	
	
	if (rotbuf)
	{
		
		if (Rotary_Direction == 0)	//clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
				
			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH1 - rotbuf) > -4095)  
				{ Virtual_ZeroLevelXYCH1 -= rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH1 = -4095; }       //Limiter
			}
			else	//Main mode TY
			{
				if ((Virtual_ZeroLevelCH1 + rotbuf) < 4095) // 0
				{ Virtual_ZeroLevelCH1 += rotbuf;	}	
				else
				{ Virtual_ZeroLevelCH1 = 4095; } //Limiter
			}
				
			VS_ZeroChangedCh1 = 1;
		
			if ((Virtual_ZeroLevelCH1 < 4095) && (Virtual_ZeroLevelCH1 > -4095))
			{
				if (Trigger_Pos_CH1_os < 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH1_os != 0))
					{ rotbuf--; Trigger_Pos_CH1_os++; }
				}
				

				if ((Trigger_Pos_CH1 + rotbuf) <= GRID_HEIGHT)
				{ Trigger_Pos_CH1 = Trigger_Pos_CH1 + rotbuf; }
				else
				{
					Trigger_Pos_CH1_os = Trigger_Pos_CH1_os + (rotbuf - (GRID_HEIGHT - Trigger_Pos_CH1));
					Trigger_Pos_CH1    = GRID_HEIGHT;	
				}
			}
			
			if (Selected_Trigger_Source == 1)
			{
				UpdateTrigger(18);	
			}
		}
		else	//counter clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
				
			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH1 + rotbuf) < 4095)
				{ Virtual_ZeroLevelXYCH1 += rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH1 = 4095; }	// limiter
			}
			else
			{
				if ((Virtual_ZeroLevelCH1 - rotbuf) > -4095)
				{ Virtual_ZeroLevelCH1 -= rotbuf; }	
				else
				{ Virtual_ZeroLevelCH1 = -4095; }
			}
			
			VS_ZeroChangedCh1 = 1;
				
			if ((Virtual_ZeroLevelCH1 < 4095) && (Virtual_ZeroLevelCH1 > -4095))
			{
				if (Trigger_Pos_CH1_os > 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH1_os != 0))
					{ rotbuf--; Trigger_Pos_CH1_os--; }
				}
				if ((Trigger_Pos_CH1 - rotbuf) >= 0)
				{ Trigger_Pos_CH1 = Trigger_Pos_CH1 - rotbuf; }
				else
				{
					Trigger_Pos_CH1_os = Trigger_Pos_CH1_os - (rotbuf - Trigger_Pos_CH1);
					Trigger_Pos_CH1 = 0;
				}
			}
			
			if (Selected_Trigger_Source == 1)
			{
				UpdateTrigger(19);	
			}
		}
	}
	
	
	if (XY_Mode)	//XY-Mode
	{
		ZeroLevelCH1 = Virtual_ZeroLevelXYCH1 + (GRID_XY / 2);
		if (ZeroLevelCH1 < 0) ZeroLevelCH1 = 0;
		if (ZeroLevelCH1 > GRID_XY) ZeroLevelCH1 = GRID_XY;
	}
	else	//TY-Mode
	{
		ZeroLevelCH1 = Virtual_ZeroLevelCH1 + (GRID_HEIGHT / 2);
		if (ZeroLevelCH1 < 0) ZeroLevelCH1 = 0;
		if (ZeroLevelCH1 > (GRID_HEIGHT + 1)) ZeroLevelCH1 = (GRID_HEIGHT + 1);
	}

 
	if (XY_Mode)
	{
		switch(Selected_Voltage_CH1)
		{
			case 0: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 1) / ZeroScaleFactor[0][0])) + 8192 + DAC_Correction[0][0]; break;//1 mV
			case 1: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 2) / ZeroScaleFactor[0][1])) + 8192 + DAC_Correction[0][1]; break;//2 mV
			case 2: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 3) / ZeroScaleFactor[0][2])) + 8192 + DAC_Correction[0][2]; break;//5 mV
			case 3: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 1) / ZeroScaleFactor[0][3])) + 8192 + DAC_Correction[0][0]; break;//10 mV
			case 4: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 2) / ZeroScaleFactor[0][4])) + 8192 + DAC_Correction[0][1]; break;//20 mV
			case 5: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 3) / ZeroScaleFactor[0][5])) + 8192 + DAC_Correction[0][2]; break;//50 mV
			case 6: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 1) / ZeroScaleFactor[0][6])) + 8192 + DAC_Correction[0][0]; break;//100 mV
			case 7: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 2) / ZeroScaleFactor[0][7])) + 8192 + DAC_Correction[0][1]; break;//200 mV
			case 8: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 3) / ZeroScaleFactor[0][8])) + 8192 + DAC_Correction[0][2]; break;//500 mV
			case 9: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 1) / ZeroScaleFactor[0][9])) + 8192 + DAC_Correction[0][0]; break;// 1V
			case 10: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 2) / ZeroScaleFactor[0][10])) + 8192 + DAC_Correction[0][1]; break;//2V
			case 11: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH1 * 3) / ZeroScaleFactor[0][11])) + 8192 + DAC_Correction[0][2]; break;//5V
		}
	}
	else
	{
		switch(Selected_Voltage_CH1)
		{
			case 0: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 1) / ZeroScaleFactor[0][0])) + 8192 + DAC_Correction[0][0]; break;//1 mV
			case 1: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 2) / ZeroScaleFactor[0][1])) + 8192 + DAC_Correction[0][1]; break;//2 mV
			case 2: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 3) / ZeroScaleFactor[0][2])) + 8192 + DAC_Correction[0][2]; break;//5 mV
		
			case 3: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 1) / ZeroScaleFactor[0][3])) + 8192 + DAC_Correction[0][0]; break;//10 mV
			case 4: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 2) / ZeroScaleFactor[0][4])) + 8192 + DAC_Correction[0][1]; break;//20 mV
			case 5: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 3) / ZeroScaleFactor[0][5])) + 8192 + DAC_Correction[0][2]; break;//50 mV
		
			case 6: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 1) / ZeroScaleFactor[0][6])) + 8192 + DAC_Correction[0][0]; break;//100 mV
			case 7: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 2) / ZeroScaleFactor[0][7])) + 8192 + DAC_Correction[0][1]; break;//200 mV
			case 8: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 3) / ZeroScaleFactor[0][8])) + 8192 + DAC_Correction[0][2]; break;//500 mV
		
			case 9:  CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 1) / ZeroScaleFactor[0][9])) + 8192 + DAC_Correction[0][0]; break;//  1 V
			case 10: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 2) / ZeroScaleFactor[0][10])) + 8192 + DAC_Correction[0][1]; break;// 2 V
			case 11: CH1_DAC_Offset = int ((float (Virtual_ZeroLevelCH1 * 3) / ZeroScaleFactor[0][11])) + 8192 + DAC_Correction[0][2]; break;// 5 V
		}

	}

    	SetDacOffset(1);
}

//##########################################################################################################################################
// Set voltage range for channel 2
void Hardware::ON_Voltage_Channel_2(void)
{
	int cnt;
	float fvolt_factor = 0;
	float fvolt_factor2 = 0;
	
	int shift_cnt = 0;
	
	if (Channel_2_Active == false) return;

	if (Rotary_Direction == 1)
	{
		if (Selected_Voltage_CH2 == 3) return;
	//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
			if ((Selected_Voltage_CH2 - Rotary_Steps) > 3)
			{
				Selected_Voltage_CH2 -= Rotary_Steps;
			}
			else Selected_Voltage_CH2 = 3;
			
			SetSwitches(2, Selected_Voltage_CH2);
			VoltageChangedCh2 = 1;
	
		if (Cursor_Enabled)
		{
			if(FFT_Mode != FFT_OFF)
			Display::FFT_CalcCursorData();
			else
			Display::CALCCURSORDATA();

			Menu_Changed = 1;
			CursorChanged = 4;
		}
	
		if (QM_Enabled)
		{
			Display::CALCQMDATA();
			Menu_Changed = 1;
		}
				
		Display::DRAWSTATUS(2, 1);											// Draw Voltage Channel 1
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
		if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
		{
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
					
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}
		if (Active_Menu == 19)
		{
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}	
		/*
		if (Continius == false)
		{
			if (signal_zoomed1 == false) for (cnt = 0; cnt < 16383; cnt++) SIGNAL1_IntBuf_YZoom[cnt] = (int) SIGNAL1[cnt];
	
			Voltage_Zoom(&SIGNAL1[0], &SIGNAL1_IntBuf_YZoom[0], Selected_Voltage_CH1, Selected_Voltage_CH1_Old, ZeroLevelCH1);
	
			UserIface_active = 0;
			signal_zoomed1 = true;
		}*/			
	}
	else
	{
		if (Selected_Voltage_CH2 == 11) return;
	//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
			if ((Selected_Voltage_CH2 + Rotary_Steps) < 11)
			{
				Selected_Voltage_CH2 += Rotary_Steps;       			
			}
		else Selected_Voltage_CH2 = 11;	
	
		SetSwitches(2, Selected_Voltage_CH2);
		VoltageChangedCh2 = 1;
			
		if (Cursor_Enabled)
		{
			if(FFT_Mode != FFT_OFF)
			Display::FFT_CalcCursorData();
			else
			Display::CALCCURSORDATA();

			Menu_Changed = 1;
			CursorChanged = 4;
		}
		if (QM_Enabled)
		{
			Display::CALCQMDATA();
			Menu_Changed = 1;
		}
			
		Display::DRAWSTATUS(2, 1);											// Draw Voltage Channel 1
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
			
		if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
		{
			MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}
		if (Active_Menu == 19)
		{
			New_Menu = Active_Menu;
			Menu_Changed = 1;
		}
			/*
		if (Continius == false)
		{
			if (signal_zoomed1 == false) for (cnt = 0; cnt < 16383; cnt++) SIGNAL1_IntBuf_YZoom[cnt] = (int) SIGNAL1[cnt];
	
			Voltage_Zoom(&SIGNAL1[0], &SIGNAL1_IntBuf_YZoom[0], Selected_Voltage_CH1, Selected_Voltage_CH1_Old, ZeroLevelCH1);
	
			UserIface_active = 0;
			signal_zoomed1 = true;
		}   */
	}
	
	Rotary_Steps = 0;
	ON_Zero_Channel_2();
}
//##########################################################################################################################################
//set zerolevel for channel 2 (zero wheel handler)
void Hardware::ON_Zero_Channel_2(void)
{
	//int lCH2_DAC_Correction_1, lCH2_DAC_Correction_2, lCH2_DAC_Correction_3, Virtual_ZeroLevel_Buf;
	
	//If XY-mode leave function
	//BF del if (XY_Mode) return;
	
	int rotbuf;
	
	if (FFT_Mode != FFT_OFF)
	{
		Rotary_Steps = 0;
		return;
	}
/*	
	if ((Rotary_Steps > 5) && (Rotary_Steps < 11)) rotbuf = Rotary_Steps * 3;
	else if (Rotary_Steps > 10) rotbuf = Rotary_Steps * 7;
	else rotbuf = Rotary_Steps;
*/
	//rotbuf = ((Rotary_Steps * Rotary_Steps) >> 1) + 1; 	//BF new square function characteristic
	rotbuf = ((Rotary_Steps * Rotary_Steps) >> 2) + Rotary_Steps; 	//BF new square function characteristic 1/4 * X² + x

	if (rotbuf)
	{
		if (Rotary_Direction == 0) //clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
			
			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH2 + rotbuf) < 4095) 
				{ Virtual_ZeroLevelXYCH2 += rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH2 = 4095; } //Limiter
			}
			else	//Main mode TY
			{
				if ((Virtual_ZeroLevelCH2 + rotbuf) < 4095) // 0
				{ Virtual_ZeroLevelCH2 += rotbuf;	}	
				else
				{ Virtual_ZeroLevelCH2 = 4095; } //Limiter
			}


			VS_ZeroChangedCh2 = 1;
		
			
			if ((Virtual_ZeroLevelCH2 < 4095) && (Virtual_ZeroLevelCH2 > -4095))
			{
				if (Trigger_Pos_CH2_os < 0)
				{
				while ((rotbuf > 0) && (Trigger_Pos_CH2_os != 0))
				{
					rotbuf--;
					Trigger_Pos_CH2_os++;
				}
				}
				if ((Trigger_Pos_CH2 + rotbuf) <= GRID_HEIGHT)
				{ Trigger_Pos_CH2 = Trigger_Pos_CH2 + rotbuf; }	
				else
				{
					Trigger_Pos_CH2_os = Trigger_Pos_CH2_os + (rotbuf - (GRID_HEIGHT - Trigger_Pos_CH2));
					Trigger_Pos_CH2 = GRID_HEIGHT;	
				}
			}
			
		
			if (Selected_Trigger_Source == 2)
			{
				UpdateTrigger(20);	
			}
		}
		else 	//counter clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
		
			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH2 - rotbuf) > -4095)
				{ Virtual_ZeroLevelXYCH2 -= rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH2 = -4095; }
			}
			else
			{
				if ((Virtual_ZeroLevelCH2 - rotbuf) > -4095)
				{ Virtual_ZeroLevelCH2 -= rotbuf; }	
				else
				{ Virtual_ZeroLevelCH2 = -4095; }
			}

				
			VS_ZeroChangedCh2 = 1;
		
			if ((Virtual_ZeroLevelCH2 < 4095) && (Virtual_ZeroLevelCH2 > -4095))
			{
				if (Trigger_Pos_CH2_os > 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH2_os != 0))
					{
						rotbuf--;
						Trigger_Pos_CH2_os--;
					}
				}
				if ((Trigger_Pos_CH2 - rotbuf) >= 0) Trigger_Pos_CH2 = Trigger_Pos_CH2 - rotbuf;
				else
				{
					Trigger_Pos_CH2_os = Trigger_Pos_CH2_os - (rotbuf - Trigger_Pos_CH2);
					Trigger_Pos_CH2 = 0;
				}
			}
		
			if (Selected_Trigger_Source == 2)
			{
				UpdateTrigger(21);
			}	
		}
	}
	
	if (XY_Mode)	//XY-Mode
	{
		ZeroLevelCH2 = Virtual_ZeroLevelXYCH2 + (GRID_XY / 2);
		if (ZeroLevelCH2 < 0) ZeroLevelCH2 = 0;
		if (ZeroLevelCH2 > GRID_XY) ZeroLevelCH2 = GRID_XY;
	
//BF del		Virtual_ZeroLevel_Buf = Virtual_ZeroLevelXYCH2 >> 2;
	}
	else	//TY-Mode
	{
		ZeroLevelCH2 = Virtual_ZeroLevelCH2 + (GRID_HEIGHT / 2);
		if (ZeroLevelCH2 < 0) ZeroLevelCH2 = 0;
		if (ZeroLevelCH2 > (GRID_HEIGHT + 1)) ZeroLevelCH2 = (GRID_HEIGHT + 1);
	
//BF del		Virtual_ZeroLevel_Buf = Virtual_ZeroLevelCH2 >> 2;
	}



   if (XY_Mode)
   {
		switch(Selected_Voltage_CH2)
		{
			case 0: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 1) / ZeroScaleFactor[1][0])) + 8192 + DAC_Correction[1][0]; break;//1 mV
			case 1: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 2) / ZeroScaleFactor[1][1])) + 8192 + DAC_Correction[1][1]; break;//2 mV
			case 2: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 3) / ZeroScaleFactor[1][2])) + 8192 + DAC_Correction[1][2]; break;//5 mV
			case 3: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 1) / ZeroScaleFactor[1][3])) + 8192 + DAC_Correction[1][0]; break;//10mV
			case 4: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 2) / ZeroScaleFactor[1][4])) + 8192 + DAC_Correction[1][1]; break;//20mV
			case 5: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 3) / ZeroScaleFactor[1][5])) + 8192 + DAC_Correction[1][2]; break;//50mV
			case 6: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 1) / ZeroScaleFactor[1][6])) + 8192 + DAC_Correction[1][0]; break;//100 mV
			case 7: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 2) / ZeroScaleFactor[1][7])) + 8192 + DAC_Correction[1][1]; break;//200 mV
			case 8: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 3) / ZeroScaleFactor[1][8])) + 8192 + DAC_Correction[1][2]; break;//500 mV
			case 9: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 1) / ZeroScaleFactor[1][9])) + 8192 + DAC_Correction[1][0]; break;//1 V
			case 10: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 2) / ZeroScaleFactor[1][10])) + 8192 + DAC_Correction[1][1]; break;//2V
			case 11: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH2 * 3) / ZeroScaleFactor[1][11])) + 8192 + DAC_Correction[1][2]; break;//5V
		}
	}
	else
	{
		switch(Selected_Voltage_CH2)
		{
			case 0: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 1) / ZeroScaleFactor[1][0])) + 8192 + DAC_Correction[1][0]; break;//1 mV
			case 1: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 2) / ZeroScaleFactor[1][1])) + 8192 + DAC_Correction[1][1]; break;//2 mV
			case 2: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 3) / ZeroScaleFactor[1][2])) + 8192 + DAC_Correction[1][2]; break;//5 mV
		
			case 3: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 1) / ZeroScaleFactor[1][3])) + 8192 + DAC_Correction[1][0]; break;//10 mV
			case 4: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 2) / ZeroScaleFactor[1][4])) + 8192 + DAC_Correction[1][1]; break;//20 mV
			case 5: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 3) / ZeroScaleFactor[1][5])) + 8192 + DAC_Correction[1][2]; break;//50 mV
		
			case 6: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 1) / ZeroScaleFactor[1][6])) + 8192 + DAC_Correction[1][0]; break;//100 mV
			case 7: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 2) / ZeroScaleFactor[1][7])) + 8192 + DAC_Correction[1][1]; break;//200 mV
			case 8: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 3) / ZeroScaleFactor[1][8])) + 8192 + DAC_Correction[1][2]; break;//500 mV
		
			case 9:  CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 1) / ZeroScaleFactor[1][9])) + 8192 + DAC_Correction[1][0]; break;//1 V
			case 10: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 2) / ZeroScaleFactor[1][10])) + 8192 + DAC_Correction[1][1]; break;//2 V
			case 11: CH2_DAC_Offset = int ((float (Virtual_ZeroLevelCH2 * 3) / ZeroScaleFactor[1][11])) + 8192 + DAC_Correction[1][2]; break;//5 V
		}
	}

    SetDacOffset(2);	

}
//##########################################################################################################################################
void Hardware::ON_Voltage_Channel_3(void)
{
    int cnt;
    float fvolt_factor = 0;
    float fvolt_factor2 = 0;

    int shift_cnt = 0;

    if (Channel_3_Active == false) return;

    if (Rotary_Direction == 1)
    {
        if (Selected_Voltage_CH3 == 3) return;
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
		if ((Selected_Voltage_CH3 - Rotary_Steps) > 3)
		{
			Selected_Voltage_CH3 -= Rotary_Steps;
		}
		else Selected_Voltage_CH3 = 3;
		
		SetSwitches(3, Selected_Voltage_CH3);
		VoltageChangedCh3 = 1;

        if (Cursor_Enabled)
        {
		if(FFT_Mode != FFT_OFF)
		Display::FFT_CalcCursorData();
		else
		Display::CALCCURSORDATA();

		Menu_Changed = 1;
		CursorChanged = 4;
        }

        if (QM_Enabled)
        {
            Display::CALCQMDATA();
            Menu_Changed = 1;
        }
			
        Display::DRAWSTATUS(3, 1);											// Draw Voltage Channel 1
        Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
        if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
        {
            MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
				
            New_Menu = Active_Menu;
            Menu_Changed = 1;
        }
        if (Active_Menu == 19)
        {
            New_Menu = Active_Menu;
            Menu_Changed = 1;
        }	

    }
    else
    {
        if (Selected_Voltage_CH3 == 11) return;
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
		if ((Selected_Voltage_CH3 + Rotary_Steps) < 11)
		{
			Selected_Voltage_CH3 += Rotary_Steps;       			
		}
        else Selected_Voltage_CH3 = 11;	

		SetSwitches(3, Selected_Voltage_CH3);
		VoltageChangedCh3 = 1;
			
	if (Cursor_Enabled)
        {
		if(FFT_Mode != FFT_OFF)
		Display::FFT_CalcCursorData();
		else
		Display::CALCCURSORDATA();

		Menu_Changed = 1;
		CursorChanged = 4;
        }
		if (QM_Enabled)
        {
            Display::CALCQMDATA();
            Menu_Changed = 1;
        }
			
		Display::DRAWSTATUS(3, 1);											// Draw Voltage Channel 1
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
			
		if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
		{
            MenuItemChanged[3] = 1;
            MenuItemChanged[4] = 1;
            New_Menu = Active_Menu;
            Menu_Changed = 1;
		}
		if (Active_Menu == 19)
		{
            New_Menu = Active_Menu;
            Menu_Changed = 1;
		}
 
    }

    Rotary_Steps = 0;
    ON_Zero_Channel_3();
}
//##########################################################################################################################################
//set zerolevel for channel 3 (zero wheel handler)
void Hardware::ON_Zero_Channel_3(void)
{
	//int lCH3_DAC_Correction_1, lCH3_DAC_Correction_2, lCH3_DAC_Correction_3, Virtual_ZeroLevel_Buf;
	
	//If XY-mode leave function
	//BF del if (XY_Mode) return;
	
	int rotbuf;

	if (FFT_Mode != FFT_OFF)
	{
		Rotary_Steps = 0;
		return;
	}

/*	
	if ((Rotary_Steps > 5) && (Rotary_Steps < 11)) rotbuf = Rotary_Steps * 3;
	else if (Rotary_Steps > 10) rotbuf = Rotary_Steps * 7;
	else rotbuf = Rotary_Steps;
*/	
	//rotbuf = ((Rotary_Steps * Rotary_Steps) >> 1) + 1; 	//BF new square function characteristic
	rotbuf = ((Rotary_Steps * Rotary_Steps) >> 2) + Rotary_Steps; 	//BF new square function characteristic 1/4 * X² + x

	if (rotbuf)
	{
		if (Rotary_Direction == 0)	//clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }

			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH3 - rotbuf) > -4095)
				{ Virtual_ZeroLevelXYCH3 -= rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH3 = -4095; }  
			}
			else	//Main mode TY
			{
				if ((Virtual_ZeroLevelCH3 + rotbuf) < 4095) // 0
				{ Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3 + rotbuf;	}	
				else
				{ Virtual_ZeroLevelCH3 = 4095; } //Limiter
			}
			VS_ZeroChangedCh3 = 1;
		

			if ((Virtual_ZeroLevelCH3 < 4095) && (Virtual_ZeroLevelCH3 > -4095))
			{
				if (Trigger_Pos_CH3_os < 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH3_os != 0))
					{
						rotbuf--;
						Trigger_Pos_CH3_os++;
					}
				}
				if ((Trigger_Pos_CH3 + rotbuf) <= GRID_HEIGHT)
				 Trigger_Pos_CH3 = Trigger_Pos_CH3 + rotbuf;	// BF old 386
				else
				{
					Trigger_Pos_CH3_os = Trigger_Pos_CH3_os + (rotbuf - (GRID_HEIGHT - Trigger_Pos_CH3));	// BF old 386
					Trigger_Pos_CH3 = GRID_HEIGHT;								// BF old 386
				}
			}
		
			if (Selected_Trigger_Source == 3)
			{ UpdateTrigger(20); }
		}
		else	//counter clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }
			
			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH3 + rotbuf) < 4095)
				{ Virtual_ZeroLevelXYCH3 += rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH3 = 4095; }
			}
			else
			{
				if ((Virtual_ZeroLevelCH3 - rotbuf) > -4095)
				{ Virtual_ZeroLevelCH3 -= rotbuf;	}	
				else
				{ Virtual_ZeroLevelCH3 = -4095;  }
			}

				
			VS_ZeroChangedCh3 = 1;
		
			if ((Virtual_ZeroLevelCH3 < 4095) && (Virtual_ZeroLevelCH3 > -4095))
			{
				if (Trigger_Pos_CH3_os > 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH3_os != 0))
					{
						rotbuf--;
						Trigger_Pos_CH3_os--;
					}
				}
				if ((Trigger_Pos_CH3 - rotbuf) >= 0) Trigger_Pos_CH3 = Trigger_Pos_CH3 - rotbuf;
				else
				{
					Trigger_Pos_CH3_os = Trigger_Pos_CH3_os - (rotbuf - Trigger_Pos_CH3);
					Trigger_Pos_CH3 = 0;
				}
			}
		
			if (Selected_Trigger_Source == 3)
			{
				UpdateTrigger(21);
			}	
		}
	}

	if (XY_Mode)	//XY-Mode
	{
		ZeroLevelCH3 = Virtual_ZeroLevelXYCH3 + (GRID_XY / 2);
		if (ZeroLevelCH3 < 0) ZeroLevelCH3 = 0;
		if (ZeroLevelCH3 > GRID_XY) ZeroLevelCH3 = GRID_XY;
	
//BF del		Virtual_ZeroLevel_Buf = Virtual_ZeroLevelXYCH3 >> 2;
	}
	else	//TY-Mode
	{
		ZeroLevelCH3 = Virtual_ZeroLevelCH3 + (GRID_HEIGHT / 2);
		if (ZeroLevelCH3 < 0) ZeroLevelCH3 = 0;
		if (ZeroLevelCH3 > (GRID_HEIGHT + 1)) ZeroLevelCH3 = (GRID_HEIGHT + 1);
	
//BF del		Virtual_ZeroLevel_Buf = Virtual_ZeroLevelCH3 >> 2;
	}


   if (XY_Mode)
    {
        switch(Selected_Voltage_CH3)
        {
            case 0: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 1) / ZeroScaleFactor[2][0])) + 8192 + DAC_Correction[2][0]; break;//  1 mV
            case 1: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 2) / ZeroScaleFactor[2][1])) + 8192 + DAC_Correction[2][1]; break;//  2 mV
            case 2: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 3) / ZeroScaleFactor[2][2])) + 8192 + DAC_Correction[2][2]; break;//  5 mV
            case 3: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 1) / ZeroScaleFactor[2][3])) + 8192 + DAC_Correction[2][0]; break;// 10 mV
            case 4: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 2) / ZeroScaleFactor[2][4])) + 8192 + DAC_Correction[2][1]; break;// 20 mV
            case 5: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 3) / ZeroScaleFactor[2][5])) + 8192 + DAC_Correction[2][2]; break;// 50 mV
            case 6: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 1) / ZeroScaleFactor[2][6])) + 8192 + DAC_Correction[2][0]; break;//100 mV
            case 7: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 2) / ZeroScaleFactor[2][7])) + 8192 + DAC_Correction[2][1]; break;//200 mV
            case 8: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 3) / ZeroScaleFactor[2][8])) + 8192 + DAC_Correction[2][2]; break;//500 mV
            case 9: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 1) / ZeroScaleFactor[2][9])) + 8192 + DAC_Correction[2][0]; break;//  1 V
            case 10: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 2) / ZeroScaleFactor[2][10])) + 8192 + DAC_Correction[2][1]; break;//2 V
            case 11: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH3 * 3) / ZeroScaleFactor[2][11])) + 8192 + DAC_Correction[2][2]; break;//5 V
        }
    }
    else
    {
        switch(Selected_Voltage_CH3)
        {
            case 0: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 1) / ZeroScaleFactor[2][0])) + 8192 + DAC_Correction[2][0]; break;//   1 mV
            case 1: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 2) / ZeroScaleFactor[2][1])) + 8192 + DAC_Correction[2][1]; break;//   2 mV
            case 2: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 3) / ZeroScaleFactor[2][2])) + 8192 + DAC_Correction[2][2]; break;//   5 mV

            case 3: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 1) / ZeroScaleFactor[2][3])) + 8192 + DAC_Correction[2][0]; break;//  10 mV
            case 4: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 2) / ZeroScaleFactor[2][4])) + 8192 + DAC_Correction[2][1]; break;//  20 mV
            case 5: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 3) / ZeroScaleFactor[2][5])) + 8192 + DAC_Correction[2][2]; break;//  50 mV

            case 6: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 1) / ZeroScaleFactor[2][6])) + 8192 + DAC_Correction[2][0]; break;// 100 mV
            case 7: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 2) / ZeroScaleFactor[2][7])) + 8192 + DAC_Correction[2][1]; break;// 200 mV
            case 8: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 3) / ZeroScaleFactor[2][8])) + 8192 + DAC_Correction[2][2]; break;// 500 mV

            case 9:  CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 1) / ZeroScaleFactor[2][9])) + 8192 + DAC_Correction[2][0]; break;//  1 V
            case 10: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 2) / ZeroScaleFactor[2][10])) + 8192 + DAC_Correction[2][1]; break;// 2 V
            case 11: CH3_DAC_Offset = int ((float (Virtual_ZeroLevelCH3 * 3) / ZeroScaleFactor[2][11])) + 8192 + DAC_Correction[2][2]; break;// 5 V
        }
    }

    SetDacOffset(3);	
}
//##########################################################################################################################################
void Hardware::ON_Voltage_Channel_4(void)
{
    int cnt;
    float fvolt_factor = 0;
    float fvolt_factor2 = 0;

    int shift_cnt = 0;

    if (Channel_4_Active == false) return;

    if (Rotary_Direction == 1)
    {
        if (Selected_Voltage_CH4 == 3) return;
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
		if ((Selected_Voltage_CH4 - Rotary_Steps) > 3)
		{
			Selected_Voltage_CH4 -= Rotary_Steps;
		}
		else Selected_Voltage_CH4 = 3;
		
		SetSwitches(4, Selected_Voltage_CH4);
		VoltageChangedCh4 = 1;

        if (Cursor_Enabled)
        {
		if(FFT_Mode != FFT_OFF)
		Display::FFT_CalcCursorData();
		else
		Display::CALCCURSORDATA();

		Menu_Changed = 1;
		CursorChanged = 4;
        }

        if (QM_Enabled)
        {
            Display::CALCQMDATA();
            Menu_Changed = 1;
        }
			
        Display::DRAWSTATUS(4, 1);											// Draw Voltage Channel 1
        Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
        if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
        {
            MenuItemChanged[3] = 1;
			MenuItemChanged[4] = 1;
				
            New_Menu = Active_Menu;
            Menu_Changed = 1;
        }
        if (Active_Menu == 19)
        {
            New_Menu = Active_Menu;
            Menu_Changed = 1;
        }	
             /*
            if (Continius == false)
            {
                if (signal_zoomed1 == false) for (cnt = 0; cnt < 16383; cnt++) SIGNAL1_IntBuf_YZoom[cnt] = (int) SIGNAL1[cnt];

                Voltage_Zoom(&SIGNAL1[0], &SIGNAL1_IntBuf_YZoom[0], Selected_Voltage_CH1, Selected_Voltage_CH1_Old, ZeroLevelCH1);

                UserIface_active = 0;
                signal_zoomed1 = true;
            }*/			
    }
    else
    {
        if (Selected_Voltage_CH4 == 11) return;
//		if (ZeroPopupChanged) { Display::DRAWZEROPOPDOWN(); }
		if ((Selected_Voltage_CH4 + Rotary_Steps) < 11)
		{
			Selected_Voltage_CH4 += Rotary_Steps;       			
		}
        else Selected_Voltage_CH4 = 11;	

		SetSwitches(4, Selected_Voltage_CH4);
		VoltageChangedCh4 = 1;
			
	if (Cursor_Enabled)
        {
		if(FFT_Mode != FFT_OFF)
		Display::FFT_CalcCursorData();
		else
		Display::CALCCURSORDATA();

		Menu_Changed = 1;
		CursorChanged = 4;
        }
		if (QM_Enabled)
        {
            Display::CALCQMDATA();
            Menu_Changed = 1;
        }
			
		Display::DRAWSTATUS(4, 1);											// Draw Voltage Channel 1
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
			
		if ((Active_Menu == 16) || (MenuButtonCheck(-1)))
		{
            MenuItemChanged[3] = 1;
            MenuItemChanged[4] = 1;
            New_Menu = Active_Menu;
            Menu_Changed = 1;
		}
		if (Active_Menu == 19)
		{
            New_Menu = Active_Menu;
            Menu_Changed = 1;
		}
                  /*
            if (Continius == false)
            {
                if (signal_zoomed1 == false) for (cnt = 0; cnt < 16383; cnt++) SIGNAL1_IntBuf_YZoom[cnt] = (int) SIGNAL1[cnt];

                Voltage_Zoom(&SIGNAL1[0], &SIGNAL1_IntBuf_YZoom[0], Selected_Voltage_CH1, Selected_Voltage_CH1_Old, ZeroLevelCH1);

                UserIface_active = 0;
                signal_zoomed1 = true;
            }   */
    }

    Rotary_Steps = 0;
    ON_Zero_Channel_4();
}
//##########################################################################################################################################
//set zerolevel for channel 4 (zero wheel handler)
void Hardware::ON_Zero_Channel_4(void)
{
	//int lCH4_DAC_Correction_1, lCH4_DAC_Correction_2, lCH4_DAC_Correction_3, Virtual_ZeroLevel_Buf;
	
	//If XY-mode leave function
	//BF del if (XY_Mode) return;
	
	int rotbuf;

	if (FFT_Mode != FFT_OFF)
	{
		Rotary_Steps = 0;
		return;
	}

/*	
	if ((Rotary_Steps > 5) && (Rotary_Steps < 11)) rotbuf = Rotary_Steps * 3;
	else if (Rotary_Steps > 10) rotbuf = Rotary_Steps * 7;
	else rotbuf = Rotary_Steps;
*/	
	//rotbuf = ((Rotary_Steps * Rotary_Steps) >> 1) + 1; 	//BF new square function characteristic
	rotbuf = ((Rotary_Steps * Rotary_Steps) >> 2) + Rotary_Steps; 	//BF new square function characteristic 1/4 * X² + x


	if (rotbuf)
	{
		if (Rotary_Direction == 0)	//clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }

			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH4 + rotbuf) < 4095)
				{ Virtual_ZeroLevelXYCH4 += rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH4 = 4095; }      //Limiter
			}
			else	//Main mode TY
			{
				if ((Virtual_ZeroLevelCH4 + rotbuf) < 4095) // 0
				{ Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4 + rotbuf;	}	
				else
				{ Virtual_ZeroLevelCH4 = 4095; } //Limiter
			}

				
			VS_ZeroChangedCh4 = 1;
		
			if ((Virtual_ZeroLevelCH4 < 4095) && (Virtual_ZeroLevelCH4 > -4095))
			{
				if (Trigger_Pos_CH4_os < 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH4_os != 0))
					{
						rotbuf--;
						Trigger_Pos_CH4_os++;
					}
				}
				if ((Trigger_Pos_CH4 + rotbuf) <= GRID_HEIGHT) Trigger_Pos_CH4 = Trigger_Pos_CH4 + rotbuf;	// BF old 386
				else
				{
					Trigger_Pos_CH4_os = Trigger_Pos_CH4_os + (rotbuf - (GRID_HEIGHT - Trigger_Pos_CH4));	// BF old 386
					Trigger_Pos_CH4 = GRID_HEIGHT;								// BF old 386
				}
			}
		
			if (Selected_Trigger_Source == 4)
			{ UpdateTrigger(20); }
		}
		else	//counter clockwise rotary direction
		{
			if (MenuButtonCheck(-1)) { New_Menu = Active_Menu; Menu_Changed = 1; }

			if (XY_Mode)	//XY-mode
			{
				if ((Virtual_ZeroLevelXYCH4 - rotbuf) > -4095)
				{ Virtual_ZeroLevelXYCH4 -= rotbuf; }		
				else
				{ Virtual_ZeroLevelXYCH4 = -4095; }
			}
			else
			{
				if ((Virtual_ZeroLevelCH4 - rotbuf) > -4095)
				{ Virtual_ZeroLevelCH4 -= rotbuf;	}	
				else
				{ Virtual_ZeroLevelCH4 = -4095; }
			}

				
			VS_ZeroChangedCh4 = 1;
		
			if ((Virtual_ZeroLevelCH4 < 4095) && (Virtual_ZeroLevelCH4 > -4095))
			{
				if (Trigger_Pos_CH4_os > 0)
				{
					while ((rotbuf > 0) && (Trigger_Pos_CH4_os != 0))
					{
						rotbuf--;
						Trigger_Pos_CH4_os--;
					}
				}
				if ((Trigger_Pos_CH4 - rotbuf) >= 0) Trigger_Pos_CH4 = Trigger_Pos_CH4 - rotbuf;
				else
				{
					Trigger_Pos_CH4_os = Trigger_Pos_CH4_os - (rotbuf - Trigger_Pos_CH4);
					Trigger_Pos_CH4 = 0;
				}
			}
		
			if (Selected_Trigger_Source == 4)
			{
				UpdateTrigger(21);
			}	
		}
	}

	if (XY_Mode)	//XY-Mode
	{
		ZeroLevelCH4 = Virtual_ZeroLevelXYCH4 + (GRID_XY / 2);
		if (ZeroLevelCH4 < 0) ZeroLevelCH4 = 0;
		if (ZeroLevelCH4 > GRID_XY) ZeroLevelCH4 = GRID_XY;
	
//BF del		Virtual_ZeroLevel_Buf = Virtual_ZeroLevelXYCH4 >> 2;
	}
	else	//TY-Mode
	{
		ZeroLevelCH4 = Virtual_ZeroLevelCH4 + (GRID_HEIGHT / 2);
		if (ZeroLevelCH4 < 0) ZeroLevelCH4 = 0;
		if (ZeroLevelCH4 > (GRID_HEIGHT + 1)) ZeroLevelCH4 = (GRID_HEIGHT + 1);
	
//BF del		Virtual_ZeroLevel_Buf = Virtual_ZeroLevelCH4 >> 2;
	}

   if (XY_Mode)
    {
        switch(Selected_Voltage_CH4)
        {
            case 0: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 1) / ZeroScaleFactor[3][0])) + 8192 + DAC_Correction[3][0]; break;//  1 mV
            case 1: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 2) / ZeroScaleFactor[3][1])) + 8192 + DAC_Correction[3][1]; break;//  2 mV
            case 2: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 3) / ZeroScaleFactor[3][2])) + 8192 + DAC_Correction[3][2]; break;//  5 mV
            case 3: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 1) / ZeroScaleFactor[3][3])) + 8192 + DAC_Correction[3][0]; break;// 10 mV
            case 4: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 2) / ZeroScaleFactor[3][4])) + 8192 + DAC_Correction[3][1]; break;// 20 mV
            case 5: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 3) / ZeroScaleFactor[3][5])) + 8192 + DAC_Correction[3][2]; break;// 50 mV
            case 6: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 1) / ZeroScaleFactor[3][6])) + 8192 + DAC_Correction[3][0]; break;//100 mV
            case 7: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 2) / ZeroScaleFactor[3][7])) + 8192 + DAC_Correction[3][1]; break;//200 mV
            case 8: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 3) / ZeroScaleFactor[3][8])) + 8192 + DAC_Correction[3][2]; break;//500 mV
            case 9: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 1) / ZeroScaleFactor[3][9])) + 8192 + DAC_Correction[3][0]; break;//  1 V
            case 10: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 2) / ZeroScaleFactor[3][10])) + 8192 + DAC_Correction[3][1]; break;//2 V
            case 11: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelXYCH4 * 3) / ZeroScaleFactor[3][11])) + 8192 + DAC_Correction[3][2]; break;//5 V
        }
    }
    else
    {
        switch(Selected_Voltage_CH4)
        {
            case 0: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 1) / ZeroScaleFactor[3][0])) + 8192 + DAC_Correction[3][0]; break;//   1 mV
            case 1: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 2) / ZeroScaleFactor[3][1])) + 8192 + DAC_Correction[3][1]; break;//   2 mV
            case 2: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 3) / ZeroScaleFactor[3][2])) + 8192 + DAC_Correction[3][2]; break;//   5 mV

            case 3: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 1) / ZeroScaleFactor[3][3])) + 8192 + DAC_Correction[3][0]; break;//  10 mV
            case 4: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 2) / ZeroScaleFactor[3][4])) + 8192 + DAC_Correction[3][1]; break;//  20 mV
            case 5: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 3) / ZeroScaleFactor[3][5])) + 8192 + DAC_Correction[3][2]; break;//  50 mV

            case 6: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 1) / ZeroScaleFactor[3][6])) + 8192 + DAC_Correction[3][0]; break;// 100 mV
            case 7: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 2) / ZeroScaleFactor[3][7])) + 8192 + DAC_Correction[3][1]; break;// 200 mV
            case 8: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 3) / ZeroScaleFactor[3][8])) + 8192 + DAC_Correction[3][2]; break;// 500 mV

            case 9:  CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 1) / ZeroScaleFactor[3][9])) + 8192 + DAC_Correction[3][0]; break;//  1 V
            case 10: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 2) / ZeroScaleFactor[3][10])) + 8192 + DAC_Correction[3][1]; break;// 2 V
            case 11: CH4_DAC_Offset = int ((float (Virtual_ZeroLevelCH4 * 3) / ZeroScaleFactor[3][11])) + 8192 + DAC_Correction[3][2]; break;// 5 V
        }
    }

    SetDacOffset(4);	
}
//##########################################################################################################################################

void Hardware::HandleMainWheel(char Direction)						// Main Wheel Handler
{
	bool doit = false;
	bool changing = false;
	double voltoff = 0;
	double timeoff = 0;
	short pos = 0;
	
	int rot_buf = 0;
	int buf_int = 0; 	
	float buf_float = 0;
	
	int rbuf = Rotary_Steps;
    		
//	Display::DRAWP(550, 50, 80, 20, 0, 6);
//	sprintf(speedt, "%i\n" , Speed);
//	Display::TEXTOUTxvbig(speedt, 550, 50, 1, 6);				// Draw the Ground Sign
	
	Rot_Time = 0;
	
//	if (RoteryChanged == 0) return;
	
	switch(Active_Menu)
	{      /*
		// Averaging
		case 0:
		{
			if (MenuItemPushed[3] == 0) doit = true;
			MenuButtonCheck(3);

            changing = false;
            while (rbuf > 0)
            {
                switch(Direction)
                {
                    case 0: if (MenuStatus[MENU_ACQUIRE][2] > 74) {MenuStatus[MENU_ACQUIRE][2]--; changing = true;} break;
                    case 1: if (MenuStatus[MENU_ACQUIRE][2] < 81) {MenuStatus[MENU_ACQUIRE][2]++; changing = true;} break;
                }
                rbuf--;
			}
			
			if (changing)
			{
                Display::DRAWP(248, 454, 60, 14, 0, Buffer_UI2Plane);
                Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_ACQUIRE][2]], 219 + MenuDataDef[MenuStatus[MENU_ACQUIRE][2]], 455, 1, Buffer_UI2Plane);
                Display::DRAWSTATUS(Active_Menu, 1);			
            }
			
			switch(MenuStatus[MENU_ACQUIRE][2])
			{
                case 74 : Average_Max = 1; break;
                case 75 : Average_Max = 2; break;
                case 76 : Average_Max = 4; break;
                case 77 : Average_Max = 8; break;
                case 78 : Average_Max = 16; break;
                case 79 : Average_Max = 32; break;
                case 80 : Average_Max = 64; break;
                case 81 : Average_Max = 128; break;
                case 82 : Average_Max = 256; break;
                case 83 : Average_Max = 512; break;
                case 84 : Average_Max = 1024; break;
                case 85 : Average_Max = 2048; break;
                case 86 : Average_Max = 4096; break;
                case 87 : Average_Max = 8192; break;
                case 88 : Average_Max = 16384; break;
            }
            Average_Cnt = 0;
						
			Menu_Changed = 1;

			break;
		}
        */	
		// Channel 1
		case 1:
		{
            		if (Channel_1_Active == 0) return;

			if (MenuItemPushed[3] == 0) doit = true;
			MenuButtonCheck(3);

		changing = false;
		while (rbuf > 0)
		{
			switch(Direction)
			{
				    case 0: if (MenuStatus[MENU_CHANNEL1][3] > 104) {MenuStatus[MENU_CHANNEL1][3]--; changing = true;} break;
				    case 1: if (MenuStatus[MENU_CHANNEL1][3] < 113) {MenuStatus[MENU_CHANNEL1][3]++; changing = true;} break;
			}
			rbuf--;
		}
			
		if (changing)
		{
			Display::DRAWP(345, 454, 60, 14, 0, Buffer_UI2Plane);
			Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_CHANNEL1][3]], 354, 455, 1, Buffer_UI2Plane);
			Display::DRAWSTATUS(Active_Menu, 1);		
			Display::DRAWSTATUS(6, 0);				
		}                		
			
			if (Cursor_Enabled)
			{
               			CursorChanged = 4;
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();
			}
			if (QM_Enabled)
			{					
				Display::CALCQMDATA();
			}
			
			//Display::CALCTRIGGER();
			TriggerLevelChanged = 1;
			Display::StatusUpdate();
			
			Menu_Changed = 1;

			break;
		}
		
		// Channel 2
		case 2:
		{
            	if (Channel_2_Active == 0) return;

			if (MenuItemPushed[3] == 0) doit = true;
			MenuButtonCheck(3);
			
            	changing = false;
		while (rbuf > 0)
		{
			switch(Direction)
			{
					case 0: if (MenuStatus[MENU_CHANNEL2][3] > 104) {MenuStatus[MENU_CHANNEL2][3]--; changing = true;} break;
					case 1: if (MenuStatus[MENU_CHANNEL2][3] < 113) {MenuStatus[MENU_CHANNEL2][3]++; changing = true;} break;
			}
                	rbuf--;
		}
			
			if (changing)
			{
				Display::DRAWP(345, 454, 60, 14, 0, Buffer_UI2Plane);
				Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_CHANNEL2][3]], 354, 455, 1, Buffer_UI2Plane);
				Display::DRAWSTATUS(Active_Menu, 1);		
				Display::DRAWSTATUS(6, 0);				
            		}

			if (Cursor_Enabled)
			{
                		CursorChanged = 4;
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();
			}
			if (QM_Enabled)
			{					
				Display::CALCQMDATA();
			}		
			
			//Display::CALCTRIGGER();
			TriggerLevelChanged = 1;
			Display::StatusUpdate();			

            		Menu_Changed = 1;	

			break;
		}
		
		// Channel 3
		case 3:
		{
            		if (Channel_3_Active == 0) return;

			if (MenuItemPushed[3] == 0) doit = true;
			MenuButtonCheck(3);
			
            changing = false;
            while (rbuf > 0)
            {
                switch(Direction)
                {
				    case 0: if (MenuStatus[MENU_CHANNEL3][3] > 104) {MenuStatus[MENU_CHANNEL3][3]--; changing = true;} break;
				    case 1: if (MenuStatus[MENU_CHANNEL3][3] < 113) {MenuStatus[MENU_CHANNEL3][3]++; changing = true;} break;
                }
                rbuf--;
			}
			
			if (changing)
			{
                Display::DRAWP(345, 454, 60, 14, 0, Buffer_UI2Plane);
                Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_CHANNEL3][3]], 354, 455, 1, Buffer_UI2Plane);
                Display::DRAWSTATUS(Active_Menu, 1);		
                Display::DRAWSTATUS(6, 0);				
            }
			
			if (Cursor_Enabled)
			{
                		CursorChanged = 4;
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();

			}
			if (QM_Enabled)
			{					
				Display::CALCQMDATA();
			}
			
			//Display::CALCTRIGGER();
			TriggerLevelChanged = 1;
			Display::StatusUpdate();
            			
			Menu_Changed = 1;

			break;
		}
		
		// Channel 4
		case 4:
		{
			if (Channel_4_Active == 0) return;
		
					if (MenuItemPushed[3] == 0) doit = true;
					MenuButtonCheck(3);
					
			changing = false;
			while (rbuf > 0)
			{
				switch(Direction)
				{
						case 0: if (MenuStatus[MENU_CHANNEL4][3] > 104) {MenuStatus[MENU_CHANNEL4][3]--; changing = true;} break;
						case 1: if (MenuStatus[MENU_CHANNEL4][3] < 113) {MenuStatus[MENU_CHANNEL4][3]++; changing = true;} break;
				}
				rbuf--;
					}
					
					if (changing)
					{
				Display::DRAWP(345, 454, 60, 14, 0, Buffer_UI2Plane);
				Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_CHANNEL4][3]], 354, 455, 1, Buffer_UI2Plane);
				Display::DRAWSTATUS(Active_Menu, 1);		
				Display::DRAWSTATUS(6, 0);				
			}
					
			if (Cursor_Enabled)
			{
				CursorChanged = 4;
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();

			}
			if (QM_Enabled)
			{					
				Display::CALCQMDATA();
			}	
			
			//Display::CALCTRIGGER();
			TriggerLevelChanged = 1;
			Display::StatusUpdate();			
		
			Menu_Changed = 1;		

			break;
		}
		
		// Display Menu -> grid brightness
		case 5:
		{
			if (MenuItemPushed[2] == 0) doit = true;
			MenuButtonCheck(2);
			
			changing = false;
			
			while (rbuf > 0)
			{		
			
				switch(Direction)
				{
					case 0:
					{
						if (MenuStatus[MENU_TIMEBASE][1] == 1)	// delayed mode
						{
							if (GridColorArrayPos_Delayed > 0)
							{
								GridColorArrayPos_Delayed--;
								GridColor_Val = GridColorArray[GridColorArrayPos_Delayed];
				
								changing = true;
							}
						}
						else	// main/XY
						{
							if (GridColorArrayPos > 0)
							{
								GridColorArrayPos--;
								GridColor_Val = GridColorArray[GridColorArrayPos];
				
								changing = true;
							}				
						}				
						break;
					}
			
					case 1:
					{
						if (MenuStatus[MENU_TIMEBASE][1] == 1)	// delayed mode
						{
							if (GridColorArrayPos_Delayed < 3)
							{
								GridColorArrayPos_Delayed++;
								GridColor_Val = GridColorArray[GridColorArrayPos_Delayed];
				
								changing = true;		
							}				
						}
						else	// main/XY
						{
							if (GridColorArrayPos < 3)
							{
								GridColorArrayPos++;
								GridColor_Val = GridColorArray[GridColorArrayPos];
										
								changing = true;
							}				
						}
						break;
					}				
				}
				rbuf--;
			}			
			
			if (changing)
			{			
				SetupADC();
								
				MenuStatus[MENU_DISPLAY][2] = GridColorArrayPos + 133;
								
				Display::DRAWP(240, 454, 60, 14, 0, Buffer_UI2Plane);
				Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_DISPLAY][2]], 218 + MenuDataDef[MenuStatus[MENU_DISPLAY][2]], 455, 1, Buffer_UI2Plane);			
			}			
			
#ifdef _Debug_			
			if (Debug_Mode) printf("GV %i : %2x\n", GridColorArrayPos, GridColor_Val);
#endif			
			//ResetTimer();
			
			MenuItemChanged[2] = 1;
			Menu_Changed = 1;

			break;
		}
		
		// Save / Recall Menu
		case 8:
		{		
			if (MenuItemPushed[0] == 0) doit = true;
			MenuButtonCheck(0);
			
			while (rbuf > 0)
			{				
				switch(Direction)
				{
				case 0: if (SavePointer > 1) SavePointer--; break;
				case 1: if (SavePointer < 80) SavePointer++; break;
				}
				rbuf--;
			}
		
			MenuItemChanged[0] = 1;
								
			New_Menu = 8;
			Menu_Changed = 1;
		
			break;	            			
		}
		
		// Edge
		case 12:
		{
            if (EdgeToggle == 0)
            {
                if (MenuItemPushed[3] == 0) doit = true;
                MenuButtonCheck(3);

                while (rbuf > 0)
                {
                    if (Direction)
                    {
                        if ((HoldOff_Expo == 4) && (HoldOff_Value == 300)) break;
                        HoldOff_Value = HoldOff_Value + HoldOff_Steps;
                    }
                    else
                    {
                        if ((HoldOff_Expo == 1) && (HoldOff_Value == 0)) break;
                        HoldOff_Value = HoldOff_Value - HoldOff_Steps;
                    }

                    if (HoldOff_Value > 1000)
                    {
                        HoldOff_Value = 1;
                        HoldOff_Steps = 1;
                        HoldOff_Expo++;
                    }
/*                  else if ((HoldOff_Value > 100) && (HoldOff_Expo != 1))
                    {
                        HoldOff_Steps = 10;
                    }*/
                    else if (HoldOff_Value <= 0)
                    {
                        if (HoldOff_Expo > 2)
                        {
                            HoldOff_Expo--;
                            HoldOff_Value = 999;
                            HoldOff_Steps = 1;
                        }
                        else if (HoldOff_Expo > 1)
                        {
                            HoldOff_Expo = 1;
                            HoldOff_Value = 960;
                            HoldOff_Steps = 40;
                        }
                    }

                    switch(HoldOff_Expo)
                    {
                        case 1:
                        {
                            //HoldOff.Write_StepSize(0.00000004);
                            HoldOff.Write_Value((float) HoldOff_Value / (float) 1000000000);
                            break;
                        }
                        case 2:
                        {
                            //HoldOff.Write_StepSize(0.0000001);
                            HoldOff.Write_Value((float) HoldOff_Value / (float) 1000000);
                            break;
                        }
                        case 3:
                        {
                            //HoldOff.Write_StepSize(0.001);
                            HoldOff.Write_Value((float) HoldOff_Value / (float) 1000);
                            break;
                        }
                        case 4:
                        {
                            //HoldOff.Write_StepSize(1);
                            HoldOff.Write_Value((float) HoldOff_Value);
                            break;
                        }
                    }
                    rbuf--;
                }

                HoldOff.RenderText();

                if (HoldOff_Value) trig_holdoff_reg = (unsigned long) (HoldOff.Read_Value() / (float) 0.000000008);
                else trig_holdoff_reg = 0x00000000;

                UpdateTrigger(26);
            }
            else if (EdgeToggle == 1)
            {
                if (MenuItemPushed[4] == 0) doit = true;
                MenuButtonCheck(4);

                changing = false;

                while (rbuf > 0)
                {
                    switch(Direction)
                    {
                        case 0: if (MenuStatus[MENU_TRIGGERMODE][4] > 104) {MenuStatus[MENU_TRIGGERMODE][4]--; changing = true;} break;
				        case 1: if (MenuStatus[MENU_TRIGGERMODE][4] < 113) {MenuStatus[MENU_TRIGGERMODE][4]++; changing = true;} break;
                    }
                    rbuf--;
                }

                if (changing)
                {
                    Display::DRAWP(442, 454, 60, 14, 0, Buffer_UI2Plane);
                    Display::TEXTOUTxvbig(MenuData[MenuStatus[MENU_TRIGGERMODE][4]], 444, 455, 1, Buffer_UI2Plane);
                }
            }


			TriggerLevelChanged = 1;
			Display::StatusUpdate();
            Menu_Changed = 1;		

			break;
		}		
			
		
	// Pre Trigger
        case 14:
	{	
		if (XY_Mode) return;

		if(FFT_Mode != FFT_OFF) return;
		
		//BFTEST	
		//printf("Trig_Pos_Mem : %d  Rotation buffer : %d Trig_Pos_Display : %d\r\n", Trig_Pos_Mem, rot_buf, Trig_Pos_Display);
	
		while (rbuf > 0)
		{
			//BF -> test rot_buf = (int) ZFT_float * Rotary_Steps;
			if (rot_buf < 1) rot_buf = Rotary_Steps; // For interpolation
			
			if (Rotary_Direction)
			{
				if ((Trig_Pos_Mem + (int) rot_buf) < 0x3FFF)
				 Trig_Pos_Mem = Trig_Pos_Mem + rot_buf;
				else
				 Trig_Pos_Mem = 0x3FFF;
			}
			else
			{
				if ((Trig_Pos_Mem - (int) rot_buf) >= 0x0064) 
				 Trig_Pos_Mem = Trig_Pos_Mem - rot_buf;
				else
				 Trig_Pos_Mem = 0x0064;
			}
			
			Recalc_Trigger();
			
			SetupADC();
			
			TriggerOffsetChanged = true;	//BF where used???
			rbuf--;
		}
	
		//printf("Trig_Pos_Mem : %d  Rotation buffer : %d Trig_Pos_Display : %d\r\n", Trig_Pos_Mem, rot_buf, Trig_Pos_Display);
            
  	
		if (Memory_Window_visible)
		Display::DRAWMEMORY(0, 0, 1);	//BF draw grid position in memory
		else
		Display::DRAWMEMORY(0, 1, 1);
	


		Display::CALCPRETRIGGER();
		Display::DRAW_ALL_CURSOR();
	
		MenuItemPushed[4] = 1;
		MenuButtonCheck(4);
	
		Menu_Changed = 1;
	
		break;
        }

        // Pulse/Width
		case 15:
		{
            if (MenuStatus[MENU_PULSEWIDTH][2] == 3)     // range
            {
#ifdef _Debug_
                printf("A Dir %d PT %d \n", Direction, PulseToggle);
                printf("A PV11 %d PE11 %d PS11 %d\n", Pulse11_Value, Pulse11_Expo, Pulse11_Steps);
                printf("A PV12 %d PE12 %d PS12 %d\n", Pulse12_Value, Pulse12_Expo, Pulse12_Steps);
#endif

                if (PulseToggle == 1)
                {
                    while (rbuf > 0)
                    {
                        if (Direction)
                        {
                            if ((Pulse11_Expo == 3) && (Pulse11_Value >= 268)) break;
                            // if ((Pulse12_Expo == 3) && (Pulse12_Value >= 268)) break;
                            Pulse11_Value = Pulse11_Value + Pulse11_Steps;
                        }
                        else
                        {
                            if ((Pulse11_Expo == 1) && (Pulse11_Value <= 16)) break;
                            Pulse11_Value = Pulse11_Value - Pulse11_Steps;
                        }

                        if (Pulse11_Value >= 1000)
                        {
                            Pulse11_Value = 1;
                            Pulse11_Steps = 1;
                            Pulse11_Expo++;
                            /*
                            if ((Pulse11_Value >= Pulse12_Value) && (Pulse11_Expo == Pulse12_Expo))
                            {
                            printf("Update Val2 1\n");

                            Pulse12_Value = 2;
                            Pulse12_Steps = 1;
                            Pulse12_Expo = Pulse11_Expo;

                            switch(Pulse12_Expo)
                            {
                                case 1:
                                {
                                    Pulse12.Write_Value((float) Pulse12_Value / (float) 1000000000);
                                    break;
                                }
                                case 2:
                                {
                                    Pulse12.Write_Value((float) Pulse12_Value / (float) 1000000);
                                    break;
                                }
                                case 3:
                                {
                                    Pulse12.Write_Value((float) Pulse12_Value / (float) 1000);
                                    break;
                                }
                            }
                            Pulse12.RenderText();
                            } */
                        }
                        else if ((Pulse11_Value >= 100) && (Pulse11_Expo == 2))
                        {
                            Pulse11_Steps = 1;
                        }
                        else if (Pulse11_Value <= 0)
                        {
                            if (Pulse11_Expo == 3)
                            {
                                Pulse11_Expo--;
                                Pulse11_Value = 999;
                                Pulse11_Steps = 1;
                            }
                            else if (Pulse11_Expo == 2)
                            {
                                Pulse11_Expo = 1;
                                Pulse11_Value = 992;
                                Pulse11_Steps = 8;
                            }
                        }
                        rbuf--;
                    }

                    switch(Pulse11_Expo)
                    {
                        case 1:
                        {
                            Pulse11.Write_Value((float) Pulse11_Value / (float) 1000000000);
                            break;
                        }
                        case 2:
                        {
                            Pulse11.Write_Value((float) Pulse11_Value / (float) 1000000);
                            break;
                        }
                        case 3:
                        {
                            Pulse11.Write_Value((float) Pulse11_Value / (float) 1000);
                            break;
                        }
                    }

                    Pulse11.RenderText();
                }
                else
                {
                    while (rbuf > 0)
                    {
                        if (Direction)
                        {
                            if ((Pulse12_Expo == 2) && (Pulse12_Value >= 524)) break;
                            Pulse12_Value = Pulse12_Value + Pulse12_Steps;
                        }
                        else
                        {
                            if ((Pulse12_Expo == 1) && (Pulse12_Value <= 8)) break;
                            Pulse12_Value = Pulse12_Value - Pulse12_Steps;
                        }

                        if (Pulse12_Value >= 1000)
                        {
                            Pulse12_Value = 1;
                            Pulse12_Steps = 1;
                            Pulse12_Expo++;
                        }
                        else if ((Pulse12_Value >= 100) && (Pulse12_Expo == 2))
                        {
                            Pulse12_Steps = 1;
                        }
                        else if (Pulse12_Value <= 0)
                        {
                            if (Pulse12_Expo == 3)
                            {
                                Pulse12_Expo--;
                                Pulse12_Value = 999;
                                Pulse12_Steps = 1;
                            }
                            else if (Pulse12_Expo == 2)
                            {
                                Pulse12_Expo = 1;
                                Pulse12_Value = 992;
                                Pulse12_Steps = 8;
                            }
                        }
                        rbuf--;
                    }

                    switch(Pulse12_Expo)
                    {
                        case 1:
                        {
                            Pulse12.Write_Value((float) Pulse12_Value / (float) 1000000000);
                            break;
                        }
                        case 2:
                        {
                            Pulse12.Write_Value((float) Pulse12_Value / (float) 1000000);
                            break;
                        }
                        case 3:
                        {
                            Pulse12.Write_Value((float) Pulse12_Value / (float) 1000);
                            break;
                        }
                    }
                    Pulse12.RenderText();
                }

                trig_range_reg = (unsigned int) (Pulse12.Read_Value() / (float) 0.000000008);
                trig_width_reg = (unsigned int) (Pulse11.Read_Value() / (float) 0.000000008);
#ifdef _Debug_
                printf("B PV11 %d PE11 %d PS11 %d\n", Pulse11_Value, Pulse11_Expo, Pulse11_Steps);
                printf("B PV12 %d PE12 %d PS12 %d\n", Pulse12_Value, Pulse12_Expo, Pulse12_Steps);
#endif
                MenuItemChanged[3] = 1;
                MenuItemChanged[4] = 1;
            }
            else
            {
                if (PulseToggle == 1)
                {
                    while (rbuf > 0)
                    {
                        if (Direction)
                        {
                            if ((Pulse21_Expo == 3) && (Pulse21_Value >= 268)) break;
                            Pulse21_Value = Pulse21_Value + Pulse21_Steps;
                        }
                        else
                        {
                            if ((Pulse21_Expo == 1) && (Pulse21_Value <= 16)) break;
                            Pulse21_Value = Pulse21_Value - Pulse21_Steps;
                        }

                        if (Pulse21_Value >= 1000)
                        {
                            Pulse21_Value = 1;
                            Pulse21_Steps = 1;
                            Pulse21_Expo++;
                        }
                        else if ((Pulse21_Value >= 100) && (Pulse21_Expo == 2))
                        {
                            Pulse21_Steps = 10;
                        }
                        else if (Pulse21_Value <= 0)
                        {
                            if (Pulse21_Expo > 2)
                            {
                                Pulse21_Expo--;
                                Pulse21_Value = 999;
                                Pulse21_Steps = 1;
                            }
                            else if (Pulse21_Expo > 1)
                            {
                                Pulse21_Expo = 1;
                                Pulse21_Value = 992;
                                Pulse21_Steps = 8;
                            }
                        }
                        rbuf--;
                    }

                    switch(Pulse21_Expo)
                    {
                        case 1:
                        {
                            Pulse21.Write_StepSize(0.000000008);
                            Pulse21.Write_Value((float) Pulse21_Value / (float) 1000000000);
                            break;
                        }
                        case 2:
                        {
                            Pulse21.Write_StepSize(0.0000001);
                            Pulse21.Write_Value((float) Pulse21_Value / (float) 1000000);
                            break;
                        }
                        case 3:
                        {
                            Pulse21.Write_StepSize(0.001);
                            Pulse21.Write_Value((float) Pulse21_Value / (float) 1000);
                            break;
                        }
                    }

                    Pulse21.RenderText();

                    trig_width_reg = (unsigned int) ((Pulse21.Read_Value() / (float) 0.000000008));
                    MenuItemChanged[3] = 1;
                }
                else
                {
                    while (rbuf > 0)
                    {
                        if (Direction)
                        {
                            if ((Pulse22_Expo == 3) && (Pulse22_Value >= 268)) break;
                            Pulse22_Value = Pulse22_Value + Pulse22_Steps;
                        }
                        else
                        {
                            if ((Pulse22_Expo == 1) && (Pulse22_Value <= 16)) break;
                            Pulse22_Value = Pulse22_Value - Pulse22_Steps;
                        }

                        if (Pulse22_Value >= 1000)
                        {
                            Pulse22_Value = 1;
                            Pulse22_Steps = 1;
                            Pulse22_Expo++;
                        }
                        else if ((Pulse22_Value >= 100) && (Pulse22_Expo == 2))
                        {
                            Pulse22_Steps = 10;
                        }
                        else if (Pulse22_Value <= 0)
                        {
                            if (Pulse22_Expo > 2)
                            {
                                Pulse22_Expo--;
                                Pulse22_Value = 999;
                                Pulse22_Steps = 1;
                            }
                            else if (Pulse22_Expo > 1)
                            {
                                Pulse22_Expo = 1;
                                Pulse22_Value = 992;
                                Pulse22_Steps = 8;
                            }
                        }
                        rbuf--;
                    }

                    switch(Pulse22_Expo)
                    {
                        case 1:
                        {
                            Pulse22.Write_StepSize(0.000000008);
                            Pulse22.Write_Value((float) Pulse22_Value / (float) 1000000000);
                            break;
                        }
                        case 2:
                        {
                            Pulse22.Write_StepSize(0.0000001);
                            Pulse22.Write_Value((float) Pulse22_Value / (float) 1000000);
                            break;
                        }
                        case 3:
                        {
                            Pulse22.Write_StepSize(0.001);
                            Pulse22.Write_Value((float) Pulse22_Value / (float) 1000);
                            break;
                        }
                    }

                    Pulse22.RenderText();

                    trig_width_reg = (unsigned int) ((Pulse22.Read_Value() / (float) 0.000000008));
                    MenuItemChanged[4] = 1;
                }
            }

            New_Menu = 15;
            Menu_Changed = 1;
            UpdateTrigger(27);

			break;
		}

        case 16: // Main Wheel -> Cursor ( comment TMW added)
	{		
            if (Cursor_Enabled == 0) break;

		    rot_buf = (int) ZFT_float;
		
		    if (rot_buf < 1) rot_buf = Rotary_Steps; // For interpolation (TMW enabled this line)		
 
            if ((rbuf > 5) && (rbuf < 11)) rbuf = rbuf * 3;
            else if (rbuf > 10) rbuf = rbuf * 7;


//BF test for later	rotbuf = ((Rotary_Steps * Rotary_Steps) >> 1) + 1; 	//BF new square function characteristic 1/2 * X²


            while (rbuf > 0)
            {            				
  				if (Cursor_Horizontal_Active == 3)	
				{
				    if (XY_Mode == 1)
				    {

                    switch(Cursor_Vertical_Active)
					{
						case 1:
						{
							CursorChanged = 1;
							
							if (MenuItemPushed[1] == 0) doit = true;
							MenuButtonCheck(1);
							
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Vertical_Position_Real_XY_1 - rot_buf) > DrawXYOffsetX1) Cursor_Vertical_Position_Real_XY_1 = Cursor_Vertical_Position_Real_XY_1 - rot_buf;

									break;
								}
								case 1:
								{
									if ((Cursor_Vertical_Position_Real_XY_1 + rot_buf) < DrawXYOffsetX2) Cursor_Vertical_Position_Real_XY_1 = Cursor_Vertical_Position_Real_XY_1 + rot_buf;

									break;
								}							
							}

							break;
						}
						case 2:
						{
							CursorChanged = 2;
							
							if (MenuItemPushed[2] == 0) doit = true;
							MenuButtonCheck(2);
							
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Vertical_Position_Real_XY_2 - rot_buf) > DrawXYOffsetX1) Cursor_Vertical_Position_Real_XY_2 = Cursor_Vertical_Position_Real_XY_2 - rot_buf;

									break;
								}
								case 1:
								{
									if ((Cursor_Vertical_Position_Real_XY_2 + rot_buf) < DrawXYOffsetX2) Cursor_Vertical_Position_Real_XY_2 = Cursor_Vertical_Position_Real_XY_2 + rot_buf;

									break;
								}							
							}
							break;
						}
						case 4:
						{
							CursorChanged = 1;
							
							//if (MenuItemPushed[5] == 0) doit = true;
							//MenuButtonCheck(5);
							MenuItemPushed[1] = 1;
							MenuItemChanged[1] = 1;
							MenuItemChanged[2] = 1;
							
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Vertical_Position_Real_XY_1 - rot_buf) > DrawXYOffsetX1) Cursor_Vertical_Position_Real_XY_1 = Cursor_Vertical_Position_Real_XY_1 - rot_buf;
                                    if ((Cursor_Vertical_Position_Real_XY_2 - rot_buf) > DrawXYOffsetX1) Cursor_Vertical_Position_Real_XY_2 = Cursor_Vertical_Position_Real_XY_2 - rot_buf;

									break;
								}
								case 1:
								{
									if ((Cursor_Vertical_Position_Real_XY_1 + rot_buf) < DrawXYOffsetX2) Cursor_Vertical_Position_Real_XY_1 = Cursor_Vertical_Position_Real_XY_1 + rot_buf;
                                    if ((Cursor_Vertical_Position_Real_XY_2 + rot_buf) < DrawXYOffsetX2) Cursor_Vertical_Position_Real_XY_2 = Cursor_Vertical_Position_Real_XY_2 + rot_buf;

									break;
								}							
							}
							break;
						}                        						
					}				
				
				    }
				    else // TMW comment added: else means XY_Mode ==0
				    {
				
					switch(Cursor_Vertical_Active)
					{
						case 1: // TMW comment added: 1 means Cursor X1 is active
						{
							CursorChanged = 1;					
							if (MenuItemPushed[1] == 0) doit = true;
							MenuButtonCheck(1);
							
                            //if (Cursor_Vertical_Position_Real1 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real1 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            //if (Cursor_Vertical_Position_Real1 > (600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real1 = 600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
							
							if (Cursor_Vertical_Position_Real1 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) 
								Cursor_Vertical_Position_Real1 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            if (Cursor_Vertical_Position_Real1 > (SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float))) 
								Cursor_Vertical_Position_Real1 = SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float);

							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Vertical_Position_Real1 - rot_buf) > 0) Cursor_Vertical_Position_Real1 = Cursor_Vertical_Position_Real1 - rot_buf;		
 				             	
									break;
								}
								case 1:
								{
									if ((Cursor_Vertical_Position_Real1 + rot_buf) < 16384) Cursor_Vertical_Position_Real1 = Cursor_Vertical_Position_Real1 + rot_buf;		

									break;
								}
							}

							break;
						}
						case 2: // TMW comment added: 2 means Cursor X2 is active
						{
							CursorChanged = 2;
							
							if (MenuItemPushed[2] == 0) doit = true;
							MenuButtonCheck(2);
							
                            //if (Cursor_Vertical_Position_Real2 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            //if (Cursor_Vertical_Position_Real2 > (600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = 600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);		

							if (Cursor_Vertical_Position_Real2 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            if (Cursor_Vertical_Position_Real2 > (SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float);

							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Vertical_Position_Real2 - rot_buf) > 0) Cursor_Vertical_Position_Real2 = Cursor_Vertical_Position_Real2 - rot_buf;

									break;
								}
								case 1:
								{
									if ((Cursor_Vertical_Position_Real2 + rot_buf) < 16384) Cursor_Vertical_Position_Real2 = Cursor_Vertical_Position_Real2 + rot_buf;

									break;
								}
							}
							break;
						}	
						case 4:
						{
							CursorChanged = 1;					
							//if (MenuItemPushed[5] == 0) doit = true;
							MenuItemPushed[1] = 1;
							//MenuButtonCheck(5);
				            MenuItemChanged[1] = 1;
				            MenuItemChanged[2] = 1;							
						    /*
                            if (Cursor_Vertical_Position_Real1 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real1 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            if (Cursor_Vertical_Position_Real1 > (600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real1 = 600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
						
                            if (Cursor_Vertical_Position_Real2 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);		
                            if (Cursor_Vertical_Position_Real2 > (600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = 600 + SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);		
						    */
							if (Cursor_Vertical_Position_Real1 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real1 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            if (Cursor_Vertical_Position_Real1 > (SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real1 = SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float);							
							
							if (Cursor_Vertical_Position_Real2 < (SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float);
                            if (Cursor_Vertical_Position_Real2 > (SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float))) Cursor_Vertical_Position_Real2 = SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float);
						
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Vertical_Position_Real1 - rot_buf) > 0) Cursor_Vertical_Position_Real1 = Cursor_Vertical_Position_Real1 - rot_buf;
                                    if ((Cursor_Vertical_Position_Real2 - rot_buf) > 0) Cursor_Vertical_Position_Real2 = Cursor_Vertical_Position_Real2 - rot_buf;		

									break;
								}
								case 1:
								{
									if ((Cursor_Vertical_Position_Real1 + rot_buf) < 16384) Cursor_Vertical_Position_Real1 = Cursor_Vertical_Position_Real1 + rot_buf;		
                                    if ((Cursor_Vertical_Position_Real2 + rot_buf) < 16384) Cursor_Vertical_Position_Real2 = Cursor_Vertical_Position_Real2 + rot_buf;

									break;
								}
							}

							break;
						}                        					
					}
                    } // if (XY_Mode == 1)				
				}
				
				else if (Cursor_Vertical_Active == 3)
				{
					switch(Cursor_Horizontal_Active)
					{
						case 1:
						{
							CursorChanged = 4;
							
							if (MenuItemPushed[3] == 0) doit = true;
							MenuButtonCheck(3);
							
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Horizontal_Position_Real1 + 1) < 384) Cursor_Horizontal_Position_Real1 = Cursor_Horizontal_Position_Real1 + 1;

									break;
								}							
								case 1:
								{
									if ((Cursor_Horizontal_Position_Real1 - 1) > 0) Cursor_Horizontal_Position_Real1 = Cursor_Horizontal_Position_Real1 - 1;

									break;
								}
							}
#ifdef _Debug_Cursor_							
							if (Debug_Mode) printf("Cur H1 Pos %i\n", Cursor_Horizontal_Position_Real1);
#endif							
							break;
						}
						case 2:
						{
							CursorChanged = 5;
							
							if (MenuItemPushed[4] == 0) doit = true;
							MenuButtonCheck(4);
							
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Horizontal_Position_Real2 + 1) < 384) Cursor_Horizontal_Position_Real2 = Cursor_Horizontal_Position_Real2 + 1;

									break;
								}							
								case 1:
								{
									if ((Cursor_Horizontal_Position_Real2 - 1) > 0) Cursor_Horizontal_Position_Real2 = Cursor_Horizontal_Position_Real2 - 1;

									break;
								}
							}
#ifdef _Debug_Cursor_							
							if (Debug_Mode) printf("Cur H2 Pos %i\n", Cursor_Horizontal_Position_Real2);
#endif							
							break;
						}
						case 4:
						{
							CursorChanged = 4;
							
							if (MenuItemPushed[5] == 0) doit = true;
							MenuButtonCheck(5);
				            MenuItemChanged[3] = 1;
				            MenuItemChanged[4] = 1;
							
							switch(Direction)
							{
								case 0:
								{
									if ((Cursor_Horizontal_Position_Real1 + 1) < 384) Cursor_Horizontal_Position_Real1 = Cursor_Horizontal_Position_Real1 + 1;
                                    if ((Cursor_Horizontal_Position_Real2 + 1) < 384) Cursor_Horizontal_Position_Real2 = Cursor_Horizontal_Position_Real2 + 1;

									break;
								}							
								case 1:
								{
									if ((Cursor_Horizontal_Position_Real1 - 1) > 0) Cursor_Horizontal_Position_Real1 = Cursor_Horizontal_Position_Real1 - 1;
                                    if ((Cursor_Horizontal_Position_Real2 - 1) > 0) Cursor_Horizontal_Position_Real2 = Cursor_Horizontal_Position_Real2 - 1;

									break;
								}
							}
#ifdef _Debug_Cursor_							
							if (Debug_Mode) printf("Cur H1H2 Pos %i  %i\n", Cursor_Horizontal_Position_Real1, Cursor_Horizontal_Position_Real2);
#endif							
							break;
						}                        						
					}			
				}	

                rbuf--;
            }
							
			if (Cursor_Enabled)
			{	
				if(FFT_Mode != FFT_OFF)
				Display::FFT_CalcCursorData();
				else
				Display::CALCCURSORDATA();
				
				Display::DRAW_ALL_CURSOR();
			}		
			
			break;	
		} // Ende Cursor Menu
		
		
		case 19:
		{
            if (QM_Enabled == 0) break; 		

            while (rbuf > 0)
            {
                if ((MenuPopupActive > -1) && (MenuPopupActive != 4)) Display::DRAWMENUPOPDOWN();
                if (MenuPopupActive == 4)
                {

                    pos = -1;
                    if (Direction == 0) MenuPopupStep(4, &MenuStatus[MENU_QUICKMEASUREMENT][1], &MenuStatus[MENU_QUICKMEASUREMENT][2], &MenuStatus[MENU_QMDELAY][4], 19, 52, 2);
                    else if (Direction == 1) MenuPopupStep(4, &MenuStatus[MENU_QUICKMEASUREMENT][1], &MenuStatus[MENU_QUICKMEASUREMENT][2], &MenuStatus[MENU_QMDELAY][4], 19, 52, 1);

                    MenuStatus[21][4] = MenuStatus[MENU_QMDELAY][4];

                    if (((MenuStatus[MENU_QUICKMEASUREMENT][1] - 52) == 4) || ((MenuStatus[MENU_QUICKMEASUREMENT][1] - 52) == 13))
                    {
                        if (MenuStatus[MENU_QUICKMEASUREMENT][4] == 244) MenuItemChanged[4] = 1;
                        MenuStatus[MENU_QUICKMEASUREMENT][4] = 242;
                    }
                    else
                    {
                        if (MenuStatus[MENU_QUICKMEASUREMENT][4] == 242) MenuItemChanged[4] = 1;
                        MenuStatus[MENU_QUICKMEASUREMENT][4] = 244;
                    }

                    MenuItemChanged[1] = 1;
                    MenuItemChanged[2] = 1;
						
                    New_Menu = 19;
                    Menu_Changed = 1;
                }
                else if (MenuPopupActive == -1)
                {
                    New_Menu = 19;
                    Menu_Changed = 1;
                }


                rbuf--;
            }

            Display::DRAWMENUPOPUP(4);		

            ResetTimer();
/*			
		
			if (QM_Enabled)
			{					
				Display::CALCQMDATA();
				if (doit == 0) ResetTimer();
			}						
*/
            break;
        }		

		case 22:
		{
			if (QM_Enabled == 0) break;
		
			while (rbuf > 0)
			{
				switch(Quick_Measure_Threshold_btn_select)
				{
					case 1:
					{
						MenuButtonCheck(2);
						//MenuItemPushed[2] = 1;
						//MenuItemChanged[2] = 1;
							
						QM_Threshold_lower.DoStep(Direction);
						QM_Threshold_lower.RenderText();
			
						break;
					}
					case 2:
					{
						MenuButtonCheck(3);
			
						//MenuItemPushed[3] = 1;
						//MenuItemChanged[3] = 1;
			
						//ResetTimer();
					
						QM_Threshold_middle.DoStep(Direction);
						QM_Threshold_middle.RenderText();
			
						break;
					}
					case 3:
					{
						MenuButtonCheck(4);
					
						//MenuItemPushed[4] = 1;
						//MenuItemChanged[4] = 1;
						//ResetTimer();
			
						QM_Threshold_upper.DoStep(Direction);
						QM_Threshold_upper.RenderText();
			
						break;
					}
				}
				rbuf--;
			}
		
			ResetTimer();
			New_Menu = 22;
			Menu_Changed = 1;

            	
			break;
		}
		
		//-----------------------------------------------------------
		// Math Settings - Scale and Offset
		//-----------------------------------------------------------
		case 29:
		{		
			// set new scale factors
			if (MathToggle == 0)
			{
				if (MenuItemPushed[0] == 0) doit = true;
				
				MenuButtonCheck(0);
					
				while (rbuf > 0)
				{				
					switch(Direction)
					{
						case 0:
						{
							if (MenuStatus[MENU_MATH][2] == 1){ if (math_mul_scale < 181) math_mul_scale++; }
							else if (MenuStatus[MENU_MATH][3] == 1){ if (math_sub_scale < 165) math_sub_scale++; }
							else if (MenuStatus[MENU_MATH][4] == 1){ if (math_add_scale < 165) math_add_scale++; }
							break;
						}

						case 1:
						{
							if (MenuStatus[MENU_MATH][2] == 1){ if (math_mul_scale > 166) math_mul_scale--; }
							else if (MenuStatus[MENU_MATH][3] == 1){ if (math_sub_scale > 153) math_sub_scale--; }
							else if (MenuStatus[MENU_MATH][4] == 1){ if (math_add_scale > 153) math_add_scale--; }
							break;
						}
					}
					rbuf--;
				}

                		MenuItemChanged[0] = 1;
			}

			// set new offsets
			if (MathToggle == 1)
			{
				if (MenuItemPushed[1] == 0) doit = true;
				MenuButtonCheck(1);
					
				//if ((rbuf > 5) && (rbuf < 11)) rbuf = rbuf * 3;
				//else if (rbuf > 10) rbuf = rbuf * 7;
printf("Rotation Buffer = %d\n",rbuf);
				if (MenuStatus[MENU_MATH][2] == 1) // function key 3 - multiply
				{
					//change offset value
					while (rbuf > 0)
					{
						if (Direction)
						{ Math_Mul_Offset += math_voltage_factor[math_mul_scale - 166]; }
						else
						{ Math_Mul_Offset -= math_voltage_factor[math_mul_scale - 166]; }
						rbuf--;
					}
/*
					//limiter -> max 20 000 000 / min -20 000 000
					if (Math_Mul_Offset > (math_voltage_factor[15] * (GRID_HEIGHT/2)))
					Math_Mul_Offset = (math_voltage_factor[15] * (GRID_HEIGHT/2));
					else if (Math_Mul_Offset < (-1 * math_voltage_factor[15] * (GRID_HEIGHT/2))) 
					Math_Mul_Offset = -1 * (math_voltage_factor[15] * (GRID_HEIGHT/2));
*/
printf("Mul Offset = %d\n",Math_Mul_Offset);
					//display offset value	
					//Math_Offset_mul.Write_StepSize(1);
					Math_Offset_mul.Write_Value(float((float)Math_Mul_Offset / (float)50000));
					Math_Offset_mul.RenderText();

				}
				else if (MenuStatus[MENU_MATH][3] == 1) // function key 4 - subtract
				{
//change offset value
					while (rbuf > 0)
					{
						if (Direction)
						{ Math_Sub_Offset += math_voltage_factor[math_sub_scale - 150]; }
						else
						{ Math_Sub_Offset -= math_voltage_factor[math_sub_scale - 150]; }
						rbuf--;
					}
/*
					//limiter -> max 20 000 000 / min -20 000 000
					if (Math_Sub_Offset > (math_voltage_factor[15] * (GRID_HEIGHT/2)))
					Math_Sub_Offset = (math_voltage_factor[15] * (GRID_HEIGHT/2));
					else if (Math_Sub_Offset < (-1 * math_voltage_factor[15] * (GRID_HEIGHT/2))) 
					Math_Sub_Offset = -1 * (math_voltage_factor[15] * (GRID_HEIGHT/2));
*/
printf("Sub Offset = %d\n",Math_Sub_Offset);
					//display offset value	
					//Math_Offset_sub.Write_StepSize(1);
					Math_Offset_sub.Write_Value(float((float)Math_Sub_Offset / (float)50000));
					Math_Offset_sub.RenderText();
	             		}
               
				else if (MenuStatus[MENU_MATH][4] == 1) // add
				{
					//change offset value
					while (rbuf > 0)
					{
						if (Direction)
						{ Math_Add_Offset += math_voltage_factor[math_add_scale - 150]; }
						else
						{ Math_Add_Offset -= math_voltage_factor[math_add_scale - 150]; }
						rbuf--;
					}
/*
					//limiter -> max 20 000 000 / min -20 000 000
					if (Math_Add_Offset > (math_voltage_factor[15] * (GRID_HEIGHT/2)))
					Math_Add_Offset = (math_voltage_factor[15] * (GRID_HEIGHT/2));
					else if (Math_Add_Offset < (-1 * math_voltage_factor[15] * (GRID_HEIGHT/2))) 
					Math_Add_Offset = -1 * (math_voltage_factor[15] * (GRID_HEIGHT/2));
*/
printf("Add Offset = %d\n",Math_Mul_Offset);
					//display offset value	
					//Math_Offset_add.Write_StepSize(1);
					Math_Offset_add.Write_Value(float((float)Math_Add_Offset / (float)50000));
					Math_Offset_add.RenderText();	
		
				}

		                MenuItemChanged[1] = 1;
			}
			
                        			
			New_Menu = 29;
			Menu_Changed = 1;
/*
printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
printf("math_sub_scale %d\n", math_sub_scale);
printf("math_add_scale %d\n", math_add_scale);
printf("math_mul_scale %d\n", math_mul_scale);

printf("Math_Off_Sub_Value %d\n", Math_Off_Sub_Value);
printf("Math_Off_Add_Value %d\n", Math_Off_Add_Value);
printf("Math_Off_Mul_Value %d\n", Math_Off_Mul_Value);
printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
*/
            		break;
		}//Math settings end		
		
		
	}	
	
	if (doit)
	{
		//printf("Do it\n");
		//ResetTimer();
		Display::DRAWSTATUS(Active_Menu, 1);		
		Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel
		
		New_Menu = Active_Menu;
		Menu_Changed = 1;
	}
	UpdateMenuTextPlane = true;	

}//HandleMainWheel end

void Hardware::Zero_Levels_Center(void)								// 
{
	//backup zerolevels
	ZeroLevelCH1_bak = ZeroLevelCH1;
	ZeroLevelCH2_bak = ZeroLevelCH2;
	ZeroLevelCH3_bak = ZeroLevelCH3;
	ZeroLevelCH4_bak = ZeroLevelCH4;

	Virtual_ZeroLevelCH1_bak = Virtual_ZeroLevelCH1;
	Virtual_ZeroLevelCH2_bak = Virtual_ZeroLevelCH2;
	Virtual_ZeroLevelCH3_bak = Virtual_ZeroLevelCH3;
	Virtual_ZeroLevelCH4_bak = Virtual_ZeroLevelCH4;


	//set zerolevels to the middle of the grid
	ZeroLevelCH1 = GRID_HEIGHT / 2;
	ZeroLevelCH2 = GRID_HEIGHT / 2;
	ZeroLevelCH3 = GRID_HEIGHT / 2;
	ZeroLevelCH4 = GRID_HEIGHT / 2;

	Virtual_ZeroLevelCH1 = 0;
	Virtual_ZeroLevelCH2 = 0;
	Virtual_ZeroLevelCH3 = 0;
	Virtual_ZeroLevelCH4 = 0;

	//activate new settings
	Rotary_Steps = 0;
	ON_Zero_Channel_1();
	Rotary_Steps = 0;
	ON_Zero_Channel_2();

	if (NumberOfChannels > 2)	// 4 channel version
	{	
		//activate new settings
		Rotary_Steps = 0;
		ON_Zero_Channel_3();
		Rotary_Steps = 0;
		ON_Zero_Channel_4();
	}
}

void Hardware::Zero_Levels_Restore(void)							// 
{
	//restore zerolevels
	ZeroLevelCH1 = ZeroLevelCH1_bak;
	ZeroLevelCH2 = ZeroLevelCH2_bak;
	ZeroLevelCH3 = ZeroLevelCH3_bak;
	ZeroLevelCH4 = ZeroLevelCH4_bak;

	Virtual_ZeroLevelCH1 = Virtual_ZeroLevelCH1_bak;
	Virtual_ZeroLevelCH2 = Virtual_ZeroLevelCH2_bak;
	Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3_bak;
	Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4_bak;

	//activate new settings
	Rotary_Steps = 0;
	ON_Zero_Channel_1();
	Rotary_Steps = 0;
	ON_Zero_Channel_2();

	if (NumberOfChannels > 2)	// 4 channel version
	{	
		//activate new settings
		Rotary_Steps = 0;
		ON_Zero_Channel_3();
		Rotary_Steps = 0;
		ON_Zero_Channel_4();
	}

}
//###########################################################################################################################################

void Hardware::DoEnableUARTInterrupt(void)						// Enable service routine
{
	nr_installuserisr(na_uart1_irq, ISR_UART, (int)puart);				// Install ISR for UART

	puart->np_uartcontrol = np_uartcontrol_irrdy_mask;				// Enable Control Bits
#ifdef _Debug_IRQ_	
	if (Debug_Mode) printf("\nUART interrupt enabled.\n"); 				// print on console
#endif	
}
	
void Hardware::DoDisableUARTInterrupt(void)						// Disable service routine
{
	puart->np_uartcontrol = 0;							// Disable Control Bits
	nr_installuserisr(na_uart1_irq, 0, 0); 						// Install empty routine for uart irq
}
//###########################################################################################################################################
//BF cleaned ISR from useless overhead and transferred buttonhandler to keyboard interface
void Hardware::ISR_UART(int context)							// UART Interrupt subroutine
{
	char rxchar;
	int status;

	status = puart->np_uartstatus;	
	rxchar = puart->np_uartrxdata;	
	
	puart->np_uartstatus = 0;
    	
	
	if (status & np_uartstatus_rrdy_mask)
	{
		UART_RXData  = rxchar;
		UART_NewData = 1;
		UI_request   = 1;
	}
}

void Hardware::DoEnableUART2Interrupt(void)						// Enable service routine
{
	uart2_count = 0;
	
	nr_installuserisr(na_uart_usb_irq, ISR_UART2, (int)puart2);			// Install ISR for UART2

	puart2->np_uartcontrol = np_uartcontrol_irrdy_mask;				// Enable Control Bits
#ifdef _Debug_IRQ_	
	if (Debug_Mode) printf("\nUART USB interrupt enabled.\n"); 			// print on console
#endif	
}
	
void Hardware::DoDisableUART2Interrupt(void)						// Disable service routine
{
	puart2->np_uartcontrol = 0;							// Disable Control Bits
	nr_installuserisr(na_uart_usb_irq, 0, 0); 					// Install empty routine for uart2 irq
}

void Hardware::ISR_UART2(int context)							// UART Interrupt subroutine
{
	char rxchar = -1;
	int status;
	int x;	
		
//	if (init_done) Reset_the_Watchdog();
		
	status = puart2->np_uartstatus;	
	rxchar = puart2->np_uartrxdata;	
	
	//BF del tc_test_var2++;
	
	puart2->np_uartstatus = 0;									// Clear Interrupt condition
	   	
	if (status & np_uartstatus_rrdy_mask)
	{
		uart2_buffer[uart2_count] = rxchar;
			
		uart2_count++;
	}	
	
	if (uart2_buffer[0] != 37) uart2_count = 0;
	
	if (uart2_count == 37)
	{		
		InterpretUART(uart2_buffer);
		
		uart2_count = 0;
		
		//config_changed = true;
#ifdef _Debug_USB_		
		if (Debug_Mode) printf("USB DATA Received\n");
#endif	
#ifdef _Debug_IRQ_		
		if (Debug_Mode) printf("USB DATA Received\n");
#endif		
	}
	
	puart2->np_uartstatus = 0;
}

void Hardware::InterpretUART(volatile unsigned char data[37])
{	
	char cnt, result_buf = 0;
	char CalcBuf;
	int	ix, CalcBufInt;
	long int libuf;
	
    	int lcnt = 0;
    	unsigned long buflong, buflong1, buflong2 = 0;	
	
	unsigned long *prog_flash_adr_buf;
	unsigned long *prog_flash_adr_buf2;
    	unsigned char add_buf = 0;

    	char DataStr[50];
	
//	unsigned char SendBuffer[37] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
#ifdef _Debug_USB_	
//	printf("Received Command %d  Which %d  dl %d  dh %d  dxl %d  dxh %d  dext %d\n", data[0], data[1], data[2], data[3], data[4], data[5], data[6]);
	if (Debug_Mode) printf("Received %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n", data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23], data[24], data[25], data[26], data[27]);
#endif
    if ((data[1] == 3) && (data[2] == 4))
    {
        //start_acq->np_piodata = 0x01;				//start record Port On
        //start_acq->np_piodata = 0x00;				//start record Port Off			
    }
    else
    {
	switch(data[1])
	{
		case 1: 											// Send Screen Shot
		{
			if (data[2] == 0) SendShot();
			else SendSWShot();
			break;
		}
		case 2: 											// Send Data
		{
			
			//switch(which)
			switch(data[2])
			{
				
				case 0: 									//
				{
					//
					break;
				}
				
				case 1:										// Main Time Base
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];
					send_buffer[2] = Selected_Timebase;
					
					SendData(send_buffer);

					break;
				}
				
				case 2:										// Expand Time Base
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];
					send_buffer[2] = Selected_Expand_Timebase;
					
					SendData(send_buffer);
					break;
				}
							
				case 8:
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];
					send_buffer[2] = GridColor_Val;
					
					SendData(send_buffer);
					break;
				}				
				
				case 9:										// Main Time Base
				{
					
					for (cnt = 0; cnt < 32; cnt++)
					{
						send_buffer[0] = 3;						// Command Write Data
						send_buffer[1] = data[2];
						
						send_buffer[2] = cnt;
					
						send_buffer[3] = LogicData[cnt] & 0xFF;
						send_buffer[4] = (LogicData[cnt] & 0xFF00) >> 8;
										
						SendData(send_buffer);
					}

					break;
				}				
				
				case 12:									// Channel 1
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];
										
					CalcBuf = Selected_Voltage_CH1;
									
					if ((MenuStatus[MENU_CHANNEL1][0] - 6) == 0) CalcBuf = CalcBuf | 0x80;   // Ground
					if ((MenuStatus[MENU_CHANNEL1][0] - 6) == 1) CalcBuf = CalcBuf | 0x40;   // AC
							
					send_buffer[2] = CalcBuf;

					CalcBuf = (char) MenuStatus[MENU_CHANNEL1][3] - 101;
					
//					if ((MenuStatus[MENU_CHANNEL1][4] - 99) == 1) CalcBuf = CalcBuf | 0x80;

					send_buffer[3] = CalcBuf;				
					
					send_buffer[4] = (char) (ZeroLevelCH1 / 1.5);
					
					SendData(send_buffer);
					
					break;
				}
				case 13:									// Channel 2
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];
										
					CalcBuf = Selected_Voltage_CH2;
					if ((MenuStatus[MENU_CHANNEL2][0] - 6) == 0) CalcBuf = CalcBuf | 0x80;   // Ground
					if ((MenuStatus[MENU_CHANNEL2][0] - 6) == 1) CalcBuf = CalcBuf | 0x40;   // AC
			
					send_buffer[2] = CalcBuf;

					CalcBuf = (char) MenuStatus[MENU_CHANNEL2][3] - 101;
				//	if ((MenuStatus[MENU_CHANNEL2][4] - 99) == 1) CalcBuf = CalcBuf || 0x80;

					send_buffer[3] = CalcBuf;
					
					send_buffer[4] = (char) (ZeroLevelCH2 / 1.5);
					
					SendData(send_buffer);
												
					break;
				}
				case 14:									// Channel 3
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];					
					
					CalcBuf = Selected_Voltage_CH3;
					if ((MenuStatus[MENU_CHANNEL3][0] - 6) == 0) CalcBuf = CalcBuf | 0x80;   // Ground
					if ((MenuStatus[MENU_CHANNEL3][0] - 6) == 1) CalcBuf = CalcBuf | 0x40;   // AC
			
					send_buffer[2] = CalcBuf;

					CalcBuf = (char) MenuStatus[MENU_CHANNEL3][3] - 101;
				//	if ((MenuStatus[MENU_CHANNEL3][4] - 99) == 1) CalcBuf = CalcBuf | 0x80;

					send_buffer[3] = CalcBuf;
					
					
					
					
					send_buffer[4] = (char) (ZeroLevelCH3 / 1.5);
					
					SendData(send_buffer);
												
					break;
				}
				case 15:									// Channel 4
				{
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];					
					
					CalcBuf = Selected_Voltage_CH4;
					if ((MenuStatus[MENU_CHANNEL4][0] - 6) == 0) CalcBuf = CalcBuf | 0x80;   // Ground
					if ((MenuStatus[MENU_CHANNEL4][0] - 6) == 1) CalcBuf = CalcBuf | 0x40;   // AC
			
					send_buffer[2] = CalcBuf;

					CalcBuf = (char) MenuStatus[MENU_CHANNEL4][3] - 101;
				//	if ((MenuStatus[MENU_CHANNEL4][4] - 99) == 1) CalcBuf = CalcBuf | 0x80;

					send_buffer[3] = CalcBuf;
					
					send_buffer[4] = (char) (ZeroLevelCH4 / 1.5);
					
					SendData(send_buffer);
													
					break;
				}	

				case 20:										// Protected Config Shifting
				{
				
					send_buffer[0] = 2;						// Command Write Data
					send_buffer[1] = 20;
					
					send_buffer[2] = tc_model & 0x000000FF;
					send_buffer[3] = (tc_model & 0x0000FF00) >> 8;
					send_buffer[4] = (tc_model & 0x00FF0000) >> 16;
					send_buffer[5] = (tc_model & 0xFF000000) >> 24;
					
					send_buffer[6] = tc_serial & 0x000000FF;
					send_buffer[7] = (tc_serial & 0x0000FF00) >> 8;
					send_buffer[8] = (tc_serial & 0x00FF0000) >> 16;
					send_buffer[9] = (tc_serial & 0xFF000000) >> 24;

					send_buffer[10] = tc_production_lot1 & 0x000000FF;
					send_buffer[11] = (tc_production_lot1 & 0x0000FF00) >> 8;
					send_buffer[12] = (tc_production_lot1 & 0x00FF0000) >> 16;
					send_buffer[13] = (tc_production_lot1 & 0xFF000000) >> 24;

					send_buffer[14] = tc_production_lot2 & 0x000000FF;
					send_buffer[15] = (tc_production_lot2 & 0x0000FF00) >> 8;
					send_buffer[16] = (tc_production_lot2 & 0x00FF0000) >> 16;
					send_buffer[17] = (tc_production_lot2 & 0xFF000000) >> 24;

					send_buffer[18] = tc_shipment_date & 0x000000FF;
					send_buffer[19] = (tc_shipment_date & 0x0000FF00) >> 8;
					send_buffer[20] = (tc_shipment_date & 0x00FF0000) >> 16;
					send_buffer[21] = (tc_shipment_date & 0xFF000000) >> 24;

					send_buffer[22] = kill_adc & 0x000000FF;
					send_buffer[23] = (kill_adc & 0x0000FF00) >> 8;

					send_buffer[24] = m2k_filter_Mode | (volt_filter_Mode << 4);
					
					SendData(send_buffer);					
				
				    break;
				}
				
				case 21:										// Hardware Shifting
				{
					la_gate->np_piodata = 0x00;
                    				
					send_buffer[0] = 3;						// Command Write Data
					send_buffer[1] = data[2];
					send_buffer[2] = la_data->np_piodata & 0x00FF;
					send_buffer[3] = (la_data->np_piodata & 0xFF00) >> 8;
                    					
					SendData(send_buffer);
#ifdef _Debug_USB_									
					printf("Hardware read : %x \n", la_data->np_piodata);
#endif					
					break;
				}	

				case 22:
				{                  				
					send_buffer[0] = 2;
					send_buffer[1] = 22;
                    send_buffer[2] = 1;
/* BF del
                    send_buffer[4] = (unsigned char) Voltage_Correction[0][0];
                    send_buffer[5] = (unsigned char) Voltage_Correction[0][1];
                    send_buffer[6] = (unsigned char) Voltage_Correction[0][2];
                    send_buffer[7] = (unsigned char) Voltage_Correction[0][3];
                    send_buffer[8] = (unsigned char) Voltage_Correction[0][4];
                    send_buffer[9] = (unsigned char) Voltage_Correction[0][5];
                    send_buffer[10] = (unsigned char) Voltage_Correction[0][6];
                    send_buffer[11] = (unsigned char) Voltage_Correction[0][7];
                    send_buffer[12] = (unsigned char) Voltage_Correction[0][8];
                    send_buffer[13] = (unsigned char) Voltage_Correction[0][9];
                    send_buffer[14] = (unsigned char) Voltage_Correction[0][10];
                    send_buffer[15] = (unsigned char) Voltage_Correction[0][11];

                    send_buffer[16] = (unsigned char) Voltage_Correction[1][0];
                    send_buffer[17] = (unsigned char) Voltage_Correction[1][1];
                    send_buffer[18] = (unsigned char) Voltage_Correction[1][2];
                    send_buffer[19] = (unsigned char) Voltage_Correction[1][3];
                    send_buffer[20] = (unsigned char) Voltage_Correction[1][4];
                    send_buffer[21] = (unsigned char) Voltage_Correction[1][5];
                    send_buffer[22] = (unsigned char) Voltage_Correction[1][6];
                    send_buffer[23] = (unsigned char) Voltage_Correction[1][7];
                    send_buffer[24] = (unsigned char) Voltage_Correction[1][8];
                    send_buffer[25] = (unsigned char) Voltage_Correction[1][9];
                    send_buffer[26] = (unsigned char) Voltage_Correction[1][10];
                    send_buffer[27] = (unsigned char) Voltage_Correction[1][11];
*/
                    send_buffer[28] = (unsigned char)ADC_Offset[0][0];
                    send_buffer[29] = (unsigned char)ADC_Offset[0][1];
                    send_buffer[30] = (unsigned char)ADC_Offset[0][2];
                    send_buffer[31] = (unsigned char)ADC_Offset[0][3];

                    send_buffer[32] = (unsigned char)ADC_Offset[1][0];
                    send_buffer[33] = (unsigned char)ADC_Offset[1][1];
                    send_buffer[34] = (unsigned char)ADC_Offset[1][2];
                    send_buffer[35] = (unsigned char)ADC_Offset[1][3];


					SendData(send_buffer);
					
					nr_delay(10);
					
					send_buffer[0] = 2;
					send_buffer[1] = 22;
                    send_buffer[2] = 2;
/* BF del
                    send_buffer[4] = (unsigned char) Voltage_Correction[2][0];
                    send_buffer[5] = (unsigned char) Voltage_Correction[2][1];
                    send_buffer[6] = (unsigned char) Voltage_Correction[2][2];
                    send_buffer[7] = (unsigned char) Voltage_Correction[2][3];
                    send_buffer[8] = (unsigned char) Voltage_Correction[2][4];
                    send_buffer[9] = (unsigned char) Voltage_Correction[2][5];
                    send_buffer[10] = (unsigned char) Voltage_Correction[2][6];
                    send_buffer[11] = (unsigned char) Voltage_Correction[2][7];
                    send_buffer[12] = (unsigned char) Voltage_Correction[2][8];
                    send_buffer[13] = (unsigned char) Voltage_Correction[2][9];
                    send_buffer[14] = (unsigned char) Voltage_Correction[2][10];
                    send_buffer[15] = (unsigned char) Voltage_Correction[2][11];

                    send_buffer[16] = (unsigned char) Voltage_Correction[3][0];
                    send_buffer[17] = (unsigned char) Voltage_Correction[3][1];
                    send_buffer[18] = (unsigned char) Voltage_Correction[3][2];
                    send_buffer[19] = (unsigned char) Voltage_Correction[3][3];
                    send_buffer[20] = (unsigned char) Voltage_Correction[3][4];
                    send_buffer[21] = (unsigned char) Voltage_Correction[3][5];
                    send_buffer[22] = (unsigned char) Voltage_Correction[3][6];
                    send_buffer[23] = (unsigned char) Voltage_Correction[3][7];
                    send_buffer[24] = (unsigned char) Voltage_Correction[3][8];
                    send_buffer[25] = (unsigned char) Voltage_Correction[3][9];
                    send_buffer[26] = (unsigned char) Voltage_Correction[3][10];
                    send_buffer[27] = (unsigned char) Voltage_Correction[3][11];
*/
                    send_buffer[28] = (unsigned char)ADC_Offset[2][0];
                    send_buffer[29] = (unsigned char)ADC_Offset[2][1];
                    send_buffer[30] = (unsigned char)ADC_Offset[2][2];
                    send_buffer[31] = (unsigned char)ADC_Offset[2][3];

                    send_buffer[32] = (unsigned char)ADC_Offset[3][0];
                    send_buffer[33] = (unsigned char)ADC_Offset[3][1];
                    send_buffer[34] = (unsigned char)ADC_Offset[3][2];
                    send_buffer[35] = (unsigned char)ADC_Offset[3][3];

					SendData(send_buffer);					
#ifdef _Debug_USB_									
					printf("Sending Voltage Corretion \n");
#endif
                    break;
                }                															
			}
			
			
			break;
		}
		case 3: 											// Receive Data
		{		
			switch(data[2])
			{
				case 0: 								
				{                                           // Connection made
					if ((data[3] & 0x01) == 0x01) OneShotRestart = true;
					if ((data[3] & 0x02) == 0x02) USB_Data_Trans = true;
					if ((data[3] & 0x04) == 0x04) Continius = true;
					if ((data[3] & 0x08) == 0x08) USB_SendAllData = true;
					
					USB_At_Startup = true;
                    /*					
					if (Debug_Mode)
					{
                        if ((data[3] & 0x80) == 0x80) printf("Received USB open at startup\n");
                        else printf("Received USB open\n");
                    }
					 */
					config_changed = true;
					break;
				}
				
				case 1:										// Main Time Base
				{
					Selected_Timebase = data[3];
					break;
				}
				
				case 2:										// Expand Time Base
				{
					Selected_Expand_Timebase = data[3];
					break;
				}
				
				case 3:										// Main Registers
				{
				    AutoTimerOff = true;
				
					ctrl_reg = data[3] + (data[4] << 8);
					adc_ctrl_reg = data[20] + (data[21] << 8);
					
					if ((ctrl_reg & 0x0010) == 0x0010)
					{					
						data_adr->np_piodata = 0x01;
			
						if ((adc_ctrl_reg & 0x0100) == 0x0100) WRITEADC(1, 0x200);
						if ((adc_ctrl_reg & 0x0200) == 0x0200) WRITEADC(2, 0x200);
						if ((adc_ctrl_reg & 0x0400) == 0x0400) WRITEADC(3, 0x200);
						if ((adc_ctrl_reg & 0x0800) == 0x0800) WRITEADC(4, 0x200);
			
						data_adr->np_piodata = 0x00;
			
						if ((adc_ctrl_reg & 0x0100) == 0x0100) printf("Read Test ADC1 : %d\n", READADC(1));
						if ((adc_ctrl_reg & 0x0200) == 0x0200) printf("Read Test ADC2 : %d\n", READADC(2));
						if ((adc_ctrl_reg & 0x0400) == 0x0400) printf("Read Test ADC3 : %d\n", READADC(3));
						if ((adc_ctrl_reg & 0x0800) == 0x0800) printf("Read Test ADC4 : %d\n", READADC(4));
					}
					
					trig_holdoff_reg = 0xFFFFFFFF - (data[5] + (data[6] << 8) + (data[7] << 16) + (data[8] << 24));					
									
					timebase_reg = tb_value[data[9]];
					Selected_Timebase = data[9];
					Selected_Expand_Timebase = data[10];
					
					SIGNALFaktor_idx = data[10];
					
					pre_reg = data[11] + (data[12] << 8);
					//trg_val_CHI_reg = (data[13] + (data[14] << 8));
					//trg_val_CHII_reg = (data[15] + (data[16] << 8));
					//trg_val_CHIII_reg = (data[31] + (data[32] << 8));					
					//trg_val_CHIV_reg = (data[33] + (data[34] << 8));

					Trigger_Pos_CH1 = (unsigned int)((255 - (data[13] + (data[14] << 8))) << 1) - 64;
					Trigger_Pos_CH2 = (unsigned int)((255 - (data[15] + (data[16] << 8))) << 1) - 64;
					Trigger_Pos_CH3 = (unsigned int)((255 - (data[31] + (data[32] << 8))) << 1) - 64;
					Trigger_Pos_CH4 = (unsigned int)((255 - (data[33] + (data[34] << 8))) << 1) - 64; 	                      					
                    					
					ram_adress_reg = data[17] + (data[18] << 8);
					
					triggering = data[19];
					
                    TimebaseChanged = 1;
                    SIGNALFaktorChanged = 1;					
				    /* siehe oben
					if ((data[20] & 0x01) == 0x01) adc_ctrl_reg |= 0x0001;
					if ((data[20] & 0x02) == 0x02) adc_ctrl_reg |= 0x0002;
					if ((data[20] & 0x04) == 0x04) adc_ctrl_reg |= 0x0004;
					if ((data[20] & 0x08) == 0x08) adc_ctrl_reg |= 0x0008;					
					
					if ((data[20] & 0x10) == 0x10) adc_ctrl_reg |= 0x0010;
					if ((data[20] & 0x20) == 0x20) adc_ctrl_reg |= 0x0020;
					if ((data[20] & 0x40) == 0x40) adc_ctrl_reg |= 0x0040;
					if ((data[20] & 0x80) == 0x80) adc_ctrl_reg |= 0x0080;						
					
					if ((data[21] & 0x01) == 0x01) adc_ctrl_reg |= 0x0100;
					if ((data[21] & 0x02) == 0x02) adc_ctrl_reg |= 0x0200;
					if ((data[21] & 0x04) == 0x04) adc_ctrl_reg |= 0x0400;
					if ((data[21] & 0x08) == 0x08) adc_ctrl_reg |= 0x0800;															
					
					if ((data[21] & 0x10) == 0x10) adc_ctrl_reg |= 0x1000;
					if ((data[21] & 0x20) == 0x20) adc_ctrl_reg |= 0x2000;
					if ((data[21] & 0x40) == 0x40) adc_ctrl_reg |= 0x4000;
					if ((data[21] & 0x80) == 0x80) adc_ctrl_reg |= 0x8000;	
					*/					
					if ((data[20] & 0x10) == 0x10) Channel_1_Active = 0;
					else Channel_1_Active = 1;
					if ((data[20] & 0x20) == 0x20) Channel_2_Active = 0;
					else Channel_2_Active = 1;
					if ((data[20] & 0x40) == 0x40) Channel_3_Active = 0;
					else Channel_3_Active = 1;
					if ((data[20] & 0x80) == 0x80) Channel_4_Active = 0;
					else Channel_4_Active = 1;	
								
					Selected_Trigger_Source = 0;

//BF changed like the fix from Stefan
					trg_val_CHI_reg	= (int)((float)(Trigger_Pos_CH1-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH1])+ADC_ZERO;
					trg_val_CHI_reg	= 255 - trg_val_CHI_reg;
		
					trg_val_CHII_reg = (int)((float)(Trigger_Pos_CH2-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH2])+ADC_ZERO;
					trg_val_CHII_reg = 255 - trg_val_CHII_reg;
		
					trg_val_CHIII_reg = (int)((float)(Trigger_Pos_CH3-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH3])+ADC_ZERO;
					trg_val_CHIII_reg = 255 - trg_val_CHIII_reg;
		
					trg_val_CHIV_reg = (int)((float)(Trigger_Pos_CH4-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH4])+ADC_ZERO;
					trg_val_CHIV_reg = 255 - trg_val_CHIV_reg;


					printf("Trig1 : %x - %x\n", Trigger_Pos_CH1, trg_val_CHI_reg);
					printf("Trig2 : %x - %x\n", Trigger_Pos_CH2, trg_val_CHII_reg);
					printf("Trig3 : %x - %x\n", Trigger_Pos_CH3, trg_val_CHIII_reg);
					printf("Trig4 : %x - %x\n", Trigger_Pos_CH4, trg_val_CHIV_reg);

									
					if ((data[3] & 0x02) == 0x02)
					{
						if ((data[20] & 0x01) == 0x01) Selected_Trigger_Source = 1;
						if ((data[20] & 0x02) == 0x02) Selected_Trigger_Source = 2;
						if ((data[20] & 0x04) == 0x04) Selected_Trigger_Source = 3;
						if ((data[20] & 0x08) == 0x08) Selected_Trigger_Source = 4;
						
					}
					else Selected_Trigger_Source = 5;
					
					//Trigger_Offset_Pos = pre_reg << 2;	//BF del not used	
					
					if ((ctrl_reg & 0x40) == 0x40) MenuStatus[MENU_TRIGGERMODE][0] = 93;
					else MenuStatus[MENU_TRIGGERMODE][0] = 94;
                 									
					trig_range_reg = data[22] + (data[23] << 8);
					
					trig_width_reg = data[24] + (data[25] << 8);
					
					
					// pulse width menu update
					if ((ctrl_reg & 0x1200) == 0x1200)
					{
					   MenuStatus[MENU_PULSEWIDTH][2] = 1;
					   Pulse22.Write_Value((float) trig_width_reg * (float) 0.000000008);					
					   Pulse22.RenderText();
                    }
   					if ((ctrl_reg & 0x1400) == 0x1400)
					{
					   MenuStatus[MENU_PULSEWIDTH][2] = 2;
					   Pulse21.Write_Value((float) trig_width_reg * (float) 0.000000008);
                       Pulse21.RenderText();				
                    }
					if ((ctrl_reg & 0x1800) == 0x1800)
					{
					   MenuStatus[MENU_PULSEWIDTH][2] = 3;
					
					   Pulse11.Write_Value((float) trig_width_reg * (float) 0.000000008);
					   Pulse12.Write_Value((float) trig_range_reg * (float) 0.000000008);
					
					   Pulse11.RenderText();
					   Pulse12.RenderText();
                    }
                    				
					
					// Extern Trigger Level
					ext_trg_val_reg = data[26];
					Trigger_Pos_CHE = data[26];
					
					// Channel Address Add
					
					channel_Adr_add = data[27] + (data[28] << 8);
					channel_Adr_add2 = data[29] + (data[30] << 8);
					
					serdata->np_piodata = ext_trg_val_reg;
	
					serstartpwm->np_piodata = 1;
					serstartpwm->np_piodata = 0;						
					
    				data_adr->np_piodata = ram_adress_reg;					
	
    				mode->np_piodata = 0x00;
    				mode->np_piodata = 0x00;
					mode->np_piodata = 0x01;
    				mode->np_piodata = 0x00;
					
#ifdef _Debug_USB_
					if (Debug_Mode)
					{
                        		    printf("pre :%x \n", pre_reg);
					    printf("ctr :%x \n", ctrl_reg);
					    printf("adc :%x \n", adc_ctrl_reg);
					    printf("del :%x \n", adc_del_reg);
					    printf("trg1 :%x \n", trg_val_CHI_reg);
					    printf("extrg :%x \n", ext_trg_val_reg);	
					    printf("tb :%x \n", timebase_reg);
					    printf("tr :%x \n", trig_range_reg);
					    printf("tw :%x \n", trig_width_reg);
					    printf("CHA 1 :%d, 2 :%d, 3 :%d, 4 :%d\n", Channel_1_Active, Channel_2_Active, Channel_3_Active, Channel_4_Active);
					    printf("TrigSrc %d, Trig %d\n", Selected_Trigger_Source, triggering);
					    printf("Channel Add %x\n", channel_Adr_add);
						printf("Channel2 Add %x\n", channel_Adr_add2);
	                }		
#endif
                    //S Display::Update_Channel_Data(1);

					SetupADC();	
					Display::DRAW_ALL_CURSOR();
					
					config_changed = true;
					
					
                    if ((adc_ctrl_reg & 0x1000) == 0x1000)
                    {
                        tc_test_var = (unsigned long) la_data->np_piodata;

                        send_buffer[0] = 6;								 // Kennung Test Var

                        send_buffer[1] = (unsigned char) (tc_test_var & 0x000000FF);
                        send_buffer[2] = (unsigned char) ((tc_test_var & 0x0000FF00) >> 8);


                        send_buffer[3] = (unsigned char) (timebase_reg & 0x000000FF);
                        send_buffer[4] = (unsigned char) ((timebase_reg & 0x0000FF00) >> 8);
                        send_buffer[5] = (unsigned char) ((timebase_reg & 0x00FF0000) >> 16);
                        send_buffer[6] = (unsigned char) ((timebase_reg & 0xFF000000) >> 24);

                        SendData(send_buffer);
                    }
                    else					
                    {
                        tc_test_var = (unsigned long) la_data->np_piodata;

                        send_buffer[0] = 8;								 // Kennung Test Var

                        send_buffer[3] = (unsigned char) (timebase_reg & 0x000000FF);
                        send_buffer[4] = (unsigned char) ((timebase_reg & 0x0000FF00) >> 8);
                        send_buffer[5] = (unsigned char) ((timebase_reg & 0x00FF0000) >> 16);
                        send_buffer[6] = (unsigned char) ((timebase_reg & 0xFF000000) >> 24);

                        SendData(send_buffer);
                    }

                    if (Active_Menu == 15)
                    {
                        MenuItemChanged[1] = 1;
                        MenuItemChanged[2] = 1;
                        MenuItemChanged[3] = 1;
                        MenuItemChanged[4] = 1;
                        MenuChanged = 1;
                        Display::UpdateMenu();
                    }

					
					break;
				}	
				
				case 4:									
				{		
					if (data[3] == 0) USB_Data_Trans = 0;
					else USB_Data_Trans = 1;

					if (data[4] == 0) Continius = 0;
					else Continius = 1;                    				
				
					if (data[5] == 0) USB_OnlyTrigger = 0;
					else USB_OnlyTrigger = 1;
#ifdef _Debug_USB_					
					if (Debug_Mode) printf("Trigger Only %d\n", USB_OnlyTrigger);
#endif					
				    config_changed = true;
		
					break;
				}	
						
				case 5:									
				{
					if (data[3] == 0) USB_Data_Trans = 0;
					else USB_Data_Trans = 1;

					if (data[4] == 0) Continius = 0;
					else Continius = 1;                    				
				
					if (data[5] == 0) USB_OnlyTrigger = 0;
					else USB_OnlyTrigger = 1;
					
					if (data[6] == 0) Transfer_man_data = 0;
					else Transfer_man_data = 1;
					
#ifdef _Debug_USB_					
					if (Debug_Mode) printf("USB %d\n", USB_Data_Trans);
#endif					
				    config_changed = true;
					break;
				}	

				case 6:									
				{
					if (data[3] == 0) USB_Data_Trans = 0;
					else USB_Data_Trans = 1;

					if (data[4] == 0) Continius = 0;
					else Continius = 1;                    				
				
					if (data[5] == 0) USB_OnlyTrigger = 0;
					else USB_OnlyTrigger = 1;
#ifdef _Debug_USB_					
					if (Debug_Mode) printf("Cont %d\n", Continius);
#endif					
				    config_changed = true;
					break;
				}
						
				case 7:
				{
				    	ADC_Data_Available = 1;
					ISR_ADC_INT(0);
					
					break;
				}
				
				case 8:
				{
					GridColor_Val = data[3];
					SetupADC();
					config_changed = true;
					break;
				}

				case 9:
				{
					adc_change12_reg = data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24);
#ifdef _Debug_USB_					
					if (Debug_Mode) printf("ADC_Change12 %x\n", adc_change12_reg);
#endif					
					SetupADC();
					AMDFlash::Write_Protected_Flash();
					break;
				}

				case 10:
				{
					adc_ctr12_reg = data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24);
#ifdef _Debug_USB_					
					if (Debug_Mode) printf("ADC_Ctr12 %x\n", adc_ctr12_reg);
#endif					
					SetupADC();
					AMDFlash::Write_Protected_Flash();
					break;
				}                           						

				case 11:
				{
					adc_change34_reg = data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24);
#ifdef _Debug_USB_					
					if (Debug_Mode) printf("ADC_Change34 %x\n", adc_change34_reg);
#endif					
					SetupADC();
					AMDFlash::Write_Protected_Flash();
					break;
				}                           						
										
				case 12:									// Channel 1
				{
					if ((data[3] & 0x80) == 0x80) MenuStatus[MENU_CHANNEL1][0] = 6;
					else if ((data[3] & 0x40) == 0x40) MenuStatus[MENU_CHANNEL1][0] = 7;
					else MenuStatus[MENU_CHANNEL1][0] = 8;					
				
					Selected_Voltage_CH1 = data[3] & 0x3F;					
					
					MenuStatus[MENU_CHANNEL1][3] = (data[4] & 0x3F) + 101;
					
					if ((data[4] & 0x40) == 0x40) volt_filter_Mode |= 0x01;
					else volt_filter_Mode &= 0xFE;					
					
					if ((data[4] & 0x80) == 0x80) m2k_filter_Mode |= 0x01;
					else m2k_filter_Mode &= 0xFE;					
					
					SwitchesCH1 = data[5] | (data[6] << 8);

                    SwitchesCH2 &= 0xFCFF;
                    					
					switch(data[22])
					{
					   case 1 : SwitchesCH2 |= 0x0200; break;    // caution 1 & 2 turned
					   case 2 : SwitchesCH2 |= 0x0100; break;
					   case 3 : SwitchesCH2 |= 0x0300; break;
                    }
                       					
		if ((data[20] & 0x01) == 0x01)
                    {
                        //BF del multi_active = 1;
                        SwitchesCH1 |= 0x8000;					
                    }
		//BF del else
                    //{
                      //  multi_active = 0;
                    //}
                    			
					//ch1_factor = data[21];	
					
					SetSwitches(1, -1);
					
					nr_delay(10);
                    					
					SetSwitches(2, -1);
					
//					ZeroLevelCH1 = (int) (data[7] * 1.5);
					
					//CH1_DAC_Offset = data[7] | (data[8] << 8);
                    Virtual_ZeroLevelCH1 = (data[7] | (data[8] << 8)) - 8192;

					DAC_Correction[0][0] = data[18] | (data[19] << 8);
					DAC_Correction[0][1] = data[24] | (data[25] << 8);
					DAC_Correction[0][2] = data[26] | (data[27] << 8);
					
					if (DAC_Correction[0][0] > 32768) DAC_Correction[0][0] -= 65536;
					if (DAC_Correction[0][1] > 32768) DAC_Correction[0][1] -= 65536;
					if (DAC_Correction[0][2] > 32768) DAC_Correction[0][2] -= 65536;
														
					//ZeroLevelCH1 = (unsigned int) CH1_DAC_Offset - 7999 + CH1_DAC_Correction;
					
                    //ZeroLevelCH1 = (unsigned int) ((CH1_DAC_Offset - 7999) / 1.74) + CH1_DAC_Correction;	
                    //ZeroLevelCH1 = (unsigned int) (CH1_DAC_Offset - 7999) + CH1_DAC_Correction;//8115;

                    Rotary_Steps = 0;
                    ON_Zero_Channel_1();
                    					
					CH1_DAC_1 = data[9];
					CH1_DAC_2 = data[11];
					CH1_DAC_3 = data[13];
					CH1_DAC_4 = data[15];
					
					if ((data[16] & 0x01) == 0x01) FirEnabledCH1 = 1;
					else FirEnabledCH1 = 0;
					
					// BF -> not used FirStartCH = data[17];		
					
					SetCHDacOffset(1);
					
					CH1_DAC_OffsetOld = CH1_DAC_Offset;
					
					CH1_DAC_1Old = CH1_DAC_1;
					CH1_DAC_2Old = CH1_DAC_2;
					CH1_DAC_3Old = CH1_DAC_3;
					CH1_DAC_4Old = CH1_DAC_4;
					
					Selected_ADCs_CH1 = data[23];					
					
					kill_adc &= 0xFFF0;
					kill_adc |= data[28];					
					
					config_changed = true;				
					break;						
				}					
				case 13:									// Channel 2
				{
					if ((data[3] & 0x80) == 0x80) MenuStatus[MENU_CHANNEL2][0] = 6;
					else if ((data[3] & 0x40) == 0x40) MenuStatus[MENU_CHANNEL2][0] = 7;
					else MenuStatus[MENU_CHANNEL2][0] = 8;
					
					Selected_Voltage_CH2 = data[3] & 0x3F;					
					
					MenuStatus[MENU_CHANNEL2][3] = (data[4] & 0x3F) + 101;
					
					if ((data[4] & 0x40) == 0x40) volt_filter_Mode |= 0x02;
					else volt_filter_Mode &= 0xFD;	
                    					
					if ((data[4] & 0x80) == 0x80) m2k_filter_Mode |= 0x02;
					else m2k_filter_Mode &= 0xFD;	
					
					SwitchesCH2 &= 0xFF00;
					SwitchesCH2 |= data[5];// | (data[6] << 8); Hier nur unteres Byte. Oberes bleibt erhalten

                    SwitchesCH2 &= 0xF3FF;
                    					
					switch(data[22])
					{
					   case 1 : SwitchesCH2 |= 0x0400; break;
					   case 2 : SwitchesCH2 |= 0x0800; break;
					   case 3 : SwitchesCH2 |= 0x0C00; break;
                    }					
					
		if ((data[20] & 0x01) == 0x01)
                    {
                //BF del        multi_active = 1;
                        SwitchesCH1 |= 0x8000;					
                    }
		else
                    {
                //BF del        multi_active = 0;
                        SwitchesCH1 &= 0x7FFF;					
                    }
                    				
					//ch2_factor = data[21];						
					
					SetSwitches(2, -1);
					
					nr_delay(10);
					
					SetSwitches(1, -1);
					
					
					//printf("serdat : %8x\n", (0x40000000 | data[5] | (data[6] * 256)) & 0xFFFF0FFF);					
					
//					ZeroLevelCH2 = (int) (data[7] * 1.5);
					
					//CH2_DAC_Offset = data[7] | (data[8] << 8);
					Virtual_ZeroLevelCH2 = (data[7] | (data[8] << 8)) - 8192;
					
					DAC_Correction[1][0] = data[18] | (data[19]  << 8);
					DAC_Correction[1][1] = data[24] | (data[25]  << 8);
					DAC_Correction[1][2] = data[26] | (data[27]  << 8);					
					
					if (DAC_Correction[1][0] > 32768) DAC_Correction[1][0] -= 65536;
					if (DAC_Correction[1][1] > 32768) DAC_Correction[1][1] -= 65536;
					if (DAC_Correction[1][2] > 32768) DAC_Correction[1][2] -= 65536;
									
					//ZeroLevelCH2 = (unsigned int) CH2_DAC_Offset - 7999 + CH2_DAC_Correction;
					//ZeroLevelCH2 = (unsigned int) ((CH2_DAC_Offset - 7999) / 1.74) + CH2_DAC_Correction;	
					//ZeroLevelCH2 = (unsigned int) (CH2_DAC_Offset - 7999) + CH2_DAC_Correction;//8115;
					
					Rotary_Steps = 0;
					ON_Zero_Channel_2();
					
					CH2_DAC_1 = data[9];
					CH2_DAC_2 = data[11];
					CH2_DAC_3 = data[13];
					CH2_DAC_4 = data[15];		
					
					if ((data[16] & 0x01) == 0x01) FirEnabledCH2 = 1;
					else FirEnabledCH2 = 0;
					
					// BF -> not used FirStartCH = data[17];	
					SetCHDacOffset(2);
			
					CH2_DAC_OffsetOld = CH2_DAC_Offset;
					
					CH2_DAC_1Old = CH2_DAC_1;
					CH2_DAC_2Old = CH2_DAC_2;
					CH2_DAC_3Old = CH2_DAC_3;
					CH2_DAC_4Old = CH2_DAC_4;
					
					Selected_ADCs_CH2 = data[23];
					
					kill_adc &= 0xFF0F;
					kill_adc |= (data[6] << 4);	
					
					config_changed = true;				
					break;
				}	
				
				case 14:									// Channel 3
				{
					if ((data[3] & 0x80) == 0x80) MenuStatus[MENU_CHANNEL3][0] = 6;
					else if ((data[3] & 0x40) == 0x40) MenuStatus[MENU_CHANNEL3][0] = 7;
					else MenuStatus[MENU_CHANNEL3][0] = 8;
					
					Selected_Voltage_CH3 = data[3] & 0x3F;					
					
					MenuStatus[MENU_CHANNEL3][3] = (data[4] & 0x3F) + 101;
					
					if ((data[4] & 0x40) == 0x40) volt_filter_Mode |= 0x04;
					else volt_filter_Mode &= 0xFB;	
                    					
					if ((data[4] & 0x80) == 0x80) m2k_filter_Mode |= 0x04;
					else m2k_filter_Mode &= 0xFB;	
					
					SwitchesCH3 = data[5] | (data[6] << 8);

                    SwitchesCH2 &= 0xCFFF;

					switch(data[22])
					{
					   case 1 : SwitchesCH2 |= 0x2000; break;
					   case 2 : SwitchesCH2 |= 0x1000; break;
					   case 3 : SwitchesCH2 |= 0x3000; break;
                    }	
                    					
		if ((data[20] & 0x01) == 0x01)
                    {
                //BF del        multi_active = 1;
                        SwitchesCH1 |= 0x8000;					
                    }
		else
                    {
                 //BF del       multi_active = 0;
                        SwitchesCH1 &= 0x7FFF;					
                    }
                    				
					//ch3_factor = data[21];						
					
					SetSwitches(3, -1);
					
					nr_delay(10);

					SetSwitches(2, -1);		
					
					nr_delay(10);					
					
					SetSwitches(1, -1);					
					
//					ZeroLevelCH3 = (int) (data[7] * 1.5);
					
					//CH3_DAC_Offset = data[7] | (data[8] << 8);
					Virtual_ZeroLevelCH3 = (data[7] | (data[8] << 8)) - 8192;
					
                    DAC_Correction[2][0] = data[18] | (data[19]  << 8);
                    DAC_Correction[2][1] = data[24] | (data[25]  << 8);
                    DAC_Correction[2][2] = data[26] | (data[27]  << 8);

                    if (DAC_Correction[2][0] > 32768) DAC_Correction[2][0] -= 65536;
                    if (DAC_Correction[2][1] > 32768) DAC_Correction[2][1] -= 65536;
                    if (DAC_Correction[2][2] > 32768) DAC_Correction[2][2] -= 65536;
                    				
					//ZeroLevelCH3 = (unsigned int) CH3_DAC_Offset - 7999 + CH3_DAC_Correction;
					//ZeroLevelCH3 = (unsigned int) (CH3_DAC_Offset - 7999) + CH3_DAC_Correction;//8115;
					
					Rotary_Steps = 0;
					ON_Zero_Channel_3();
					
					CH3_DAC_1 = data[9];
					CH3_DAC_2 = data[11];
					CH3_DAC_3 = data[13];
					CH3_DAC_4 = data[15];
					
					if ((data[16] & 0x01) == 0x01) FirEnabledCH3 = 1;
					else FirEnabledCH3 = 0;
					
					// BF -> not used FirStartCH = data[17];
					
					SetCHDacOffset(3);					

					CH3_DAC_OffsetOld = CH3_DAC_Offset;
					
					CH3_DAC_1Old = CH3_DAC_1;
					CH3_DAC_2Old = CH3_DAC_2;
					CH3_DAC_3Old = CH3_DAC_3;
					CH3_DAC_4Old = CH3_DAC_4;
					
					Selected_ADCs_CH3 = data[23];
					
					kill_adc &= 0xF0FF;
					kill_adc |= (data[6] << 8);						
					
                    config_changed = true;
					break;
				}													
							
				
				case 15:									// Channel 4
				{
					if ((data[3] & 0x80) == 0x80) MenuStatus[MENU_CHANNEL4][0] = 6;
					else if ((data[3] & 0x40) == 0x40) MenuStatus[MENU_CHANNEL4][0] = 7;
					else MenuStatus[MENU_CHANNEL4][0] = 8;
					
					Selected_Voltage_CH4 = data[3] & 0x3F;
					
					
					MenuStatus[MENU_CHANNEL4][3] = (data[4] & 0x3F) + 101;
					
					if ((data[4] & 0x40) == 0x40) volt_filter_Mode |= 0x08;
					else volt_filter_Mode &= 0xF7;						
					
					if ((data[4] & 0x80) == 0x80) m2k_filter_Mode |= 0x08;
					else m2k_filter_Mode &= 0xF7;	
					
					SwitchesCH4 = data[5] | (data[6] << 8);

                    SwitchesCH2 &= 0x3FFF;
                    					
					switch(data[22])
					{
					   case 1 : SwitchesCH2 |= 0x4000; break;
					   case 2 : SwitchesCH2 |= 0x8000; break;
					   case 3 : SwitchesCH2 |= 0xC000; break;
                    }						
					
		if ((data[20] & 0x01) == 0x01)
                    {
                //BF del        multi_active = 1;
                        SwitchesCH1 |= 0x8000;					
                    }
		else
                    {
                  //BF del      multi_active = 0;
                        SwitchesCH1 &= 0x7FFF;					
                    }
                    				
					//ch4_factor = data[21];						
					
					SetSwitches(4, -1);		
					
					nr_delay(10);
					
					SetSwitches(2, -1);		
					
					nr_delay(10);					
					
					SetSwitches(1, -1);					
				
//					ZeroLevelCH4 = (int) (data[7] * 1.5);  // data[8] is high byte
				
					//CH4_DAC_Offset = data[7] | (data[8] << 8);
					Virtual_ZeroLevelCH4 = (data[7] | (data[8] << 8)) - 8192;
					
                    DAC_Correction[3][0] = data[18] | (data[19]  << 8);
                    DAC_Correction[3][1] = data[24] | (data[25]  << 8);
                    DAC_Correction[3][2] = data[26] | (data[27]  << 8);
                    		
                    if (DAC_Correction[3][0] > 32768) DAC_Correction[3][0] -= 65536;
                    if (DAC_Correction[3][1] > 32768) DAC_Correction[3][1] -= 65536;
                    if (DAC_Correction[3][2] > 32768) DAC_Correction[3][2] -= 65536;
                            			
					//ZeroLevelCH4 = (unsigned int) CH4_DAC_Offset - 7999 + CH4_DAC_Correction;
					//ZeroLevelCH4 = (unsigned int) (CH4_DAC_Offset - 7999) + CH4_DAC_Correction;//8115;
					Rotary_Steps = 0;
					ON_Zero_Channel_4();
					
					CH4_DAC_1 = data[9];
					CH4_DAC_2 = data[11];
					CH4_DAC_3 = data[13];
					CH4_DAC_4 = data[15];
					
					if ((data[16] & 0x01) == 0x01) FirEnabledCH4 = 1;
					else FirEnabledCH4 = 0;
					
					// BF -> not used FirStartCH = data[17];
					
					SetCHDacOffset(4);   

					CH4_DAC_OffsetOld = CH4_DAC_Offset;
					
					CH4_DAC_1Old = CH4_DAC_1;
					CH4_DAC_2Old = CH4_DAC_2;
					CH4_DAC_3Old = CH4_DAC_3;
					CH4_DAC_4Old = CH4_DAC_4;
					
					Selected_ADCs_CH4 = data[23];
					
					kill_adc &= 0x0FFF;
					kill_adc |= (data[6] << 12);						
					
                    config_changed = true;
					break;
				}
				
				case 16:									// Trigger
				{
					SwitchesTB = data[3];		// External			
									
					SetSwitches(5, SwitchesTB);					
					config_changed = true;
					break;
				}	
				
				
				case 17:									// Spike Generator / TestPort Bits
				{				
					// TestBits
					test_port_reg = data[3];
					//out_test->np_piodata = test_port_reg;
					
                    config_changed = true;			
					break;								
				}
				
				case 18:									// Triangle Generator
				{	
					rot_speed_read->np_piodata = 1;
								
					for (cnt = 0; cnt < 32; cnt++)
					{					
						serdata->np_piodata = data[cnt + 3];
	
						serstartpwm->np_piodata = 1;
						serstartpwm->np_piodata = 0;
						
						//printf("gtd :%x \n", data[cnt + 3]);
					}
					
					rot_speed_read->np_piodata = 0;
					config_changed = true;
					break;								
				}

				case 19:									// Only one shot after restart bit
				{
					OneShotRestart = data[3];
#ifdef _Debug_USB_					
					if (Debug_Mode)
                    {
                        if (OneShotRestart) printf("One shot will made after restart\n");
                        else printf("Normal mode after restart\n");
                    }
#endif					
					config_changed = true;
					
					break;
				}


				case 20:									// Protected Config
				{
					tc_model = data[4] | (data[5] << 8);

                    			tc_serial = data[6] | (data[7] << 8) | (data[8] << 16) | (data[9] << 24);
					
                    			tc_production_lot1 = data[10];				
                    			tc_production_lot2 = data[11];

                    			tc_shipment_date = (data[12] << 8) | (data[13] << 4) | (data[14] & 0x0000000F);

                    			kill_adc = data[15] | (data[16] << 8);
                    			m2k_filter_Mode = data[17] & 0x0F;
                    			volt_filter_Mode = (data[17] & 0xF0) >> 4;

                   // if (data[19] != 5) Voltage_Correction[data[19]][data[18]] = data[20];


                   // if ((data[21] != 5) && (data[22] != 5))ADC_Offset[data[21]][data[22]] = data[23];



                   			 AMDFlash::Write_Protected_Flash();

					break;
				}

				case 22:									// Protected Config
				{				
        			switch(data[3])
		          	{
					case 1:	
					{
/* BF del
						Voltage_Correction[0][0] = (int) data[4];
						Voltage_Correction[0][1] = (int) data[5];
						Voltage_Correction[0][2] = (int) data[6];
						Voltage_Correction[0][3] = (int) data[7];
						Voltage_Correction[0][4] = (int) data[8];
						Voltage_Correction[0][5] = (int) data[9];
						Voltage_Correction[0][6] = (int) data[10];
						Voltage_Correction[0][7] = (int) data[11];
						Voltage_Correction[0][8] = (int) data[12];
						Voltage_Correction[0][9] = (int) data[13];
						Voltage_Correction[0][10] = (int) data[14];
						Voltage_Correction[0][11] = (int) data[15];
	
						Voltage_Correction[1][0] = (int) data[16];
						Voltage_Correction[1][1] = (int) data[17];
						Voltage_Correction[1][2] = (int) data[18];
						Voltage_Correction[1][3] = (int) data[19];
						Voltage_Correction[1][4] = (int) data[20];
						Voltage_Correction[1][5] = (int) data[21];
						Voltage_Correction[1][6] = (int) data[22];
						Voltage_Correction[1][7] = (int) data[23];
						Voltage_Correction[1][8] = (int) data[24];
						Voltage_Correction[1][9] = (int) data[25];
						Voltage_Correction[1][10] = (int) data[26];
						Voltage_Correction[1][11] = (int) data[27];
BF end*/	
						ADC_Offset[0][0] = (int) data[28];
						ADC_Offset[0][1] = (int) data[29];
						ADC_Offset[0][2] = (int) data[30];
						ADC_Offset[0][3] = (int) data[31];

						ADC_Offset[1][0] = (int) data[32];
						ADC_Offset[1][1] = (int) data[33];
						ADC_Offset[1][2] = (int) data[34];
						ADC_Offset[1][3] = (int) data[35];
/* BF del	
						ZeroScaleFactor[0][0] = (float) ((Voltage_Correction[0][0] + 100) / 100);
						ZeroScaleFactor[0][1] = (float) ((Voltage_Correction[0][1] + 100) / 100);
						ZeroScaleFactor[0][2] = (float) ((Voltage_Correction[0][2] + 100) / 100);
						ZeroScaleFactor[0][3] = (float) ((Voltage_Correction[0][3] + 100) / 100);
						ZeroScaleFactor[0][4] = (float) ((Voltage_Correction[0][4] + 100) / 100);
						ZeroScaleFactor[0][5] = (float) ((Voltage_Correction[0][5] + 100) / 100);
						ZeroScaleFactor[0][6] = (float) ((Voltage_Correction[0][6] + 100) / 100);
						ZeroScaleFactor[0][7] = (float) ((Voltage_Correction[0][7] + 100) / 100);
						ZeroScaleFactor[0][8] = (float) ((Voltage_Correction[0][8] + 100) / 100);
						ZeroScaleFactor[0][9] = (float) ((Voltage_Correction[0][9] + 100) / 100);
						ZeroScaleFactor[0][10] = (float) ((Voltage_Correction[0][10] + 100) / 100);
						ZeroScaleFactor[0][11] = (float) ((Voltage_Correction[0][11] + 100) / 100);
	
						ZeroScaleFactor[1][0] = (float) ((Voltage_Correction[1][0] + 100) / 100);
						ZeroScaleFactor[1][1] = (float) ((Voltage_Correction[1][1] + 100) / 100);
						ZeroScaleFactor[1][2] = (float) ((Voltage_Correction[1][2] + 100) / 100);
						ZeroScaleFactor[1][3] = (float) ((Voltage_Correction[1][3] + 100) / 100);
						ZeroScaleFactor[1][4] = (float) ((Voltage_Correction[1][4] + 100) / 100);
						ZeroScaleFactor[1][5] = (float) ((Voltage_Correction[1][5] + 100) / 100);
						ZeroScaleFactor[1][6] = (float) ((Voltage_Correction[1][6] + 100) / 100);
						ZeroScaleFactor[1][7] = (float) ((Voltage_Correction[1][7] + 100) / 100);
						ZeroScaleFactor[1][8] = (float) ((Voltage_Correction[1][8] + 100) / 100);
						ZeroScaleFactor[1][9] = (float) ((Voltage_Correction[1][9] + 100) / 100);
						ZeroScaleFactor[1][10] = (float) ((Voltage_Correction[1][10] + 100) / 100);
						ZeroScaleFactor[1][11] = (float) ((Voltage_Correction[1][11] + 100) / 100);
BF end */	
						break;
					}
	
					case 2:	
					{
/* BF del
						Voltage_Correction[2][0] = (int) data[4];
						Voltage_Correction[2][1] = (int) data[5];
						Voltage_Correction[2][2] = (int) data[6];
						Voltage_Correction[2][3] = (int) data[7];
						Voltage_Correction[2][4] = (int) data[8];
						Voltage_Correction[2][5] = (int) data[9];
						Voltage_Correction[2][6] = (int) data[10];
						Voltage_Correction[2][7] = (int) data[11];
						Voltage_Correction[2][8] = (int) data[12];
						Voltage_Correction[2][9] = (int) data[13];
						Voltage_Correction[2][10] = (int) data[14];
						Voltage_Correction[2][11] = (int) data[15];
	
						Voltage_Correction[3][0] = (int) data[16];
						Voltage_Correction[3][1] = (int) data[17];
						Voltage_Correction[3][2] = (int) data[18];
						Voltage_Correction[3][3] = (int) data[19];
						Voltage_Correction[3][4] = (int) data[20];
						Voltage_Correction[3][5] = (int) data[21];
						Voltage_Correction[3][6] = (int) data[22];
						Voltage_Correction[3][7] = (int) data[23];
						Voltage_Correction[3][8] = (int) data[24];
						Voltage_Correction[3][9] = (int) data[25];
						Voltage_Correction[3][10] = (int) data[26];
						Voltage_Correction[3][11] = (int) data[27];
BF end */
						ADC_Offset[2][0] = (int) data[28];
						ADC_Offset[2][1] = (int) data[29];
						ADC_Offset[2][2] = (int) data[30];
						ADC_Offset[2][3] = (int) data[31];
	
						ADC_Offset[3][0] = (int) data[32];
						ADC_Offset[3][1] = (int) data[33];
						ADC_Offset[3][2] = (int) data[34];
						ADC_Offset[3][3] = (int) data[35];
/* BF del	
						ZeroScaleFactor[2][0] = (float) ((Voltage_Correction[2][0] + 100) / 100);
						ZeroScaleFactor[2][1] = (float) ((Voltage_Correction[2][1] + 100) / 100);
						ZeroScaleFactor[2][2] = (float) ((Voltage_Correction[2][2] + 100) / 100);
						ZeroScaleFactor[2][3] = (float) ((Voltage_Correction[2][3] + 100) / 100);
						ZeroScaleFactor[2][4] = (float) ((Voltage_Correction[2][4] + 100) / 100);
						ZeroScaleFactor[2][5] = (float) ((Voltage_Correction[2][5] + 100) / 100);
						ZeroScaleFactor[2][6] = (float) ((Voltage_Correction[2][6] + 100) / 100);
						ZeroScaleFactor[2][7] = (float) ((Voltage_Correction[2][7] + 100) / 100);
						ZeroScaleFactor[2][8] = (float) ((Voltage_Correction[2][8] + 100) / 100);
						ZeroScaleFactor[2][9] = (float) ((Voltage_Correction[2][9] + 100) / 100);
						ZeroScaleFactor[2][10] = (float) ((Voltage_Correction[2][10] + 100) / 100);
						ZeroScaleFactor[2][11] = (float) ((Voltage_Correction[2][11] + 100) / 100);
	
						ZeroScaleFactor[3][0] = (float) ((Voltage_Correction[3][0] + 100) / 100);
						ZeroScaleFactor[3][1] = (float) ((Voltage_Correction[3][1] + 100) / 100);
						ZeroScaleFactor[3][2] = (float) ((Voltage_Correction[3][2] + 100) / 100);
						ZeroScaleFactor[3][3] = (float) ((Voltage_Correction[3][3] + 100) / 100);
						ZeroScaleFactor[3][4] = (float) ((Voltage_Correction[3][4] + 100) / 100);
						ZeroScaleFactor[3][5] = (float) ((Voltage_Correction[3][5] + 100) / 100);
						ZeroScaleFactor[3][6] = (float) ((Voltage_Correction[3][6] + 100) / 100);
						ZeroScaleFactor[3][7] = (float) ((Voltage_Correction[3][7] + 100) / 100);
						ZeroScaleFactor[3][8] = (float) ((Voltage_Correction[3][8] + 100) / 100);
						ZeroScaleFactor[3][9] = (float) ((Voltage_Correction[3][9] + 100) / 100);
						ZeroScaleFactor[3][10] = (float) ((Voltage_Correction[3][10] + 100) / 100);
						ZeroScaleFactor[3][11] = (float) ((Voltage_Correction[3][11] + 100) / 100);
BF end */
						break;
					}
                    		}

                    		AMDFlash::Write_Protected_Flash();

				break;
			}	

			case 23:									// USB Data Received
			{
                    		switch(data[3])
		          	{
					case 1: Virtual_ZeroLevelCH1 = 196 - (data[4] + (data[5] << 8)); ON_Zero_Channel_1(); break;
					case 2: Virtual_ZeroLevelCH2 = 196 - (data[4] + (data[5] << 8)); ON_Zero_Channel_2(); break;
					case 3: Virtual_ZeroLevelCH3 = 196 - (data[4] + (data[5] << 8)); ON_Zero_Channel_3(); break;
					case 4: Virtual_ZeroLevelCH4 = 196 - (data[4] + (data[5] << 8)); ON_Zero_Channel_4(); break;
  	       			}
  	       			
  	       			if (MenuStatus[MENU_TRIGGEREDGE][1] == 138) Trigger_Pos_CH1 = 384 - (data[4] + (data[5] << 8));
  	       			else if (MenuStatus[MENU_TRIGGEREDGE][1] == 139) Trigger_Pos_CH2 = 384 - (data[4] + (data[5] << 8));
  	       			else if (MenuStatus[MENU_TRIGGEREDGE][1] == 140) Trigger_Pos_CH3 = 384 - (data[4] + (data[5] << 8));
  	       			else if (MenuStatus[MENU_TRIGGEREDGE][1] == 141) Trigger_Pos_CH4 = 384 - (data[4] + (data[5] << 8));
  	       			
  	       			UpdateTrigger(43);
  	       			
 			    }                				
			}
			
			TriggerLevelChanged = 1;
			TriggerModeChanged = 1;	
			TriggerWayChanged = 1;
			TimebaseChanged = 1;
			TimeOffsetChanged = 1;	
			
			Display::StatusUpdate();			
			
			break;
		}

		
		case 5: 											// Receive Data
		{

			start_acq->np_piodata = 0x01;				//start record Port On
			start_acq->np_piodata = 0x00;				//start record Port Off


			break;			
		}
					
		case 6: 											// Receive Data
		{
			switch(data[2])
			{
				case 1: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Button1\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(30, 0);
					break;
				}		
				case 2: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Button2\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(31, 0);
					break;
				}
				case 3: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Button3\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(32, 0);
					break;
				}
				case 4: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Button4\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(33, 0);
					break;
				}
				case 5: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Button5\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(34, 0);
					break;
				}
				case 6: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Button6\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(35, 0);
					break;
				}
				case 7: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 1\n");
#endif					
//					ButtonChanged = 1;
//					Buttonhandler(1, 0);

					if ((data[3]) && (Channel_1_Active == 0)) UpdateChannel(1, 1);
					if ((data[3] == 0) && (Channel_1_Active == 1)) UpdateChannel(1, 0);
					
					if (Channel_1_Active == 0)
					{
						RemovePlane |= 0x01;
						ClearPlanes();
					}
					
					
					break;
				}
				case 8: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Math\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(26, 0);
					break;
				}
				case 9: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 2\n");
#endif					
//					ButtonChanged = 1;
//					Buttonhandler(2, 0);
					
					if ((data[3]) && (Channel_2_Active == 0)) UpdateChannel(2, 1);
					if ((data[3] == 0) && (Channel_2_Active == 1)) UpdateChannel(2, 0);
					
					if (Channel_2_Active == 0)
					{
						RemovePlane |= 0x02;
						ClearPlanes();
					}
					
				
					break;
				}
				case 10: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 3\n");
#endif					
					//ButtonChanged = 1;
					//Buttonhandler(3, 0);
					
					if ((data[3]) && (Channel_3_Active == 0)) UpdateChannel(3, 1);
					if ((data[3] == 0) && (Channel_3_Active == 1)) UpdateChannel(3, 0);
                    					
					if (Channel_3_Active == 0)
					{
						RemovePlane |= 0x04;
						ClearPlanes();
					}
					
					break;
				}
				case 11: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 4\n");
#endif					
					//ButtonChanged = 1;
					//Buttonhandler(4, 0);
					
					if ((data[3]) && (Channel_4_Active == 0)) UpdateChannel(4, 1);
					if ((data[3] == 0) && (Channel_4_Active == 1)) UpdateChannel(4, 0);
					
					if (Channel_4_Active == 0)
					{
						RemovePlane |= 0x08;
						ClearPlanes();
					}
                    					
					break;
				}
				case 12: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Auto Scale\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(23, 0);
					break;
				}
				case 13: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Save/Recall\n");
#endif					
					ButtonChanged = 1;
					break;
				}
				case 14: 									// All
    			{
#ifdef _Debug_USB_			
					if (Debug_Mode) printf("USB Function Quick Print\n");
#endif					
					ButtonChanged = 1;
					break;
				}
				case 15: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Utility\n");
#endif					
					ButtonChanged = 1;
					break;
				}
				case 16: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Pulse Width\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(15, 0);
					break;
				}
				case 17: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Cursor\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(16, 0);
					break;
				}
				case 18: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Quick Meas\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(19, 0);
					break;
				}
				case 19: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Acquire\n");
#endif
					ButtonChanged = 1;
					Buttonhandler(0, 0);
					break;
				}
				case 20: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Display\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(5, 0);
					break;
				}
				case 21: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Edge\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(14, 0);
					break;
				}
				case 22: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Mode / Coupling\n");
#endif					
					break;
				}
				case 23: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Mode\n");
#endif					
					break;
				}
				case 24: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Run/Stop\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(37, 0);
			
                    if (Continius)
                    {		
                        LED_ON[12] = 1;
                        LED_ON[13] = 0;
                        Send_LED();					
                    }
                    else
                    {		
                        LED_ON[12] = 0;
                        LED_ON[13] = 1;
                        Send_LED();					
                    }					
					break;
				}
				case 25: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Single\n");
#endif					
					ButtonChanged = 1;
					Buttonhandler(38, 0);
					
					break;
				}
				case 26: 									// All
				{
					printf("USB Test Button\n");
					
					
					
                    buflong = 0x00000000;

                    while (1 == 1)
                    {
                        data_adr->np_piodata = 0x01;
                        buflong = READADC(1);

                        if ((buflong & 0x00008000) == 0x00008000)
                        {
                            buflong1 = READADC(1);

                            if (Selected_Voltage_CH1 == 9) DAC_Correction[0][0] = (int) (buflong1 - 8192);
                            else if (Selected_Voltage_CH1 == 10) DAC_Correction[0][1] = (int) (buflong1 - 8192);
                            else if (Selected_Voltage_CH1 == 11) DAC_Correction[0][2] = (int) (buflong1 - 8192);

                            printf("buflong %8x %d\n", buflong, buflong);
                            printf("buflong1 %8x %d\n", buflong1, buflong1);
                            printf("CH1_1 : %4.4d CH1_2 : %4.4d CH1_3 : %4.4d \n", DAC_Correction[0][0], DAC_Correction[0][1], DAC_Correction[0][2]);
                            
                            break;
                        }

                        data_adr->np_piodata = 0x00;
                        lcnt++;
                        if (lcnt == 50000) break;
                    }					
					

                    printf("lcnt %d\n", lcnt);

				}	
				case 27:
				{
					if (data[3] == 1)
					{
						USB_SendAllData = 1;
#ifdef _Debug_USB_						
						if (Debug_Mode) printf("USB Function Send All Data On\n");
#endif						
					}					
					else
					{
						USB_SendAllData = 0;
#ifdef _Debug_USB_						
						if (Debug_Mode) printf("USB Function Send All Data Off\n");
#endif						
					}
					
					if (data[4] == 1)
					{
						OneShotRestart = 1;
#ifdef _Debug_USB_						
						if (Debug_Mode) printf("USB Function OneShotRestart On\n");
#endif
					}					
					else
					{
						OneShotRestart = 0;
#ifdef _Debug_USB_						
						if (Debug_Mode) printf("USB Function OneShotRestart Off\n");
#endif						
					}
					
					config_changed = true;
                    					
					break;
				}


				case 28: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 1 ACDC\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL1][0] = 7;  // DC
					else MenuStatus[MENU_CHANNEL1][0] = 8;  // AC
					
					SetSwitches(1, -1);
					
					MenuItemChanged[0] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();
                    					
					break;
				}
				case 29: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 2 ACDC\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL2][0] = 7;  // DC
					else MenuStatus[MENU_CHANNEL2][0] = 8;  // AC
					
					SetSwitches(1, -1);
					
					MenuItemChanged[0] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}
				case 30: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 3 ACDC\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL3][0] = 7;  // DC
					else MenuStatus[MENU_CHANNEL3][0] = 8;  // AC
					
					SetSwitches(1, -1);
					
					MenuItemChanged[0] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}
				case 31: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 4 ACDC\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL4][0] = 7;  // DC
					else MenuStatus[MENU_CHANNEL4][0] = 8;  // AC
                    					
					SetSwitches(1, -1);
					
					MenuItemChanged[0] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}

				case 32: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 1 Invert\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL1][2] = 241;  // Invert
					else MenuStatus[MENU_CHANNEL1][2] = 240;
				
					MenuItemChanged[2] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}

				case 33: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 2 Invert\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL2][2] = 241;  // Invert
					else MenuStatus[MENU_CHANNEL2][2] = 240;
				
					MenuItemChanged[2] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}
				
				case 34: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 3 Invert\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL3][2] = 241;  // Invert
					else MenuStatus[MENU_CHANNEL3][2] = 240;
				
					MenuItemChanged[2] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}

				case 35: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB Function Channel 4 Invert\n");
#endif									
					if (data[3]) MenuStatus[MENU_CHANNEL4][2] = 241;  // Invert
					else MenuStatus[MENU_CHANNEL4][2] = 240;
				
					MenuItemChanged[2] = 1;
					Menu_Changed = 1;
					Display::UpdateMenu();					
                    					
					break;
				}                				
                                                                              							
			}
			SendCtrlBlock();
			
			nr_delay(10);
			
			SendCtrlBlock3();	

			nr_delay(10);
			
			SendCtrlBlock2();

			break;
		}

		case 7: 											// Receive Data
		{
			switch(data[2])
			{
				case 1: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Channel 1\n");
#endif					
					if (data[3] == 1) Set_LED(0);
					else Reset_LED(0);					
					break;
				}	
				case 2: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Math\n");
#endif					
					if (data[3] == 1) Set_LED(4);
					else Reset_LED(4);
					break;
				}	
				case 3: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Channel 2\n");
#endif					
					if (data[3] == 1) Set_LED(1);
					else Reset_LED(1);
					break;
				}	
				case 4: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Channel 3\n");
#endif					
					if (data[3] == 1) Set_LED(2);
					else Reset_LED(2);
					break;
				}	
				case 5: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Channel 4\n");
#endif					
					if (data[3] == 1) Set_LED(3);
					else Reset_LED(3);
					break;
				}	
				case 6: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Pulse Width\n");
#endif					
					if (data[3] == 1) Set_LED(10);
					else Reset_LED(10);
					break;
				}	
				case 7: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Wheel\n");
#endif					
					if (data[3] == 1) Set_LED(6);
					else Reset_LED(6);
					break;
				}	
				case 8: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Cursor\n");
#endif					
					if (data[3] == 1) Set_LED(5);
					else Reset_LED(5);
					break;
				}	
				case 9: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Quick Meas\n");
#endif					
					if (data[3] == 1) Set_LED(7);
					else Reset_LED(7);
					break;
				}	
				case 10: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Edge\n");
#endif					
					if (data[3] == 1) Set_LED(8);
					else Reset_LED(8);
					break;
				}	
				case 11: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Run/Stop Green\n");
#endif					
					LED_ON[12] = 1;
					LED_ON[13] = 0;
					Send_LED();
					break;
				}	
				case 12: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Run/Stop Red\n");
#endif					
					LED_ON[13] = 1;
					LED_ON[12] = 0;
					Send_LED();
					break;
				}	
				case 13: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Single Green\n");
#endif					
					LED_ON[14] = 1;
					LED_ON[15] = 0;
					Send_LED();
					break;
				}	
				case 14: 									// All
				{
#ifdef _Debug_USB_				
					if (Debug_Mode) printf("USB LED Single Red\n");
#endif					
					LED_ON[15] = 1;
					LED_ON[14] = 0;
					Send_LED();
					break;
				}									
			}
			
			SendCtrlBlock();
			
			nr_delay(10);
			
			SendCtrlBlock3();			

			nr_delay(10);
			
			SendCtrlBlock2();
			
			
			break;			
		}	
		
		case 8: 											// Receive Data
		{
			switch(data[2])
			{
				case 1: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 1 Right\n");
#endif							
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 1 Left\n");
#endif							
							break;
						}
					}
					break;						
				}	
				case 2: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 2 Right\n");
#endif							
							break;
						}
						case 2:
						{	
#ifdef _Debug_USB_                        				
							if (Debug_Mode) printf("USB Wheel Pos Channel 2 Left\n");
#endif							
							break;
						}
					}
					break;						
				}	
				case 3: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 3 Right\n");
#endif							
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 3 Left\n");
#endif							
							break;
						}
					}
					break;						
				}	
				case 4: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 4 Right\n");
#endif							
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Pos Channel 4 Left\n");
#endif							
							break;
						}
					}
					break;						
				}	
				case 5: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 1 Right\n");
#endif							
                            Rotary_Direction = 1;
                            ON_Voltage_Channel_1();	

							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 1 Left\n");
#endif						
                            Rotary_Direction = 0;
                            ON_Voltage_Channel_1();	
                            	
							break;
						}
					}
					break;						
				}	
				case 6: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 2 Right\n");
#endif							
                            Rotary_Direction = 1;
                            ON_Voltage_Channel_2();	

							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 2 Left\n");
#endif						
                            Rotary_Direction = 0;
                            ON_Voltage_Channel_2();		

							break;
						}
					}
					break;						
				}	
				case 7: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 3 Right\n");
#endif							
                            Rotary_Direction = 1;
                            ON_Voltage_Channel_3();	
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 3 Left\n");
#endif						
                            Rotary_Direction = 0;
                            ON_Voltage_Channel_3();		
							break;
						}
					}
					break;						
				}	
				case 8: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 4 Right\n");
#endif						
                            Rotary_Direction = 1;
                            ON_Voltage_Channel_4();	
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Volt Channel 4 Left\n");
#endif							
                            Rotary_Direction = 0;
                            ON_Voltage_Channel_4();	

							break;
						}
					}
					break;						
				}	
				case 9: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Generic Right\n");
#endif							
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Generic Left\n");
#endif							
							break;
						}
					}
					break;						
				}	
				case 10: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Trigger Level Right\n");
#endif							
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Trigger Level Left\n");
#endif							
							break;
						}
					}
					break;						
				}				
				case 11: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Timebase Right\n");
#endif						
                            Rotary_Direction = 1;
                            ON_Timebase();
                            	
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Timebase Left\n");
#endif							
                            Rotary_Direction = 0;
                            ON_Timebase();

							break;
						}
					}
					break;						
				}	
				case 12: 									// All
				{
					switch(data[3])
					{				
						case 1:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Trigger Delay Right\n");
#endif							
							break;
						}
						case 2:
						{					
#ifdef _Debug_USB_						
							if (Debug_Mode) printf("USB Wheel Trigger Delay Left\n");
#endif							
							break;
						}
					}
					break;						
				}	
				
			}
			
			SendCtrlBlock();
			
			nr_delay(10);
			
			SendCtrlBlock3();			
			
			nr_delay(10);
			
			SendCtrlBlock2();			
			
			break;
		}
		
		case 9:
		{	
		
			switch(data[10])
			{
				case 1 :
				{
/* BF del not used		
					CH1_X_Offset_1 = data[6];
					CH1_X_Offset_2 = data[7];
					CH1_X_Offset_3 = data[8];
					CH1_X_Offset_4 = data[9];
					
			        if (data[2] > ADCzero) Channel1_1_ADC_Correction = 256 - (256 - data[2]);
			        else Channel1_1_ADC_Correction = data[2];
			        if (data[3] > ADCzero) Channel1_2_ADC_Correction = 256 - (256 - data[3]);
			        else Channel1_2_ADC_Correction = data[3];
			        if (data[4] > ADCzero) Channel1_3_ADC_Correction = 256 - (256 - data[4]);
			        else Channel1_3_ADC_Correction = data[4];
			        if (data[5] > ADCzero) Channel1_4_ADC_Correction = 256 - (256 - data[5]);
			        else Channel1_4_ADC_Correction = data[5];					
*/					
					break;					
				}
				case 2 :
				{
/* BF del not used
					CH2_X_Offset_1 = data[6];
					CH2_X_Offset_2 = data[7];
					CH2_X_Offset_3 = data[8];
					CH2_X_Offset_4 = data[9];
					
			        if (data[2] > ADCzero) Channel2_1_ADC_Correction = 256 - (256 - data[2]);
			        else Channel2_1_ADC_Correction = data[2];
			        if (data[3] > ADCzero) Channel2_2_ADC_Correction = 256 - (256 - data[3]);
			        else Channel2_2_ADC_Correction = data[3];
			        if (data[4] > ADCzero) Channel2_3_ADC_Correction = 256 - (256 - data[4]);
			        else Channel2_3_ADC_Correction = data[4];
			        if (data[5] > ADCzero) Channel2_4_ADC_Correction = 256 - (256 - data[5]);
			        else Channel2_4_ADC_Correction = data[5];	
*/					
					break;					
				}
				case 3 :
				{
/* BF del not used
					CH3_X_Offset_1 = data[6];
					CH3_X_Offset_2 = data[7];
					CH3_X_Offset_3 = data[8];
					CH3_X_Offset_4 = data[9];	
					
			        if (data[2] > ADCzero) Channel3_1_ADC_Correction = 256 - (256 - data[2]);
			        else Channel3_1_ADC_Correction = data[2];
			        if (data[3] > ADCzero) Channel3_2_ADC_Correction = 256 - (256 - data[3]);
			        else Channel3_2_ADC_Correction = data[3];
			        if (data[4] > ADCzero) Channel3_3_ADC_Correction = 256 - (256 - data[4]);
			        else Channel3_3_ADC_Correction = data[4];
			        if (data[5] > ADCzero) Channel3_4_ADC_Correction = 256 - (256 - data[5]);
			        else Channel3_4_ADC_Correction = data[5];	
*/									
					break;				
				}
				case 4 :
				{
/* BF del not used
					CH4_X_Offset_1 = data[6];
					CH4_X_Offset_2 = data[7];
					CH4_X_Offset_3 = data[8];
					CH4_X_Offset_4 = data[9];
					
			        if (data[2] > ADCzero) Channel4_1_ADC_Correction = 256 - (256 - data[2]);
			        else Channel4_1_ADC_Correction = data[2];
			        if (data[3] > ADCzero) Channel4_2_ADC_Correction = 256 - (256 - data[3]);
			        else Channel4_2_ADC_Correction = data[3];
			        if (data[4] > ADCzero) Channel4_3_ADC_Correction = 256 - (256 - data[4]);
			        else Channel4_3_ADC_Correction = data[4];
			        if (data[5] > ADCzero) Channel4_4_ADC_Correction = 256 - (256 - data[5]);
			        else Channel4_4_ADC_Correction = data[5];	
*/								
					break;					
				}												
			}
#ifdef _Debug_USB_			
			if (Debug_Mode) printf("W : %d ; X1 : %d ; X2 : %d ; X3 : %d ; X4 : %d ; idx %i\n", data[10], data[6], data[7], data[8], data[9], data[11]);
#endif			
			
			config_changed = true;
			
			break;			
		}
		case 10: 											// Program the Flash
		{
			switch(data[2])
			{
				case 0 :                                    // Set programm mode
				{
                    switch(data[3])
                    {				
				        case 0 :                            // End programm mode
				        {				
//                            reset_watchdog->np_piodata = 0x01;						// Enableable WatchDog
                            Continius = true;
                            //adc_started = false;
                            result_buf = 0;
                            AutoTimerOff = false;

#ifdef _Debug_USB_
                            printf("Program mode disabled \n");
#endif
                            break;
                        }
				        case 1 :                            // Start programm mode
				        {				
//                            reset_watchdog->np_piodata = 0x00;						// Disable WatchDog
                            Continius = false;
                            //adc_started = true;
                            result_buf = 1;

                            Stop_Record();
                            AutoTimerOff = true;

#ifdef _Debug_USB_
                            printf("Program mode enabled \n");
#endif
                            break;
                        }
                    }
                    break;
                }			
				case 1 :                                    // Erase a block
				{
				    prog_flash_adr = (unsigned long *) (data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24));
#ifdef _Debug_USB_				
				    printf("Erase address %x \n", prog_flash_adr);
#endif				
				    result_buf = AMDFlash::EraseSector_Flash(prog_flash_adr);
				
				    break;
                }
				case 2 :                                    // receive offset
				{
				    prog_flash_offset = (unsigned long) (data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24));
#ifdef _Debug_USB_				
				    printf("Received Flash Offset %x \n", prog_flash_offset);
#endif				
				    result_buf = 0;
				
				    break;
                }
				case 3 :                                    // Write a block
				{
				    prog_flash_adr = (unsigned long *) ((data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24)) - prog_flash_offset);
				
                    prog_flash_length = data[7];

                    result_buf = 0;
                    for (cnt = 0; cnt < prog_flash_length; cnt++)
                    {
                        result_buf = result_buf + AMDFlash::WriteData_Byte_Flash(prog_flash_adr, cnt, data[8 + cnt]);
                        //nr_delay(20);
                    }

#ifdef _Debug_USB_
                    printf("PFD @ %x[%d]  : %d \n", prog_flash_adr, prog_flash_length, result_buf);
#endif
				    break;
                }

				case 4 :                                    // Read Data
				{
				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif				
				    break;
                }

				case 5 :                                    // Read Software Version
				{
#ifdef _Debug_USB_				
				    printf("Read Software Version %x \n", tc_version);				
				    printf("Read Software Subversion %x \n", tc_subversion);
				    printf("Read Software Reversion %x \n", tc_dev_version);
				    printf("Read Software Compile %x \n", tc_dev_subversion);
#endif				
                    result_buf = 0;

                    send_buffer[7] = (unsigned char) tc_version & 0x000000FF;
                    send_buffer[8] = (unsigned char) ((tc_version & 0x0000FF00) >> 8);
                    send_buffer[9] = (unsigned char) ((tc_version & 0x00FF0000) >> 16);
                    send_buffer[10] = (unsigned char) ((tc_version & 0xFF000000) >> 24);

                    send_buffer[11] = (unsigned char) tc_subversion & 0x000000FF;
                    send_buffer[12] = (unsigned char) ((tc_subversion & 0x0000FF00) >> 8);
                    send_buffer[13] = (unsigned char) ((tc_subversion & 0x00FF0000) >> 16);
                    send_buffer[14] = (unsigned char) ((tc_subversion & 0xFF000000) >> 24);

                    send_buffer[15] = (unsigned char) tc_dev_version & 0x000000FF;
                    send_buffer[16] = (unsigned char) ((tc_dev_version & 0x0000FF00) >> 8);
                    send_buffer[17] = (unsigned char) ((tc_dev_version & 0x00FF0000) >> 16);
                    send_buffer[18] = (unsigned char) ((tc_dev_version & 0xFF000000) >> 24);

                    send_buffer[19] = (unsigned char) tc_dev_subversion & 0x000000FF;
                    send_buffer[20] = (unsigned char) ((tc_dev_subversion & 0x0000FF00) >> 8);
                    send_buffer[21] = (unsigned char) ((tc_dev_subversion & 0x00FF0000) >> 16);
                    send_buffer[22] = (unsigned char) ((tc_dev_subversion & 0xFF000000) >> 24);

				    break;
                }

				case 6 :                                    // Read Hardware Version
				{		
#ifdef _Debug_USB_                	
				    printf("Read Hardware Version %x \n", tc_hw_version);				
				    printf("Read Hardware SW Version %x \n", tc_hw_sw_version);				
				    printf("Read Serial %d hex : %x\n", tc_serial, tc_serial);				
#endif				
                    result_buf = 0;

                    send_buffer[7] = (unsigned char) (tc_hw_version & 0x000000FF);
                    send_buffer[8] = (unsigned char) ((tc_hw_version & 0x0000FF00) >> 8);
                    send_buffer[9] = (unsigned char) ((tc_hw_version & 0x00FF0000) >> 16);
                    send_buffer[10] = (unsigned char) ((tc_hw_version & 0xFF000000) >> 24);

                    send_buffer[11] = (unsigned char) (tc_hw_sw_version & 0x000000FF);
                    send_buffer[12] = (unsigned char) ((tc_hw_sw_version & 0x0000FF00) >> 8);
                    send_buffer[13] = (unsigned char) ((tc_hw_sw_version & 0x00FF0000) >> 16);
                    send_buffer[14] = (unsigned char) ((tc_hw_sw_version & 0xFF000000) >> 24);

                    send_buffer[15] = (unsigned char) (tc_serial & 0x000000FF);
                    send_buffer[16] = (unsigned char) ((tc_serial & 0x0000FF00) >> 8);
                    send_buffer[17] = (unsigned char) ((tc_serial & 0x00FF0000) >> 16);
                    send_buffer[18] = (unsigned char) ((tc_serial & 0xFF000000) >> 24);

                    send_buffer[19] = (unsigned char) (tc_production_lot1 & 0x000000FF);
                    send_buffer[20] = (unsigned char) ((tc_production_lot1 & 0x0000FF00) >> 8);
                    send_buffer[21] = (unsigned char) ((tc_production_lot1 & 0x00FF0000) >> 16);
                    send_buffer[22] = (unsigned char) ((tc_production_lot1 & 0xFF000000) >> 24);

                    send_buffer[23] = (unsigned char) (tc_production_lot2 & 0x000000FF);
                    send_buffer[24] = (unsigned char) ((tc_production_lot2 & 0x0000FF00) >> 8);
                    send_buffer[25] = (unsigned char) ((tc_production_lot2 & 0x00FF0000) >> 16);
                    send_buffer[26] = (unsigned char) ((tc_production_lot2 & 0xFF000000) >> 24);

                    send_buffer[27] = (unsigned char) (tc_model & 0x000000FF);
                    send_buffer[28] = (unsigned char) ((tc_model & 0x0000FF00) >> 8);
                    send_buffer[29] = (unsigned char) ((tc_model & 0x00FF0000) >> 16);
                    send_buffer[30] = (unsigned char) ((tc_model & 0xFF000000) >> 24);

				    break;
                }

				case 7 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 8 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 9 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 10 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 11 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 12 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 13 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 14 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 15 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 16 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 17 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

				case 18 :                                    // Read Data
				{

				    prog_flash_adr = (unsigned long *) ((data[4] << 8) + (data[5] << 16) + (data[6] << 24));
				
				    if ((data[3] == 0x00) & ((data[4] % 0x04) == 0)) AMDFlash::ReadData_Prepare_Flash(prog_flash_adr);
				
                    			result_buf = AMDFlash::ReadData_Byte_Flash(data[3] + ((data[4] & 0x03) << 8));
#ifdef _Debug_USB_
				    printf("Read address %x byte %d res = %x\n", prog_flash_adr, data[3] + ((data[4] & 0x03) << 8), result_buf);
#endif
				    break;
                }

            }

            send_buffer[0] = 10;
            send_buffer[1] = data[2];
            send_buffer[2] = data[3];
            send_buffer[3] = data[4];
            send_buffer[4] = data[5];
            send_buffer[5] = data[6];

            send_buffer[6] = result_buf;
            		
            SendData(send_buffer);

			break;
		}

		case 11: 											// Prgram the Flash
		{

            timebase_reg = data[3] + (data[4] << 8) + (data[5] << 16) + (data[6] << 24);
#ifdef _Debug_USB_
            if (Debug_Mode) printf("TB Reg written %x\n", timebase_reg);
#endif
            SetupADC();	

			break;
		}
		case 12: 											// Prgram the Flash
		{
#ifdef _Debug_USB_		
			if (Debug_Mode) printf("Read TB Reg %x\n", timebase_reg);
#endif
			send_buffer[0] = 8;								 // Kennung Test Var
		
			send_buffer[3] = (unsigned char) (timebase_reg & 0x000000FF);
			send_buffer[4] = (unsigned char) ((timebase_reg & 0x0000FF00) >> 8);
			send_buffer[5] = (unsigned char) ((timebase_reg & 0x00FF0000) >> 16);
			send_buffer[6] = (unsigned char) ((timebase_reg & 0xFF000000) >> 24);
		
			SendData(send_buffer);

			break;
		}		
		case 13: 											// Search Zeros
		{
			Search_Mode = true;
		
			CalcBuf = 0x01;
			while (CalcBuf != 0x00)
			{
				CalcBuf = Hardware::SearchZeros();
#ifdef _Debug_USB_
				printf("SearchResult : %i\n", CalcBuf);
#endif
			} 
			break;
		}
		
		case 14: 											// Receive Data
		{

			USB_Data_Requested = true;
			
			if (Continius == false) ISR_ADC_INT(6);

			break;			
		}	

		case 15: 											// Receive Data
        	{

			Set_Vars_Default();
			// BF insert - Recalc vars			
			Recalc_Vars();
			// BF insert - init display
			Display::RefreshScreen();
			
			UpdateChannel(1, 1);
			UpdateChannel(2, 1);
		
			VoltageChangedCh1 = 1;
			VoltageChangedCh2 = 1;				
		
			LED_ON[0] = 1;
			LED_ON[1] = 1; 				
			LED_ON[5] = 1;
			LED_ON[6] = 0;
	
			Rotary_Steps = 0;
			ON_Zero_Channel_1();
			Rotary_Steps = 0;
			ON_Zero_Channel_2();
	
			SetSwitches(1, Selected_Voltage_CH1);
			SetSwitches(2, Selected_Voltage_CH2);

			if (NumberOfChannels > 2)
			{
				UpdateChannel(3, 1);
				UpdateChannel(4, 1);
	
				VoltageChangedCh3 = 1;
				VoltageChangedCh4 = 1;
			
				LED_ON[2] = 1;
				LED_ON[3] = 1;
					
				ON_Zero_Channel_3();
				ON_Zero_Channel_4();
	
				SetSwitches(3, Selected_Voltage_CH3);
				SetSwitches(4, Selected_Voltage_CH4);
	
			}
			else
			{
				UpdateChannel(3, 0);
				UpdateChannel(4, 0);
			}

			TriggerLevelChanged = 1;
			TriggerModeChanged  = 1;	
			TriggerWayChanged   = 1;
			TimebaseChanged     = 1;
			TimeOffsetChanged   = 1;
			MenuStatusChanged   = 1;
			MenuAktive          = 1;

			Cursor_Data_First_Draw = 0;
			Quick_Measure_First_Draw = 0;
			

			UpdateTrigger(12);
			Display::CALCPRETRIGGER();
			Display::DRAW_ALL_CURSOR();
				
                    	// remove the cursor data
			for (ix = 408 * 20; ix < 430 * 20; ix++)
			{
				*(UI_Plane1 + ix) = 0;	// delete
				*(Buffer_UI2Plane + ix) = 0;	// delete Text				
				*(UI_Plane4 + ix) = 0;	// delete
				*(UI_Plane5 + ix) = 0;	// delete
			}				

			Display::DRAWSQUAREBUTTON(2, 1, 14, 16, btnPushed, btnDraw);						// Button
			Display::TEXTOUTvbig("1", 6, 4, 1, Channel_Plane1);							// Draw Voltage Text
//                   	Display::TEXTOUTvbig("1", 6, 4, 1, Buffer_Plane1);							// Draw Voltage Text

			Display::DRAWSQUAREBUTTON(78, 1, 14, 16, btnPushed, btnDraw);						// Button
			Display::TEXTOUTvbig("2", 82, 4, 1, Channel_Plane2);							// Draw Voltage Text
	//                    Display::TEXTOUTvbig("2", 82, 4, 1, Buffer_Plane2);						// Draw Voltage Text
	
			Display::StatusUpdate();


			if (NumberOfChannels > 2)
			{
				Display::DRAWSQUAREBUTTON(154, 1, 14, 16, btnPushed, btnDraw);					// Button
				Display::TEXTOUTvbig("3", 158, 4, 1, Channel_Plane3);						// Draw Voltage Text
	//                        Display::TEXTOUTvbig("3", 158, 4, 1, Buffer_Plane3);						// Draw Voltage Text
	
				Display::DRAWSQUAREBUTTON(230, 1, 14, 16, btnPushed, btnDraw);					// Button		
				Display::TEXTOUTvbig("4", 234, 4, 1, Channel_Plane4);						// Draw Voltage Text
	//                        Display::TEXTOUTvbig("4", 234, 4, 1, Buffer_Plane4);						// Draw Voltage Text
			}
                    	Display::DRAWSTATUS(6, 0);
				
			Send_LED();

			break;			
		}

		case 16: 											// Receive Data
		{

			SendCtrlBlock();
			
			nr_delay(100);
			
			SendCtrlBlock3();
			
			nr_delay(10);
			
			SendCtrlBlock2();
            			
			USB_Connected = true;	

			break;			
		}             	

		case 17: 											// Receive Data
		{

			SendCtrlBlock2();

			break;			
		}
		
		case 18: 											// Receive Data
		{		
		
			New_Menu = 17;
			Menu_Changed = 1;
			
			USB_Connected = true;		
			
			break;			
		}		
	}
    }   // else			
}
/*
unsigned char Hardware::Calc_Chksum(volatile unsigned char Bytes[37])
{
    int i;

    for (i = 0; i < 37; i++)
    {
        calc_chks += Bytes[i];
        nr_uart_txchar(Bytes[i], puart2);
    }

}
*/
void Hardware::SendData(volatile unsigned char Bytes[40])
{
	int i;

#ifdef _Debug_USB_
    if (Command_Mode)
    {
        printf("Sending  0:%x  1:%x  2:%x  3:%x  4:%x  5:%x  6:%x  7:%x  8:%x 9:%x \n", Bytes[0], Bytes[1], Bytes[2], Bytes[3], Bytes[4], Bytes[5], Bytes[6], Bytes[7], Bytes[8], Bytes[9]);
        printf("Sending 10:%x 11:%x 12:%x 13:%x 14:%x 15:%x 16:%x 17:%x 18:%x 19:%x\n", Bytes[10], Bytes[11], Bytes[12], Bytes[13], Bytes[14], Bytes[15], Bytes[16], Bytes[17], Bytes[18], Bytes[19]);
        printf("Sending 20:%x 21:%x 22:%x 23:%x 24:%x 25:%x 26:%x 27:%x 28:%x 29:%x\n", Bytes[20], Bytes[21], Bytes[22], Bytes[23], Bytes[24], Bytes[25], Bytes[26], Bytes[27], Bytes[28], Bytes[29]);
        printf("Sending 30:%x 31:%x 32:%x 33:%x 34:%x 35:%x 36:%x \n", Bytes[30], Bytes[31], Bytes[32], Bytes[33], Bytes[34], Bytes[35], Bytes[36]);
    }
#endif

    nr_uart_txchar(40, puart2);
    for (i = 0; i < 40; i++)
    {
        nr_uart_txchar(Bytes[i], puart2);
    }
}

void Hardware::SendShot(void)
{
//    reset_watchdog->np_piodata = 0x00;                                  // Disable Watchdog

    // Disable all Interrupts
	DoDisableLogicAnalyserInterrupt();
	DoDisableReadVSyncInterrupt();
	DoDisableADCInterrupt();
	DoDisableTimer3Interrupt();
	//BF not used  DoDisableTimerInterrupt();
	DoDisableUART2Interrupt();
	DoDisableUARTInterrupt();
	DoDisableRotInterrupt();
	DoDisableKeyInterrupt();

	SendLayer(1);
	SendLayer(2);
	SendLayer(3);
	SendLayer(4);
	SendLayer(5);
	SendLayer(6);
	SendLayer(7);
	SendLayer(8);
	SendLayer(9);
	SendLayer(10);
	SendLayer(11);
	SendLayer(12);
	SendLayer(13);
	SendLayer(14);
	SendLayer(15);
	SendLayer(16);

    // Enable all Interrupts
	DoEnableKeyInterrupt();
	DoEnableRotInterrupt();
	DoEnableUARTInterrupt();
	DoEnableUART2Interrupt();
//	DoEnableTimerInterrupt();
	DoEnableTimer3Interrupt();
	DoEnableADCInterrupt();	
	DoEnableReadVSyncInterrupt();
//    DoEnableLogicAnalyserInterrupt();	

//    reset_watchdog->np_piodata = 0x01;                                  // Enable Watchdog
}

void Hardware::SendSWShot(void)
{
    unsigned int LineCnt, PackCnt;
    unsigned long *Layer1 = UI_Plane1;
    unsigned long *Layer2 = UI_Plane2;
    unsigned long *Layer3 = UI_Plane3;
    unsigned long *Layer4 = UI_Plane4;
    unsigned long *Layer5 = UI_Plane5;
    unsigned long *Layer6 = Channel_Plane1;
    unsigned long *Layer7 = Channel_Plane2;
    unsigned long *Layer8 = Channel_Plane3;
    unsigned long *Layer9 = Channel_Plane4;
    unsigned long *Layer10 = Channel_Math_Plane;
    unsigned long *Layer11 = Memory_Plane1;
    unsigned long *Layer12 = Memory_Plane2;
    unsigned long *Layer13 = Memory_Plane3;
    unsigned long *Layer14 = Marker_Plane1;
    unsigned long *Layer15 = Marker_Plane2;
    unsigned long *Layer16 = Grid_Plane;

    unsigned long BufLayer = 0x00000000;

//    reset_watchdog->np_piodata = 0x00;                                  // Disable Watchdog

    // Disable all Interrupts
	DoDisableLogicAnalyserInterrupt();
	DoDisableReadVSyncInterrupt();
	DoDisableADCInterrupt();
	DoDisableTimer3Interrupt();
	//BF not used DoDisableTimerInterrupt();
	DoDisableUART2Interrupt();
	DoDisableUARTInterrupt();
	DoDisableRotInterrupt();
	DoDisableKeyInterrupt();


    send_buffer[0] = 254;                                               // Kennung Screen Data
    send_buffer[1] = 1;                                                 // Layer number

    for(LineCnt = 0; LineCnt < 1200; LineCnt++)
    {
        send_buffer[2] = (unsigned char) ((LineCnt & 0xFF00) >> 8);     // High Line Address
        send_buffer[3] = (unsigned char) (LineCnt & 0x00FF);            // Low Line Address

        for(PackCnt = 0; PackCnt < 8; PackCnt++)
        {

            BufLayer = Layer1[(LineCnt * 8) + PackCnt] | Layer2[(LineCnt * 8) + PackCnt] | Layer5[(LineCnt * 8) + PackCnt] | Layer6[(LineCnt * 8) + PackCnt] | Layer7[(LineCnt * 8) + PackCnt] | Layer8[(LineCnt * 8) + PackCnt] | Layer9[(LineCnt * 8) + PackCnt] | Layer10[(LineCnt * 8) + PackCnt] | Layer11[(LineCnt * 8) + PackCnt] | Layer12[(LineCnt * 8) + PackCnt] | Layer13[(LineCnt * 8) + PackCnt] | Layer14[(LineCnt * 8) + PackCnt] | Layer15[(LineCnt * 8) + PackCnt] | Layer16[(LineCnt * 8) + PackCnt];

            send_buffer[4 + (PackCnt * 4)] = (unsigned char) (BufLayer & 0x000000FF);
            send_buffer[5 + (PackCnt * 4)] = (unsigned char) ((BufLayer & 0x0000FF00) >> 8);
            send_buffer[6 + (PackCnt * 4)] = (unsigned char) ((BufLayer & 0x00FF0000) >> 16);
            send_buffer[7 + (PackCnt * 4)] = (unsigned char) ((BufLayer & 0xFF000000) >> 24);
        }

        SendData(send_buffer);
    }

    // Enable all Interrupts
	DoEnableKeyInterrupt();
	DoEnableRotInterrupt();
	DoEnableUARTInterrupt();
	DoEnableUART2Interrupt();
//	DoEnableTimerInterrupt();
	DoEnableTimer3Interrupt();
	DoEnableADCInterrupt();	
	DoEnableReadVSyncInterrupt();
//    DoEnableLogicAnalyserInterrupt();	

//    reset_watchdog->np_piodata = 0x01;                                  // Enable Watchdog
}

void Hardware::SendLayer(unsigned char LayerNr)						// Send a Layer through USB
{
    unsigned int LineCnt, PackCnt;
    unsigned long *Layer = Planes;

    switch(LayerNr)
    {
        case 1 : Layer = UI_Plane1; break;
        case 2 : Layer = UI_Plane2; break;
        case 3 : Layer = UI_Plane3; break;
        case 4 : Layer = UI_Plane4; break;
        case 5 : Layer = UI_Plane5; break;
        case 6 : Layer = Channel_Plane1; break;
        case 7 : Layer = Channel_Plane2; break;
        case 8 : Layer = Channel_Plane3; break;
        case 9 : Layer = Channel_Plane4; break;
        case 10 : Layer = Channel_Math_Plane; break;
        case 11 : Layer = Memory_Plane1; break;
        case 12 : Layer = Memory_Plane2; break;
        case 13 : Layer = Memory_Plane3; break;
        case 14 : Layer = Marker_Plane1; break;
        case 15 : Layer = Marker_Plane2; break;
        case 16 : Layer = Grid_Plane; break;
    }
    send_buffer[0] = 253;                                               // Kennung Screen Data
    send_buffer[1] = LayerNr;                                                 // Layer number

    for(LineCnt = 0; LineCnt < 1200; LineCnt++)
    {
        send_buffer[2] = (unsigned char) ((LineCnt & 0xFF00) >> 8);     // High Line Address
        send_buffer[3] = (unsigned char) (LineCnt & 0x00FF);            // Low Line Address

        for(PackCnt = 0; PackCnt < 8; PackCnt++)
        {
            send_buffer[4 + (PackCnt * 4)] = 0;
            send_buffer[5 + (PackCnt * 4)] = 0;
            send_buffer[6 + (PackCnt * 4)] = 0;
            send_buffer[7 + (PackCnt * 4)] = 0;

            send_buffer[4 + (PackCnt * 4)] = (unsigned char) (Layer[(LineCnt * 8) + PackCnt] & 0x000000FF);
            send_buffer[5 + (PackCnt * 4)] = (unsigned char) ((Layer[(LineCnt * 8) + PackCnt] & 0x0000FF00) >> 8);
            send_buffer[6 + (PackCnt * 4)] = (unsigned char) ((Layer[(LineCnt * 8) + PackCnt] & 0x00FF0000) >> 16);
            send_buffer[7 + (PackCnt * 4)] = (unsigned char) ((Layer[(LineCnt * 8) + PackCnt] & 0xFF000000) >> 24);
        }

        SendData(send_buffer);
    }
}

void Hardware::SendCtrlBlock(void)
{
    int intbuf, ix;
    int chk_calc = 0;

    send_buffer[0] = 105;								// Kennung Data
//    send_buffer[1] = 5;									// Kennung Datablock

    send_buffer[2] = (unsigned char) (Selected_Voltage_CH1);
    send_buffer[3] = (unsigned char) (Selected_Voltage_CH2);
    send_buffer[4] = (unsigned char) (Selected_Voltage_CH3);
    send_buffer[5] = (unsigned char) (Selected_Voltage_CH4);
    send_buffer[6] = (unsigned char) (Selected_Timebase);
    send_buffer[7] = (unsigned char) (SIGNALFaktor_idx);
		
    send_buffer[8] = (unsigned char) ((ZeroLevelCH1 + 64) >> 1);		
    send_buffer[9] = (unsigned char) ((ZeroLevelCH2 + 64) >> 1);		
    send_buffer[10] = (unsigned char) ((ZeroLevelCH3 + 64) >> 1);		
    send_buffer[11] = (unsigned char) ((ZeroLevelCH4 + 64) >> 1);		

    send_buffer[12] = (unsigned char) (NumberOfChannels);
    send_buffer[13] = (unsigned char) (ZFT_float);
        		
    send_buffer[14] = (unsigned char) SingleMode;
    send_buffer[15] = (unsigned char) Continius;

    send_buffer[16] = (unsigned char) Selected_Trigger_Source;

    send_buffer[17] = (unsigned char) 0;

    switch(Selected_Trigger_Source)
    {
        case 1 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH1 + 64) >> 1); break;
        case 2 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH2 + 64) >> 1); break;
        case 3 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH3 + 64) >> 1); break;
        case 4 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH4 + 64) >> 1); break;
        case 5 : send_buffer[17] = (unsigned char) Trigger_Pos_CHE; break;
    }

    send_buffer[18] = 0;
    if (Channel_1_Active) send_buffer[18] = send_buffer[18] | 0x01;
    if (MenuStatus[MENU_CHANNEL1][0] == 7) send_buffer[18] = send_buffer[18] | 0x02;  // AC
    if (MenuStatus[MENU_CHANNEL1][0] == 8) send_buffer[18] = send_buffer[18] | 0x04;  // AC
    if (MenuStatus[MENU_CHANNEL1][0] == 9) send_buffer[18] = send_buffer[18] | 0x08;  // AC
    if (MenuStatus[MENU_CHANNEL1][2] == 241) send_buffer[18] = send_buffer[18] | 0x10;  // Invert

    send_buffer[19] = 0;
    if (Channel_2_Active) send_buffer[19] = send_buffer[19] | 0x01;
    if (MenuStatus[MENU_CHANNEL2][0] == 7) send_buffer[19] = send_buffer[19] | 0x02;  // AC
    if (MenuStatus[MENU_CHANNEL2][0] == 8) send_buffer[19] = send_buffer[19] | 0x04;  // AC
    if (MenuStatus[MENU_CHANNEL2][0] == 9) send_buffer[19] = send_buffer[19] | 0x08;  // AC
    if (MenuStatus[MENU_CHANNEL2][2] == 241) send_buffer[18] = send_buffer[18] | 0x10;  // Invert

    send_buffer[20] = 0;
    if (Channel_3_Active) send_buffer[20] = send_buffer[20] | 0x01;
    if (MenuStatus[MENU_CHANNEL3][0] == 7) send_buffer[20] = send_buffer[20] | 0x02;  // AC
    if (MenuStatus[MENU_CHANNEL3][0] == 8) send_buffer[20] = send_buffer[20] | 0x04;  // AC
    if (MenuStatus[MENU_CHANNEL3][0] == 9) send_buffer[20] = send_buffer[20] | 0x08;  // AC
    if (MenuStatus[MENU_CHANNEL3][2] == 241) send_buffer[18] = send_buffer[18] | 0x10;  // Invert

    send_buffer[21] = 0;
    if (Channel_4_Active) send_buffer[21] = send_buffer[21] | 0x01;
    if (MenuStatus[MENU_CHANNEL4][0] == 7) send_buffer[21] = send_buffer[21] | 0x02;  // AC
    if (MenuStatus[MENU_CHANNEL4][0] == 8) send_buffer[21] = send_buffer[21] | 0x04;  // AC
    if (MenuStatus[MENU_CHANNEL4][0] == 9) send_buffer[21] = send_buffer[21] | 0x08;  // AC
    if (MenuStatus[MENU_CHANNEL4][2] == 241) send_buffer[18] = send_buffer[18] | 0x10;  // Invert

    send_buffer[22] = (unsigned char) Channel_Math_Active;

    send_buffer[23] = (unsigned char) MenuStatus[MENU_CHANNEL1][3];
    send_buffer[24] = (unsigned char) MenuStatus[MENU_CHANNEL2][3];
    send_buffer[25] = (unsigned char) MenuStatus[MENU_CHANNEL3][3];
    send_buffer[26] = (unsigned char) MenuStatus[MENU_CHANNEL4][3];
    send_buffer[27] = (unsigned char) MenuStatus[MENU_TRIGGERMODE][4];

    intbuf = (int)((float) Timebase_Offset_Pos * OFT_float);

    send_buffer[28] = (unsigned char) (intbuf & 0x00FF);
    send_buffer[29] = (unsigned char) ((intbuf & 0xFF00) >> 8);
    send_buffer[30] = (unsigned char) ((Timebase_Offset_Pos + 300) & 0x00FF);      // + 300 so it was unsigned
    send_buffer[31] = (unsigned char) (((Timebase_Offset_Pos + 300)  & 0xFF00) >> 8);

    send_buffer[32] = (unsigned char) MenuStatus[MENU_TRIGGEREDGE][0];        // Trigger Edge
    send_buffer[33] = (unsigned char) MenuStatus[MENU_TRIGGEREDGE][2];        // Trigger Extern

    send_buffer[34] = (unsigned char) (pre_reg & 0x00FF);
    send_buffer[35] = (unsigned char) ((pre_reg & 0xFF00) >> 8);

    chk_calc = 0;	
    for (ix = 0; ix < 32; ix++)
    {	
        chk_calc += send_buffer[3 + ix];
    }	
				
    send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
    send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
        		
    SendData(send_buffer);
}

void Hardware::SendCtrlBlock2(void)
{
    int intbuf, ix;
    int chk_calc = 0;

    send_buffer[0] = 107;								// Kennung Data
//    send_buffer[1] = 7;									// Kennung Datablock

    send_buffer[2] = (unsigned char) (Cursor_Enabled);
    send_buffer[3] = (unsigned char) (SelectedCursor);
    send_buffer[4] = (unsigned char) (Cursor_XY_Selected);
    send_buffer[5] = (unsigned char) (Cursor_Both_Selected);
    send_buffer[6] = (unsigned char) (Cursor_Horizontal_Active);
    send_buffer[7] = (unsigned char) (Cursor_Vertical_Active);

    send_buffer[8] = (unsigned char) (Cursor_Horizontal_Position_Real1 & 0x000000FF);
    send_buffer[9] = (unsigned char) ((Cursor_Horizontal_Position_Real1 & 0x0000FF00) >> 8);
    send_buffer[10] = (unsigned char) ((Cursor_Horizontal_Position_Real1 & 0x00FF0000) >> 16);
    send_buffer[11] = (unsigned char) ((Cursor_Horizontal_Position_Real1 & 0xFF000000) >> 24);

    send_buffer[12] = (unsigned char) (Cursor_Horizontal_Position_Real2 & 0x000000FF);
    send_buffer[13] = (unsigned char) ((Cursor_Horizontal_Position_Real2 & 0x0000FF00) >> 8);
    send_buffer[14] = (unsigned char) ((Cursor_Horizontal_Position_Real2 & 0x00FF0000) >> 16);
    send_buffer[15] = (unsigned char) ((Cursor_Horizontal_Position_Real2 & 0xFF000000) >> 24);

    send_buffer[16] = (unsigned char) (Cursor_Vertical_Position_Real1 & 0x000000FF);
    send_buffer[17] = (unsigned char) ((Cursor_Vertical_Position_Real1 & 0x0000FF00) >> 8);
    send_buffer[18] = (unsigned char) ((Cursor_Vertical_Position_Real1 & 0x00FF0000) >> 16);
    send_buffer[19] = (unsigned char) ((Cursor_Vertical_Position_Real1 & 0xFF000000) >> 24);

    send_buffer[20] = (unsigned char) (Cursor_Vertical_Position_Real2 & 0x000000FF);
    send_buffer[21] = (unsigned char) ((Cursor_Vertical_Position_Real2 & 0x0000FF00) >> 8);
    send_buffer[22] = (unsigned char) ((Cursor_Vertical_Position_Real2 & 0x00FF0000) >> 16);
    send_buffer[23] = (unsigned char) ((Cursor_Vertical_Position_Real2 & 0xFF000000) >> 24);

    send_buffer[24] = (unsigned char) QM_Threshold_lower.Read_Value();
    send_buffer[25] = (unsigned char) QM_Threshold_middle.Read_Value();
    send_buffer[26] = (unsigned char) QM_Threshold_upper.Read_Value();

    send_buffer[27] = (unsigned char) ((SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float)) & 0x00FF);
    send_buffer[28] = (unsigned char) (((SIG_Start_Stop[ZIT_short][0] + (int)((float) Timebase_Offset_Pos * OFT_float)) & 0xFF00) >> 8);

    send_buffer[29] = (unsigned char) ((SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float)) & 0x00FF);
    send_buffer[30] = (unsigned char) (((SIG_Start_Stop[ZIT_short][1] + (int)((float) Timebase_Offset_Pos * OFT_float)) & 0xFF00) >> 8);

    //send_buffer[31] = (unsigned char) ((SIG_Start_Stop[ZIT_short][0] + (int)((float) -300 * OFT_float)) & 0x00FF);
    //send_buffer[32] = (unsigned char) (((SIG_Start_Stop[ZIT_short][0] + (int)((float) -300 * OFT_float)) & 0xFF00) >> 8);

    send_buffer[31] = (unsigned char) (MemWinStart & 0x00FF);
    send_buffer[32] = (unsigned char) ((MemWinStart & 0xFF00) >> 8);


    send_buffer[33] = (unsigned char) ((Trigger_Offset_Calc + 100) & 0x00FF);
    send_buffer[34] = (unsigned char) (((Trigger_Offset_Calc + 100) & 0xFF00) >> 8);

    //BF not used send_buffer[35] = (unsigned char) (FirStartCH & 0x00FF);
    //BF not used send_buffer[36] = (unsigned char) ((FirStartCH & 0xFF00) >> 8);
    

    //send_buffer[8] = (unsigned char) (Cursor_Vertical_Position_Real1 & 0x000000FF);
    //send_buffer[9] = (unsigned char) ((Cursor_Vertical_Position_Real1 & 0x0000FF00) >> 8);
    //send_buffer[10] = (unsigned char) ((Cursor_Vertical_Position_Real1 & 0x00FF0000) >> 16);
    //send_buffer[11] = (unsigned char) ((Cursor_Vertical_Position_Real1 & 0xFF000000) >> 24);            		
    //send_buffer[8] = (unsigned char) ((ZeroLevelCH1 + 64) >> 1);		
    //send_buffer[9] = (unsigned char) ((ZeroLevelCH2 + 64) >> 1);		
    //send_buffer[10] = (unsigned char) ((ZeroLevelCH3 + 64) >> 1);		
    //send_buffer[11] = (unsigned char) ((ZeroLevelCH4 + 64) >> 1);		

    //send_buffer[12] = (unsigned char) (NumberOfChannels);
    //send_buffer[13] = (unsigned char) (ZFT_float);
        		
    //send_buffer[14] = (unsigned char) SingleMode;
    //send_buffer[15] = (unsigned char) Continius;

    //send_buffer[16] = (unsigned char) Selected_Trigger_Source;

    //send_buffer[17] = (unsigned char) 0;
    /*
    switch(Selected_Trigger_Source)
    {
        case 1 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH1 + 64) >> 1); break;
        case 2 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH2 + 64) >> 1); break;
        case 3 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH3 + 64) >> 1); break;
        case 4 : send_buffer[17] = (unsigned char) ((Trigger_Pos_CH4 + 64) >> 1); break;
        case 5 : send_buffer[17] = (unsigned char) Trigger_Pos_CHE; break;
    }
    */
    //send_buffer[18] = (unsigned char) Channel_1_Active;
    //send_buffer[19] = (unsigned char) Channel_2_Active;
    //send_buffer[20] = (unsigned char) Channel_3_Active;
    //send_buffer[21] = (unsigned char) Channel_4_Active;
    //send_buffer[22] = (unsigned char) Channel_Math_Active;

    //send_buffer[23] = (unsigned char) MenuStatus[MENU_CHANNEL1][3];
    //send_buffer[24] = (unsigned char) MenuStatus[MENU_CHANNEL2][3];
    //send_buffer[25] = (unsigned char) MenuStatus[MENU_CHANNEL3][3];
    //send_buffer[26] = (unsigned char) MenuStatus[MENU_CHANNEL4][3];
    //send_buffer[27] = (unsigned char) MenuStatus[MENU_TRIGGERMODE][4];

    //intbuf = (int)((float) Timebase_Offset_Pos * OFT_float);

    //send_buffer[28] = (unsigned char) (intbuf & 0x00FF);
    //send_buffer[29] = (unsigned char) ((intbuf & 0xFF) >> 8);
    //send_buffer[30] = (unsigned char) ((Timebase_Offset_Pos + 300) & 0x00FF);      // + 300 so it was unsigned
    //send_buffer[31] = (unsigned char) (((Timebase_Offset_Pos + 300)  & 0xFF00) >> 8);

    chk_calc = 0;	
    for (ix = 0; ix < 32; ix++)
    {	
        chk_calc += send_buffer[3 + ix];
    }	
				
    send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
    send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
                    		
    SendData(send_buffer);
}

void Hardware::SendCtrlBlock3(void)
{
    int intbuf, ix;
    int chk_calc = 0;

    send_buffer[0] = 108;								// Kennung Data

//BF del    send_buffer[2] = (unsigned char) (Voltage_Correction[0][Selected_Voltage_CH1]);
//BF del    send_buffer[3] = (unsigned char) (Voltage_Correction[1][Selected_Voltage_CH2]);
//BF del    send_buffer[4] = (unsigned char) (Voltage_Correction[2][Selected_Voltage_CH3]);
//BF del    send_buffer[5] = (unsigned char) (Voltage_Correction[3][Selected_Voltage_CH4]);
    send_buffer[6] = (unsigned char) AutoFreeRun;
    
    send_buffer[7] = (unsigned char) 0;
    send_buffer[8] = (unsigned char) 0;
    send_buffer[9] = (unsigned char) 0;
    send_buffer[10] = (unsigned char) 0;
    send_buffer[11] = (unsigned char) 0;
    send_buffer[12] = (unsigned char) 0;
    send_buffer[13] = (unsigned char) 0;
    send_buffer[14] = (unsigned char) 0;
    send_buffer[15] = (unsigned char) 0;
    send_buffer[16] = (unsigned char) 0;
    send_buffer[17] = (unsigned char) 0;
    send_buffer[18] = (unsigned char) 0;
    send_buffer[19] = (unsigned char) 0;
    send_buffer[20] = (unsigned char) 0;
    send_buffer[21] = (unsigned char) 0;
    send_buffer[22] = (unsigned char) 0;
    send_buffer[23] = (unsigned char) 0;
    send_buffer[24] = (unsigned char) 0;
    send_buffer[25] = (unsigned char) 0;
    send_buffer[26] = (unsigned char) 0;
    send_buffer[27] = (unsigned char) 0;
    send_buffer[28] = (unsigned char) 0;
    send_buffer[29] = (unsigned char) 0;
    send_buffer[30] = (unsigned char) 0;
    send_buffer[31] = (unsigned char) 0;
    send_buffer[32] = (unsigned char) 0;
    send_buffer[33] = (unsigned char) 0;
    send_buffer[34] = (unsigned char) 0;
    send_buffer[35] = (unsigned char) 0;
    send_buffer[36] = (unsigned char) 0;

    chk_calc = 0;	
    for (ix = 0; ix < 32; ix++)
    {	
        chk_calc += send_buffer[3 + ix];
    }	
				
    send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
    send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
                    		
    SendData(send_buffer);
}
//###################################################################################################################################################
/*BF del -> not used
void Hardware::DoEnableTimerInterrupt(void)										// Enable service routine
{	
    return;
    					
	nr_installuserisr(na_timer1_irq,ISR_TIMER,(int)timer1); 						// Install timer isr
	

//	timer1->np_timerperiodh = timer_array_first[Selected_Timebase] >> 16;					// Set High Register of Timer
//	timer1->np_timerperiodl = timer_array_first[Selected_Timebase] & 0xffff;					// Set Low Register of Timer

    timer_reload_high = timerAutoFreefirst >> 16;					// Set High Register of Timer 200 ms  -> mu� in TB array
    timer_reload_low = timerAutoFreefirst & 0xffff;					// Set Low Register of Timer

    timer1->np_timerperiodh = timer_reload_high;
    timer1->np_timerperiodl = timer_reload_low;	

    timer_counter_value = 0;

    timer1->np_timercontrol = timer1->np_timercontrol | np_timercontrol_ito_mask;  	// Enable timer interrupt
    timer1->np_timercontrol = ((timer1->np_timercontrol & 3) + np_timercontrol_stop_mask);	// Stop Timer
#ifdef _Debug_IRQ_	
	if (Debug_Mode) printf("\nTimer1 interrupt enabled.\n"); 										// print on console
#endif	
}

*/

/*BF del -> not used	
void Hardware::DoDisableTimerInterrupt(void)										// Disable service routine
{
	nr_installuserisr(na_timer1_irq,0,0); 											// Install empty routine for timer irq
	timer1->np_timercontrol = timer1->np_timercontrol & ~np_timercontrol_ito_mask; 	// Disable timer interrupt
}
*/
/*BF del -> not used
void Hardware::Start_Timer1(void)
{
    return;

    if (init_done == false) return;

    if (Selected_Timebase < 17)
    {
        if (AutoSearchTrigger)
        {
            timer_reload_high = timerAutoFreefast >> 16;					// Set High Register of Timer 1 ms
            timer_reload_low = timerAutoFreefast & 0xffff;					// Set Low Register of Timer
        }
        else
        {
            timer_reload_high = timerAutoFreefirst >> 16;					// Set High Register of Timer 200 ms  -> mu� in TB array
            timer_reload_low = timerAutoFreefirst & 0xffff;					// Set Low Register of Timer
        }
    }
    else if (Selected_Timebase < 23)
    {
        if (AutoSearchTrigger)
        {
            timer_reload_high = timerAutoFreefast >> 13;					// Set High Register of Timer 4 ms
            timer_reload_low = timerAutoFreefast & 0xffff;					// Set Low Register of Timer
        }
        else
        {
            timer_reload_high = timerAutoFreefirst >> 13;					// Set High Register of Timer 800 ms  -> mu� in TB array
            timer_reload_low = timerAutoFreefirst & 0xffff;					// Set Low Register of Timer
        }
    }
    else
    {
        if (AutoSearchTrigger)
        {
            timer_reload_high = timerAutoFreefast >> (11 - (Selected_Timebase - 23));		// Set High Register of Timer 4 ms
            timer_reload_low = timerAutoFreefast & 0xffff;					// Set Low Register of Timer
        }
        else
        {
            timer_reload_high = timerAutoFreefirst >> (11 - (Selected_Timebase - 23));		// Set High Register of Timer 800 ms  -> mu� in TB array
            timer_reload_low = timerAutoFreefirst & 0xffff;					// Set Low Register of Timer
        }
    }

    timer1->np_timerperiodh = timer_reload_high;
    timer1->np_timerperiodl = timer_reload_low;	

    timer_counter_value = 0;
	
    timer1->np_timercontrol = ((timer1->np_timercontrol & 3) + np_timercontrol_start_mask);	// Start Timer
}
*/

/*BF del -> not used
void Hardware::Stop_Timer1(void)
{
    timer1->np_timercontrol = ((timer1->np_timercontrol & 3) + np_timercontrol_stop_mask);	// Stop Timer
}
*/
/*BF del -> not used
void Hardware::ISR_TIMER(int context)											// Menu Timer service subroutine
{
	//char fchanged = 0;    	
	printf("\nTimer 1 interrupt occured\n");

	if(USTB_Mode != 0) return;

	//tc_test_var2++;
	
	timer1->np_timercontrol = ((timer1->np_timercontrol & 3) + np_timercontrol_stop_mask);			// Stop Timer
	timer1->np_timerstatus = 0;										// write anything to clear the ISR

    	timer1->np_timerperiodh = timer_reload_high;
    	timer1->np_timerperiodl = timer_reload_low;	


#ifdef _Debug_IRQ_
	if (Debug_Mode)  printf("We got a timer1 irq  AFR %d  AST %d tcv %d tcm %d irq %d\n", AutoFreeRun, AutoSearchTrigger, timer_counter_value, timer_counter_max, acq_ready->np_piodata);
#endif

    	Start_Record();  	
}
*/
//##############################################################################################################################################
// BF new implemented
// Enable timer 2 interrupt for rollmode
void Hardware::DoEnableTimer2Interrupt(void)									// Enable service routine
{	

	//timer2->np_timercontrol = np_timercontrol_stop_mask;							// Stop Timer
	timer2->np_timercontrol = 0x0008;									// Stop Timer, disable interrupt
	//timer2->np_timerperiodh = (short)((USTB_timer_value[Selected_Timebase - 23] >> 16) & 0x0000ffff);	// Set High Register of Timer
	//timer2->np_timerperiodl = (short)(USTB_timer_value[Selected_Timebase - 23] & 0x0000ffff);		// Set Low Register of Timer
	timer2->np_timerstatus = 0;										// write anything to clear the ISR

	nr_installuserisr(na_timer2_irq,ISR_TIMER2,(int)timer2); 						// Install timer isr
	timer2->np_timercontrol = 0x0001;									// enable interrupt

	//printf("\nTimer2 interrupt enabled.\n");

}
//##############################################################################################################################################
// BF new implemented
// disable timer 2 interrupt for rollmode
void Hardware::DoDisableTimer2Interrupt(void)									// Disable service routine
{
	
	timer2->np_timercontrol = np_timercontrol_stop_mask;							// Stop Timer
	nr_installuserisr(na_timer2_irq,0,0); 									// Install empty routine for timer irq
    	timer2->np_timerstatus = 0;

	printf("\nTimer2 interrupt disabled.\n");	

}
// BF new implemented
void Hardware::Start_Timer2(void)
{
	//timer2->np_timerperiodh = (short)((USTB_timer_value[Selected_Timebase - 23] >> 16) & 0x0000ffff);	// Set High Register of Timer
	//timer2->np_timerperiodl = (short)(USTB_timer_value[Selected_Timebase - 23] & 0x0000ffff);		// Set Low Register of Timer
	//timer2->np_timerstatus = 0;										// clear the ISR

	//timer2->np_timercontrol = np_timercontrol_start_mask;							// Start Timer
	//timer2->np_timercontrol = np_timercontrol_start_mask + np_timercontrol_ito_mask;			// Start Timer and enable Interrupt
	timer2->np_timercontrol = 0x0005;									// Start Timer and enable Interrupt
	printf("\nTimer2 started.\n");
}
// BF new implemented
void Hardware::Stop_Timer2(void)
{
	//timer2->np_timercontrol = np_timercontrol_stop_mask;							// Stop Timer
	//timer2->np_timercontrol = 0x0009;									// Stop Timer
	timer2->np_timercontrol = 0x0008;									// Stop Timer, disable interrupt
	timer2->np_timerstatus  = 0;										// clear the ISR

	//printf("\nTimer2 stopped.\n");
}
// BF new implemented
void Hardware::Reset_Timer2(void)
{
	timer2->np_timerperiodh = (short)((USTB_timer_value[Selected_Timebase - 23] >> 16) & 0x0000ffff);	// Set High Register of Timer
	timer2->np_timerperiodl = (short)(USTB_timer_value[Selected_Timebase - 23] & 0x0000ffff);		// Set Low Register of Timer
	timer2->np_timerstatus = 0;										// clear the ISR
	
	timer2->np_timercontrol = 0x0007; 									// Set Timer to continous and start

	//timer2->np_timercontrol = np_timercontrol_start_mask;							// Start Timer
	//timer2->np_timercontrol = np_timercontrol_start_mask + np_timercontrol_ito_mask;			// Start Timer and enable Interrupt
	//timer2->np_timercontrol = 0x0005;									// Start Timer and enable Interrupt
	printf("\r\nTimer2 counter value = %d\r\n", USTB_timer_value[Selected_Timebase - 23]);
	//printf("\nTimer2 resetted.\n");
}

//##############################################################################################################################################
// timer 2 interrupt service routine for rollmode
// BF new implemented
void Hardware::ISR_TIMER2(int context)										// Menu Timer service subroutine
{
	//int cnt;
	
	if (context != (int)timer2) return;

	//if (Continius == false) return;

	timer2->np_timerstatus  = 0;										// clear the status register
	//Stop_Timer2();

	Start_Record();
	
//	printf("\nTimer 2 interrupt occured - new record started\n");

}

//##############################################################################################################################################
/* BF -> not needed
// copy/shift routine for rollmode
void Hardware::Copy_in_asm(int cnt, unsigned char *DataArray_in, unsigned char *DataArray_out)
{
    asm("
            ;MOV	%l0, %i0

            ;MOV	%l1, %i1
            ;SUB	%l1, %i0

            ;MOV	%l2, %i2
            ;SUB	%l2, %i0

        copy_asm1 :
            LD      	%r0, [%i1]	; save old value
            EXT8D   	%r0, %i1 	; extract byte

            FILL8	%r0, %r0
            ST8D	[%i2], %r0

            ADDI   	%i1, 1    	; Add Address Counter
            ADDI   	%i2, 1 		; Add Address Counter
                        	
            SUBI   	%i0, 1   	; Decrement Line Counter
            SKPS   	cc_z
            BR     	copy_asm1	
            NOP

        ");

}
*/


//##############################################################################################################################################
// enable timer 3 interupt for rotary interface
void Hardware::DoEnableTimer3Interrupt(void)										// Enable service routine
{					
	timer_rotary_busy->np_timerperiodh = timerrotPeriod >> 16;									// Set High Register of Timer
	timer_rotary_busy->np_timerperiodl = timerrotPeriod & 0xffff;									// Set Low Register of Timer
    timer_rotary_busy->np_timerstatus = 0;														// write anything to clear the IRQ

	nr_installuserisr(na_timer3_irq,ISR_TIMER3,(int)timer_rotary_busy); 						// Install timer isr

	timer_rotary_busy->np_timercontrol = timer_rotary_busy->np_timercontrol | np_timercontrol_ito_mask;  	// Enable timer interrupt
	
#ifdef _Debug_IRQ_	
	if (Debug_Mode) printf("Timer3 interrupt enabled & started.\n"); 										// print on console
#endif	
}
//##############################################################################################################################################
// disable timer 3 interupt for rotary interface
void Hardware::DoDisableTimer3Interrupt(void)										// Disable service routine
{
	nr_installuserisr(na_timer3_irq,0,0); 											// Install empty routine for timer irq
	timer_rotary_busy->np_timercontrol = timer_rotary_busy->np_timercontrol & ~np_timercontrol_ito_mask; 	// Disable timer interrupt
}

//##############################################################################################################################################
// timer 3 interrupt service routine for rotary interface and popup menus
void Hardware::ISR_TIMER3(int context)				// Menu Timer service subroutine
{
	char fchanged = 0;
	char already_saved = 0;					// TMW added variable

	//BF del tc_test_var2++;

	timer_rotary_busy->np_timerstatus = 0;	// write anything to clear the IRQ
    	
	if ((Search_Mode) || (Splash_drawed)) return;

	if(QP_request) return;
	
 	if (MenuItemPushed[0] == 1) { fchanged = 1; MenuItemPushed[0] = 0; MenuItemPushed_old[0] = 1; MenuItemChanged[0] = 1;}
	if (MenuItemPushed[1] == 1) { fchanged = 1; MenuItemPushed[1] = 0; MenuItemPushed_old[1] = 1; MenuItemChanged[1] = 1;}
	if (MenuItemPushed[2] == 1) { fchanged = 1; MenuItemPushed[2] = 0; MenuItemPushed_old[2] = 1; MenuItemChanged[2] = 1;}
	if (MenuItemPushed[3] == 1) { fchanged = 1; MenuItemPushed[3] = 0; MenuItemPushed_old[3] = 1; MenuItemChanged[3] = 1;}
	if (MenuItemPushed[4] == 1) { fchanged = 1; MenuItemPushed[4] = 0; MenuItemPushed_old[4] = 1; MenuItemChanged[4] = 1;}
	if (MenuItemPushed[5] == 1) { fchanged = 1; MenuItemPushed[5] = 0; MenuItemPushed_old[5] = 1; MenuItemChanged[5] = 1;}

	if (StatusbarChanged) { Display::RemoveStatusBtn(); }			// Remove the Status Button
	if (MenuPopupActive > -1)
    	{
  		config_changed = true;						// BF write config
       		fchanged = 0;
        	Display::DRAWMENUPOPDOWN();
		already_saved = 1;						// TMW added variable
    	}	 

// TMW changed   -> Bf changed for new menu structure 
	if ((Memory_Window_visible) && (MenuStatus[MENU_TIMEBASE][5] == 240)) 	// if Memory Window is visible and
    	{									// Browse Function not active
		if ( already_saved == 0 )					// TMW added variable
		{
			config_changed = true;  				// BF write config
		}
		
      		Display::DRAWMEMORY(1, 0, 0);     			  	// Close Memory Window and
        	//Display::DRAW_ALL_CURSOR();	// TMW removed			// redraw all cursors due to closure
    	}
// TMW change ends
	
	if (fchanged == 1) { New_Menu = Active_Menu; Menu_Changed = 1; }
	

	ButtonChanged = 0;
	RoteryReady = 0;

	Menu_Popup_visible =0;

   	acq_ready->np_pioedgecapture = 0;

}
//##############################################################################################################################################
// Reset timer 3 
void Hardware::ResetTimer(void)	// Reset Timer
{
	long timerVal;
	long timerPeriod;

	timer_rotary_busy->np_timercontrol = ((timer_rotary_busy->np_timercontrol & 3) + np_timercontrol_stop_mask);// & ~np_timercontrol_cont_mask;	// Stop Timer
	timer_rotary_busy->np_timerstatus = 0;								// write anything to clear the IRQ
		
	timer_rotary_busy->np_timerperiodh = timerrotPeriod >> 16;			// Set High Register of Timer
	timer_rotary_busy->np_timerperiodl = timerrotPeriod & 0xffff;		// Set Low Register of Timer

	timer_rotary_busy->np_timercontrol = ((timer_rotary_busy->np_timercontrol & 3) + np_timercontrol_start_mask);// | np_timercontrol_cont_mask;	// Start Timer

}
//##############################################################################################################################################
// set hardware switches on the mainboard for voltage range
void Hardware::SetSwitches(char channel, int voltage)
{
	bool DoNothing = 0;
	short dat_buf = 0;
	short CalcBufInt = 0;	
	long adr_buf = 0x00000000;
	long outbuf = 0x00000000;
				
	switch(voltage)
	{
		case -1 :
		{
			switch(channel)
			{
				case 1 : dat_buf = SwitchesCH1;break;
				case 2 : dat_buf = SwitchesCH2;break;
				case 3 : dat_buf = SwitchesCH3;break;
				case 4 : dat_buf = SwitchesCH4;break;
				case 5 : dat_buf = SwitchesTB;break;				
			}	
			break;		
		}			
	
		case 0 : dat_buf = 0x0015; break;
		case 1 : dat_buf = 0x0015; break;
		case 2 : dat_buf = 0x0015; break;
		case 3 : dat_buf = 0x0015; break;
		case 4 : dat_buf = 0x0055; break;
		case 5 : dat_buf = 0x00C5; break;
		case 6 : dat_buf = 0x0019; break;
		case 7 : dat_buf = 0x0059; break;
		case 8 : dat_buf = 0x00C9; break;
		case 9 : dat_buf = 0x001A; break;
		case 10 : dat_buf = 0x005A; break;
		case 11 : dat_buf = 0x00CA; break;
	}

	switch(channel)
	{
		case 1:
		{
			adr_buf = 0x70000000;		// channel 1 = address 7 (hardware)

			// Set AC Bits
			dat_buf = dat_buf & 0xF0DF;
		
			if (MenuStatus[MENU_CHANNEL1][0] == 8) dat_buf = dat_buf | 0x0100;
			if (MenuStatus[MENU_CHANNEL2][0] == 8) dat_buf = dat_buf | 0x0200;
			if (MenuStatus[MENU_CHANNEL3][0] == 8) dat_buf = dat_buf | 0x0400;
			if (MenuStatus[MENU_CHANNEL4][0] == 8) dat_buf = dat_buf | 0x0800;	
		
			// BW Limit
			if (MenuStatus[MENU_CHANNEL1][1] == 241) dat_buf = dat_buf | 0x0020;

			SwitchesCH1 = dat_buf;
			
			VoltageChangedCh1 = 1;
#ifdef _Debug_			
			if (Debug_Mode) printf("Switches : %x , erg : %x \n", SwitchesCH1, (adr_buf | SwitchesCH1));
#endif			
			break;	
		}
		case 2:
		{
			adr_buf = 0x50000000;		// channel 2 = address 5 (hardware)
						
			dat_buf = dat_buf & 0xFFDF;
			if (MenuStatus[MENU_CHANNEL2][1] == 241) dat_buf = dat_buf | 0x0020;
			
			SwitchesCH2 = dat_buf;
            			
			VoltageChangedCh2 = 1;
#ifdef _Debug_			
			if (Debug_Mode) printf("Switches : %x , erg : %x \n", SwitchesCH2, (adr_buf | SwitchesCH2));
#endif			
			break;	
		}
		case 3:
		{
			adr_buf = 0x10000000;		// channel 3 = address 4 (hardware)
					
			dat_buf = dat_buf & 0xFFDF;
			if (MenuStatus[MENU_CHANNEL3][1] == 241) dat_buf = dat_buf | 0x0020;
			
			SwitchesCH3 = dat_buf;
            			
			VoltageChangedCh3 = 1;
#ifdef _Debug_			
			if (Debug_Mode) printf("Switches : %x , erg : %x \n", SwitchesCH3, (adr_buf | SwitchesCH3));
#endif			
			break;	
		}
		case 4:
		{
			adr_buf = 0x30000000;		// channel 4 = address 3 (hardware)
				
            dat_buf = dat_buf & 0xFFDF;	
			if (MenuStatus[MENU_CHANNEL4][1] == 241) dat_buf = dat_buf | 0x0020;
			
			SwitchesCH4 = dat_buf;
            			
			VoltageChangedCh4 = 1;
#ifdef _Debug_			
			if (Debug_Mode) printf("Switches : %x , erg : %x \n", SwitchesCH4, (adr_buf | SwitchesCH4));
#endif			
			break;	
		}		
		case 5:
		{
			adr_buf = 0x20000000;		// trigger channel = address 2 (hardware)
			
			SwitchesTB = voltage;
#ifdef _Debug_			
			if (Debug_Mode) printf("Switches : %x , erg : %x \n", SwitchesTB, (adr_buf | SwitchesTB));
#endif			
			break;	
		}				
	}

	switch(channel)
	{
		case 1: outbuf = adr_buf | SwitchesCH1; break;
		case 2: outbuf = adr_buf | SwitchesCH2; break;
		case 3: outbuf = adr_buf | SwitchesCH3; break;
		case 4: outbuf = adr_buf | SwitchesCH4; break;
		case 5: outbuf = adr_buf | SwitchesTB; break;		
		case 6: outbuf = 0xFFFFFFFF; break;		
		case 7: outbuf = 0x00000000; break;				
	}	
#ifdef _Debug_		
    if (Debug_Mode) printf("outbuf1 : %x\n", outbuf);
#endif       		
    serdata->np_piodata = outbuf;//TurnBits(outbuf);
	
	serstartsw->np_piodata = 1;
	serstartsw->np_piodata = 0;	
		
	nr_delay(15);

	switch(channel)
	{
		case 1: outbuf = (adr_buf | SwitchesCH1) & 0xFFFFFFF0; break;
		case 2: outbuf = (adr_buf | SwitchesCH2) & 0xFFFFFFF0; break;
		case 3: outbuf = (adr_buf | SwitchesCH3) & 0xFFFFFFF0; break;
		case 4: outbuf = (adr_buf | SwitchesCH4) & 0xFFFFFFF0; break;
	}		
#ifdef _Debug_
    if (Debug_Mode) printf("outbuf2 : %x\n", outbuf);
#endif
    if ((channel > 0) && (channel < 5))
    {
        serdata->np_piodata = outbuf;//TurnBits(outbuf);	
	
	   serstartsw->np_piodata = 1;
	   serstartsw->np_piodata = 0;	

	   nr_delay(15);
    }
#ifdef _Debug_	
	if (Debug_Mode)
    {
	    switch(channel)
	    {	
		    case 1: printf("Switches : %x , erg : %x\n", SwitchesCH1, (adr_buf | SwitchesCH1) & 0xFFFFFFF0); break;
		    case 2: printf("Switches : %x , erg : %x\n", SwitchesCH2, (adr_buf | SwitchesCH2) & 0xFFFFFFF0); break;
		    case 3: printf("Switches : %x , erg : %x\n", SwitchesCH3, (adr_buf | SwitchesCH3) & 0xFFFFFFF0); break;
		    case 4: printf("Switches : %x , erg : %x\n", SwitchesCH4, (adr_buf | SwitchesCH4) & 0xFFFFFFF0); break;
		    case 5: printf("Switches : %x , erg : %x\n", SwitchesTB, (adr_buf | SwitchesTB) & 0xFFFFFFFF); break;
	    }
    }
#endif					
//	nr_delay(1);
		
	switch(channel)
	{	
		case 1: SwitchesCH1Old = SwitchesCH1; break;
		case 2: SwitchesCH2Old = SwitchesCH2; break;
		case 3: SwitchesCH3Old = SwitchesCH3; break;
		case 4: SwitchesCH4Old = SwitchesCH4; break;
	}
}

void Hardware::SetDacOffset(char channel)
{
	long CalcBufInt = 0;	
	long BufInt = 0;
	long BufInt2 = 0;	
	long outbuf = 0x00000000;		


	switch(channel)
	{
		case 1 :	//if (CH1_DAC_Offset != CH1_DAC_OffsetOld)
					{
						BufInt = CH1_DAC_Offset;
						BufInt2 = (0x00310000 | (BufInt * 4));


						// Bei gelegenheit gegen Turnbits tauschen
						outbuf = (0x60000000 | BufInt2);
						
						serdata->np_piodata = outbuf;
						
						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
										
						nr_delay(5);						
					}	
					break;	
					
		case 2 :	//if (CH2_DAC_Offset != CH2_DAC_OffsetOld)
					{
						BufInt = CH2_DAC_Offset;
						BufInt2 = (0x00300000 | (BufInt * 4));						

                        			outbuf = (0x60000000 | BufInt2);
						
						serdata->np_piodata = outbuf;
						
						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
										
						nr_delay(5);						
					}	
					break;	
					
		case 3 :	//if (CH3_DAC_Offset != CH3_DAC_OffsetOld)
					{
						BufInt = CH3_DAC_Offset;
						BufInt2 = (0x00310000 | (BufInt * 4));	
						
                        			outbuf = (0x40000000 | BufInt2);
						
						serdata->np_piodata = outbuf;
						
						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
										
						nr_delay(5);						
					}	
					break;	
					
		case 4 :	//if (CH4_DAC_Offset != CH4_DAC_OffsetOld)
					{
						BufInt = CH4_DAC_Offset;
						BufInt2 = (0x00300000 | (BufInt * 4));						

                        			outbuf = (0x40000000 | BufInt2);
						
						serdata->np_piodata = outbuf;
						
						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
										
						nr_delay(5);						
					}	
					break;	
	}											
#ifdef _Debug_
	if (Debug_Mode) printf("ch : %d cb : %x bi : %x bi2 : %x  ob : %x \n", channel, CalcBufInt, BufInt, BufInt2, outbuf);
#endif
}

void Hardware::SetCHDacOffset(char channel)
{
	switch(channel)
	{
		case 1 : 	//if (CH1_DAC_1 != CH1_DAC_1Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH1_DAC_1 | 0x0600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	

						nr_delay(1);
					}

					//if (CH1_DAC_2 != CH1_DAC_2Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH1_DAC_2 | 0x1600; //0x0E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
										
					//if (CH1_DAC_3 != CH1_DAC_3Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH1_DAC_3 | 0x1E00; //0x1600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
				
					//if (CH1_DAC_4 != CH1_DAC_4Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH1_DAC_4 | 0x2600; //0x1E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);	
					}
					
					break;														
															
		case 2 : 	//if (CH2_DAC_1 != CH2_DAC_1Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH2_DAC_1 | 0x0E00; //0x2600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}	
						
					//if (CH2_DAC_2 != CH2_DAC_2Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH2_DAC_2 | 0x3E00; //0x2E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}				

					//if (CH2_DAC_3 != CH2_DAC_3Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH2_DAC_3 | 0x3600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
						
					//if (CH2_DAC_4 != CH2_DAC_4Old)
				 	{
						serdata->np_piodata = 0x80000000 | CH2_DAC_4 | 0x2E00; //0x3E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
										
					break;

		case 3 : 	//if (CH3_DAC_1 != CH3_DAC_1Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH3_DAC_1 | 0x0600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	

						nr_delay(1);		
					}			

					//if (CH3_DAC_2 != CH3_DAC_2Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH3_DAC_2 | 0x0E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
										
					//if (CH3_DAC_3 != CH3_DAC_3Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH3_DAC_3 | 0x1600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
				
					//if (CH3_DAC_4 != CH3_DAC_4Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH3_DAC_4 | 0x1E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);	
					}
					
					break;														
															
		case 4 : 	//if (CH4_DAC_1 != CH4_DAC_1Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH4_DAC_1 | 0x2600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);	
					}
						
					//if (CH4_DAC_2 != CH4_DAC_2Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH4_DAC_2 | 0x2E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}				

					//if (CH4_DAC_3 != CH4_DAC_3Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH4_DAC_3 | 0x3600;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
						
					//if (CH4_DAC_4 != CH4_DAC_4Old)
				 	{
						serdata->np_piodata = 0x90000000 | CH4_DAC_4 | 0x3E00;

						serstartsw->np_piodata = 1;
						serstartsw->np_piodata = 0;	
						
						nr_delay(1);
					}
										
					break;					
					
	}	
}

void Hardware::SetupADC(void)
{
	mode->np_piodata = 0x01;
		
	if (triggering == 0) WRITEADC(1, (ctrl_reg | 0x0001) + (adc_ctrl_reg << 16));																		
	else if(triggering == 1) WRITEADC(1, ctrl_reg + (adc_ctrl_reg << 16));
	else WRITEADC(1, (ctrl_reg & 0xFFFE) + (adc_ctrl_reg << 16));					

	WRITEADC(1, timebase_reg);
	
	WRITEADC(1, pre_reg + (channel_Adr_add << 16));
    	
	WRITEADC(1, trg_val_CHI_reg + (trg_val_CHII_reg << 8) + (trig_range_reg << 16));
	WRITEADC(1, (0xFFFFFFFF - trig_holdoff_reg));

	//BF set the grid color via trigger width register -> function is a little bit dubious
	WRITEADC(1, trig_width_reg + (GridColor_Val << 26));	// ->GridColorArray[4] = {0x00, 0x15, 0x2A, 0x3F};
	
	WRITEADC(1, adc_change12_reg);
	
	WRITEADC(1, adc_ctr12_reg);

	mode->np_piodata = 0x00;

	if (NumberOfChannels == 4)
	{
		mode->np_piodata = 0x01;
								
		if(triggering == 3) WRITEADC(3, ctrl_reg + (adc_ctrl_reg << 16));
		else WRITEADC(3, (ctrl_reg & 0xFFFE) + (adc_ctrl_reg << 16));
	
		WRITEADC(3, timebase_reg);
		
		WRITEADC(3, pre_reg + (channel_Adr_add2 << 16));
		
		WRITEADC(3, trg_val_CHIII_reg + (trg_val_CHIV_reg << 8) + (trig_range_reg << 16));	
		WRITEADC(3, (0xFFFFFFFF - trig_holdoff_reg));
	
		//BF set the grid color via trigger width register -> function is a little bit dubious		
		WRITEADC(3, trig_width_reg + (GridColor_Val << 26));	// ->GridColorArray[4] = {0x00, 0x15, 0x2A, 0x3F};
	
	
	//BF -> to be checked out  ????????????
	//BF del	WRITEADC(3, adc_change34_reg);
		WRITEADC(3, adc_change12_reg);	//BF test
		WRITEADC(3, adc_ctr12_reg);
	//BF???????????????????????????????????
	
		mode->np_piodata = 0x00;
    	}
#ifdef _Debug_	
	if (Debug_Mode) printf("ctr %x actr %x tb %x pr %x tv1 %x tv2 %x tv1 %x tv2 %x trr %x trw %x cha %x adcch12 %x adcch34 %x adcctr12 %x adcctr34 %x\n", ctrl_reg, adc_ctrl_reg, timebase_reg, pre_reg, trg_val_CHI_reg, trg_val_CHII_reg, trg_val_CHIII_reg, trg_val_CHIV_reg, trig_range_reg, trig_width_reg, channel_Adr_add, adc_change12_reg, adc_change34_reg, adc_ctr12_reg, adc_ctr34_reg);
#endif
}

void Hardware::WRITEADC(unsigned char which, unsigned long value)
{	
	switch(which)
	{
		case 1 :
				asm("		
						MOV		%r0,%i1					; Address of Buffer
						PFX		%hi(0x00A00000)
						MOVI	%l0,%lo(0x00A00000)
						PFX		%xhi(0x00A00000)
						MOVHI	%l0,%xlo(0x00A00000)				
			
						ST		[%l0], %r0		
					");	
				break;
		case 2 :
				asm("		
						MOV		%r0,%i1					; Address of Buffer
						PFX		%hi(0x00A00010)
						MOVI	%l0,%lo(0x00A00010)
						PFX		%xhi(0x00A00010)
						MOVHI	%l0,%xlo(0x00A00010)				
			
						ST		[%l0], %r0		
					");	
				break;
		case 3 :
				asm("		
						MOV		%r0,%i1					; Address of Buffer
						PFX		%hi(0x00A00020)
						MOVI	%l0,%lo(0x00A00020)
						PFX		%xhi(0x00A00020)
						MOVHI	%l0,%xlo(0x00A00020)				
			
						ST		[%l0], %r0		
					");	
				break;
		case 4 :
				asm("		
						MOV		%r0,%i1					; Address of Buffer
						PFX		%hi(0x00A00030)
						MOVI	%l0,%lo(0x00A00030)
						PFX		%xhi(0x00A00030)
						MOVHI	%l0,%xlo(0x00A00030)				
			
						ST		[%l0], %r0		
					");	
				break;
	}
}

unsigned long Hardware::READADC(unsigned char which)
{





	switch(which)
	{
		case 1 :
				asm("		
						PFX		%hi(0x00A00000)
						MOVI	%l0,%lo(0x00A00000)
						PFX		%xhi(0x00A00000)
						MOVHI	%l0,%xlo(0x00A00000)				
		
						LD		%r0,[%l0]	
		
						MOV		%i0, %r0
					");	
				break;
		case 2 :
				asm("		
						PFX		%hi(0x00A00010)
						MOVI	%l0,%lo(0x00A00010)
						PFX		%xhi(0x00A00010)
						MOVHI	%l0,%xlo(0x00A00010)				
		
						LD		%r0,[%l0]	
		
						MOV		%i0, %r0	
					");	
				break;
		case 3 :
				asm("		
						PFX		%hi(0x00A00020)
						MOVI	%l0,%lo(0x00A00020)
						PFX		%xhi(0x00A00020)
						MOVHI	%l0,%xlo(0x00A00020)				
		
						LD		%r0,[%l0]	
		
						MOV		%i0, %r0	
					");	
				break;
		case 4 :
				asm("		
						PFX		%hi(0x00A00030)
						MOVI	%l0,%lo(0x00A00030)
						PFX		%xhi(0x00A00030)
						MOVHI	%l0,%xlo(0x00A00030)				
		
						LD		%r0,[%l0]	
		
						MOV		%i0, %r0	
					");	
				break;
	}
}	
//##############################################################################################################################################################
//BF set registers for ADC reading with correction values and value count
void Hardware::PREPARE_READADC(unsigned char correct1, unsigned char correct2, unsigned char correct3, unsigned char correct4, unsigned int count)
{
    asm("
            MOV		%r3, %i0
            MOV		%r4, %i1
            MOV		%r5, %i2
            MOV		%r6, %i3
            MOV		%r7, %i4
        ");
}
//##############################################################################################################################################################
//BF sort, correct and recalculate ADC-values
//BF changed by Stefan to avoid correction error in inverting and averaging mode
void Hardware::READADC_ALL(unsigned char which, unsigned char *DataArray1, unsigned char inverse, unsigned int zero, unsigned char averageval, unsigned char highspeed)
{

    asm("
            PFX	%hi(0xFEFEFEFE)                   ; Set MASK
            MOVI	%r10,%lo(0xFEFEFEFE)
            PFX	%xhi(0xFEFEFEFE)
            MOVHI	%r10,%xlo(0xFEFEFEFE)

            MOV		%l1, %r7               ; set address offset memory 2

            IFRZ    %i5                     ; highspeeed timebases?
            BR      lpr_slow                ; jump to slow tb configuration
            NOP                   									

            MOV		%l4, %i1               ; set address offset memory 2
            PFX     %hi(0x0001)
            ADDI    %l4, %lo(0x0001);
						
            MOV		%l5, %i1               ; set address offset memory 3
            PFX     %hi(0x0002)
            ADDI    %l5, %lo(0x0002);
						
            MOV		%l6, %i1               ; set address offset memory 4
            PFX     %hi(0x0003)
            ADDI    %l6, %lo(0x0003);

            BR      lpr_channel
            NOP

        lpr_slow:
            MOV		%l4, %i1               ; set address offset memory 2
            PFX     %hi(0x1000)
            ADDI    %l4, %lo(0x1000);
						
            MOV		%l5, %i1               ; set address offset memory 3
            PFX     %hi(0x2000)
            ADDI    %l5, %lo(0x2000);
						
            MOV		%l6, %i1               ; set address offset memory 4
            PFX     %hi(0x3000)
            ADDI    %l6, %lo(0x3000);

      lpr_channel:


            PFX     %hi(0x00917440)         ; load address channel
            MOVI	%l0,%lo(0x00917440)
            PFX		%xhi(0x00917440)
            MOVHI	%l0,%xlo(0x00917440)

	
        lpr1:
            LD		%l2, [%l0]
            NOT     %l2	
            
            ; start mem 1			
            MOV		%r0, %l2  							


            EXT8S	%r0, 0
	
	    SUB     %r0, %r3		;Offsetadjustment (Stefan)

            IFS     cc_n
            PFX     %hi(0)
            MOVI    %r0, %lo(0)	
						
            IFRZ      %i2                 ; inverting
            BR        lpr1s
            NOP						
						
            ; start inverting
						
            CMP       %r0, %i3            ; is Vnew > ZL
            IFS       cc_nc
            BR        lpr1i
            NOP						
						
            ; Vnew < ZeroLevel
						
            MOV       %r2, %i3            ; store ZeroLevel	
            SUB       %r2, %r0            ; ZL - Vnew = Vcalc0	
            ADD       %r2, %i3            ; Vcalc0 + ZL = Vcalc1
						
            PFX       %hi(255)
            CMPI      %r2, %lo(255)
            IFS       cc_nc
            PFX       %hi(255)
            MOVI      %r2, %lo(255)		
						
            MOV       %r0, %r2            ; store result
	
            BR        lpr1s
            NOP		

        lpr1i:

            MOV       %r2, %i3            ; store ZeroLevel		
            SUB       %r0, %r2            ; Vnew - ZL = Vcalc0		
            SUB       %r2, %r0            ; ZL - Vcalc0 = Vcalc1
            IFS       cc_v		
            PFX       %hi(0)
            MOVI      %r2, %lo(0)	
	
            MOV       %r0, %r2            ; store result

            ; end inverting		

						
        lpr1s:
      						
            IFRZ      %i4                 ; is average = 0
            BR        lpr1e
            NOP						
	
            ; start averaging

            LD        %l7, [%i1]          ; save old value
            EXT8D     %l7, %i1            ; extract byte

            CMP       %r0, %l7
            IFS       cc_nc
            BR        lpr1a						
            NOP
						
            ; Vnew < ZL

            MOV       %r2, %l7            ; store Vold	
            SUB       %r2, %r0            ; Vold - Vnew = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1
            SUB       %l7, %r2            ; Vold - Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0

            BR        lpr1e
            NOP	
						
        lpr1a:

            ; Vnew > ZL
						
            MOV       %r2, %r0            ; store Vnew	
            SUB       %r2, %l7            ; Vnew - Vold = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1	
            ADD       %l7, %r2            ; Vold + Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0
						
        lpr1e:							

						
            FILL8	%r0, %r0
            ST8D	[%i1], %r0
					
            ; start mem 2		
            MOV		%r0, %l2  

            EXT8S	%r0, 1
	
	    SUB     %r0, %r4		; offsetadjustment(Stefan)
			
            IFS     cc_n
            PFX     %hi(0)
            MOVI    %r0, %lo(0)		
			
            IFRZ      %i2                 ; inverting
            BR        lpr2s
            NOP						
						
            ; start inverting
						
            CMP       %r0, %i3            ; is Vnew > ZL
            IFS       cc_nc
            BR        lpr2i
            NOP						
						
            ; Vnew < ZeroLevel
						
            MOV       %r2, %i3            ; store ZeroLevel		
            SUB       %r2, %r0            ; ZL - Vnew = Vcalc0		
            ADD       %r2, %i3            ; Vcalc0 + ZL = Vcalc1
						
            PFX       %hi(255)
            CMPI      %r2, %lo(255)
            IFS       cc_nc
            PFX       %hi(255)
            MOVI      %r2, %lo(255)		
						
            MOV       %r0, %r2            ; store result
	
            BR        lpr2s
            NOP			
						
        lpr2i:

            MOV       %r2, %i3            ; store ZeroLevel		
            SUB       %r0, %r2            ; Vnew - ZL = Vcalc0			
            SUB       %r2, %r0            ; ZL - Vcalc0 = Vcalc1
            IFS       cc_v		
            PFX       %hi(255)
            MOVI      %r2, %lo(255)		
						
            MOV       %r0, %r2            ; store result

            ; end inverting		
						
						
        lpr2s:
	
            IFRZ      %i4                 ; is average = 0
            BR        lpr2e
            NOP						
	
            ; start averaging

            LD        %l7, [%l4]          ; save old value
            EXT8D     %l7, %l4            ; extract byte

            CMP       %r0, %l7
            IFS       cc_nc
            BR        lpr2a						
            NOP
						
            ; Vnew < ZL

            MOV       %r2, %l7            ; store Vold	
            SUB       %r2, %r0            ; Vold - Vnew = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1
            SUB       %l7, %r2            ; Vold - Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0

            BR        lpr2e
            NOP	
						
        lpr2a:
                	
            ; Vnew > ZL
						
            MOV       %r2, %r0            ; store Vnew	
            SUB       %r2, %l7            ; Vnew - Vold = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1						
            ADD       %l7, %r2            ; Vold + Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0
						
        lpr2e:							
            			
            FILL8	%r0, %r0
            ST8D	[%l4], %r0

            ; start mem 3								
            MOV     %r0, %l2  							

            EXT8S	%r0, 2
			            
			SUB     %r0, %r5			;offsetadjustment(Stefan)

            IFS     cc_n
            PFX     %hi(0)
            MOVI    %r0, %lo(0)	
						
            IFRZ    %i2                 ; inverting
            BR      lpr3s
            NOP						
						
            ; start inverting
						
            CMP       %r0, %i3            ; is Vnew > ZL
            IFS       cc_nc
            BR        lpr3i
            NOP						
						
            ; Vnew < ZeroLevel
						
            MOV       %r2, %i3            ; store ZeroLevel							
            SUB       %r2, %r0            ; ZL - Vnew = Vcalc0						
            ADD       %r2, %i3            ; Vcalc0 + ZL = Vcalc1
						
            PFX       %hi(255)
            CMPI      %r2, %lo(255)
            IFS       cc_nc
            PFX       %hi(255)
            MOVI      %r2, %lo(255)		
						
            MOV       %r0, %r2            ; store result
                        						
            BR        lpr3s
            NOP								
						
        lpr3i:

            MOV       %r2, %i3            ; store ZeroLevel							
            SUB       %r0, %r2            ; Vnew - ZL = Vcalc0						
            SUB       %r2, %r0            ; ZL - Vcalc0 = Vcalc1
            IFS       cc_v						
            PFX       %hi(255)
            MOVI      %r2, %lo(255)								
						
            MOV       %r0, %r2            ; store result

            ; end inverting						
						
						
        lpr3s:
                    						
            IFRZ      %i4                 ; is average = 0
            BR        lpr3e
            NOP						
	
            ; start averaging

            LD        %l7, [%l5]          ; save old value
            EXT8D     %l7, %l5            ; extract byte

            CMP       %r0, %l7
            IFS       cc_nc
            BR        lpr3a						
            NOP
						
            ; Vnew < ZL

            MOV       %r2, %l7            ; store Vold	
            SUB       %r2, %r0            ; Vold - Vnew = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1
            SUB       %l7, %r2            ; Vold - Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0

            BR        lpr3e
            NOP	
						
        lpr3a:
                	
            ; Vnew > ZL
						
            MOV       %r2, %r0            ; store Vnew	
            SUB       %r2, %l7            ; Vnew - Vold = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1						
            ADD       %l7, %r2            ; Vold + Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0
						
        lpr3e:							
						
            FILL8	%r0, %r0
            ST8D	[%l5], %r0
			
            ; start mem 4								
            MOV		%r0, %l2  							

            EXT8S	%r0, 3
			
			SUB     %r0, %r6				;offsetadjustment (Stefan)
			
            IFS     cc_n
            PFX     %hi(0)
            MOVI    %r0, %lo(0)	
						
            IFRZ      %i2                 ; inverting
            BR        lpr4s
            NOP						
						
            ; start inverting
						
            CMP       %r0, %i3            ; is Vnew > ZL
            IFS       cc_nc
            BR        lpr4i
            NOP						
						
            ; Vnew < ZeroLevel
						
            MOV       %r2, %i3            ; store ZeroLevel							
            SUB       %r2, %r0            ; ZL - Vnew = Vcalc0						
            ADD       %r2, %i3            ; Vcalc0 + ZL = Vcalc1
						
            PFX       %hi(255)
            CMPI      %r2, %lo(255)
            IFS       cc_nc
            PFX       %hi(255)
            MOVI      %r2, %lo(255)	; (0) ???	
						
            MOV       %r0, %r2            ; store result
                        						
            BR        lpr4s
            NOP								
						
        lpr4i:

            MOV       %r2, %i3            ; store ZeroLevel							
            SUB       %r0, %r2            ; Vnew - ZL = Vcalc0						
            SUB       %r2, %r0            ; ZL - Vcalc0 = Vcalc1
            IFS       cc_v						
            PFX       %hi(255)
            MOVI      %r2, %lo(255)								
						
            MOV       %r0, %r2            ; store result

            ; end inverting						
						
						
        lpr4s:
                    						
            IFRZ      %i4                 ; is average = 0
            BR        lpr4e
            NOP						
	
            ; start averaging

            LD        %l7, [%l6]          ; save old value
            EXT8D     %l7, %l6            ; extract byte

            CMP       %r0, %l7
            IFS       cc_nc
            BR        lpr4a						
            NOP
						
            ; Vnew < ZL

            MOV       %r2, %l7            ; store Vold	
            SUB       %r2, %r0            ; Vold - Vnew = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1
            SUB       %l7, %r2            ; Vold - Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0

            BR        lpr4e
            NOP	
						
        lpr4a:
                	
            ; Vnew > ZL
						
            MOV       %r2, %r0            ; store Vnew	
            SUB       %r2, %l7            ; Vnew - Vold = Vcalc0
            LSR       %r2, %i4            ; Vcalc0 >> avg = Vcalc1						
            ADD       %l7, %r2            ; Vold + Vcalc1 = Vcalc2

            MOV       %r0, %l7            ; store result in r0
						
        lpr4e:							
            			
            FILL8	%r0, %r0
            ST8D	[%l6], %r0


            ADDI   %l0, 4                            ; Add Address Counter

            IFRZ    %i5                     ; highspeeed timebases?
            BR      lpr_slow_ac             ; jump to slow address calculaten
            NOP
						
            ; calc new adresses
            ADDI   %i1, 4                            ; Add Address Counter
            ADDI   %l4, 4                            ; Add Address Counter
            ADDI   %l5, 4                            ; Add Address Counter
            ADDI   %l6, 4                            ; Add Address Counter
                        	
            SUBI   %l1, 1                            ; Decrement Line Counter
            SKPS   cc_z
            BR     lpr1	
            NOP	

            BR     lprend
            NOP	


        lpr_slow_ac:
            ; calc new adresses
            ADDI   %i1, 1                            ; Add Address Counter
            ADDI   %l4, 1                            ; Add Address Counter
            ADDI   %l5, 1                            ; Add Address Counter
            ADDI   %l6, 1                            ; Add Address Counter
                        	
            SUBI   %l1, 1                            ; Decrement Line Counter
            SKPS   cc_z
            BR     lpr1	
            NOP

        lprend:		
    ");

}
//#######################################################################################################
//BF -> get data from ADC  -  Assembler routine 
void Hardware::READADC_ALL2(unsigned char which, unsigned long *DataArray1, unsigned int count)
{

    asm("
            CMPI    %i0, 0x01               ; Is it channel 1
            IFS     cc_z
            BR      lpr1ch1n
            NOP

            CMPI    %i0, 0x02               ; Is it channel 2
            IFS     cc_z
            BR      lpr1ch2n
            NOP

            CMPI    %i0, 0x03               ; Is it channel 3
            IFS     cc_z
            BR      lpr1ch3n
            NOP

            CMPI    %i0, 0x04               ; Is it channel 4
            IFS     cc_z
            BR      lpr1ch4n
            NOP

        lpr1ch1n:
            PFX     %hi(0x00A00000)         ; load address channel 1
            MOVI	%l0,%lo(0x00A00000)
            PFX		%xhi(0x00A00000)
            MOVHI	%l0,%xlo(0x00A00000)
            BR      lpr1n
            NOP

        lpr1ch2n:
            PFX     %hi(0x00A00010)         ; load address channel 2
            MOVI	%l0,%lo(0x00A00010)
            PFX		%xhi(0x00A00010)
            MOVHI	%l0,%xlo(0x00A00010)
            BR      lpr1n
            NOP

        lpr1ch3n:
            PFX     %hi(0x00A00020)         ; load address channel 3
            MOVI	%l0,%lo(0x00A00020)
            PFX		%xhi(0x00A00020)
            MOVHI	%l0,%xlo(0x00A00020)
            BR      lpr1n
            NOP

        lpr1ch4n:
            PFX     %hi(0x00A00030)         ; load address channel 4
            MOVI	%l0,%lo(0x00A00030)
            PFX		%xhi(0x00A00030)
            MOVHI	%l0,%xlo(0x00A00030)
	
        lpr1n:
            LD		%l2, [%l0]
	
            MOV		%r0, %l2  	

            ST  	[%i1], %r0
						
           					 ; calc new adresses
            ADDI   %i1, 4                            ; Add Address Counter

            SUBI   %i2, 1                            ; Decrement Line Counter
            SKPS   cc_z
            BR     lpr1n	
            NOP
    ");

}

//#######################################################################################################
//BF -> get data from ADC
//BF new C-coded hardware routine as replacement for READADC_ALL2()
void Hardware::ADC_ReadData(unsigned char which, unsigned long *DataArray1, unsigned int count)
{

		//coded by Guido

		unsigned long *source=0;
		
			
		switch (which)
		{
			case  	1:
				source = ((unsigned long*)(0x00A00000)); 	//load address channel 1
				break;
				
			case	2:
				source = ((unsigned long*)(0x00A00010));	//load address channel 2
				break;
				
			case	3:
				source = ((unsigned long*)(0x00A00020));	//load address channel 3
				break;
				
			case	4:
				source = ((unsigned long*)(0x00A00030)); 	//load address channel 4
				break;
		}	
		for (unsigned int i = 0; i < count; i++)
		{
			DataArray1[i] = *source;
		}

}

//##############################################################################################################################################################
//BF sort, correct and recalculate ADC-values
//BF new C-coded hardware routine as replacement for READADC_ALL()
void Hardware::ADC_ProcessData(unsigned char which, unsigned char *DataArray1, unsigned char inverse, unsigned int zero, unsigned char averageval, unsigned char highspeed)
{
	//coded by Guido

	static unsigned long mask = 0xFEFEFEFE;  	//set MASK (but never use it???)
	static unsigned int lw_count = 4096;		//number of longwords to work on, should be a parameter
	static unsigned char *chan_addr;		//input-buffer			
	static unsigned int loop, i;			//control
	static unsigned char byte_data; 		//byte to work on
	static unsigned char temp_byte;	
	static int temp_int;		
	static unsigned char correct[4];		//channeldependend correctionvalues	
	static unsigned char *DataArray2;
	static unsigned int zero2;
		
	DataArray2 = DataArray1;		
	zero2 = zero << 1;
	
	chan_addr = ((unsigned char*)(0x00917440)); //channel_address = readout_sigbuf, READADC_ALL2 filled this buffer	
	if (highspeed == 1)	//timebase < 7
/*	//Guido: testing:
	{
		for (loop = 0; loop < 4096; loop++)
		{
			byte_data = *(chan_addr);
			byte_data = ~byte_data;
			*(DataArray2) = byte_data;;	
			*(DataArray2 + 1) = byte_data;;	
			//byte_data = *(chan_addr + 2);
			//byte_data = ~byte_data;					
			*(DataArray2 + 2) = byte_data;;	
			*(DataArray2 + 3) = byte_data;;		
			DataArray2 += 4;
			chan_addr += 4;
		}	
	}
*/
	{
		// this was done bei PREPARE_READADC (now obsolete): load the channel's correctionvalues
		for (i = 0; i < 4; i++) correct[i] = ADC_Offset[(which - 1)][i];

		for (loop = 0; loop < lw_count; loop++)		
		{	
			byte_data = *(chan_addr);	//load first byte
			byte_data = ~byte_data;		//invert it bitwise			
			if (byte_data > correct[0]) byte_data -= correct[0];	//offsetadjustment (stefan put it here)
			else byte_data = 0;
			if (inverse == 1)
			{			
				temp_int = zero2 - byte_data;
				if (temp_int < 0) temp_int = 0;		//limit to byte
				else if (temp_int > 255) temp_int = 255;	
				byte_data = temp_int;				
			}	
			if (averageval != 0) //then start averaging				
			{
				temp_byte = *(DataArray2);		//load old value as byte
				byte_data = (unsigned char)(((unsigned short)byte_data + (unsigned short)temp_byte) >> 1);
			}
			*(DataArray2) = byte_data;	//store result	
			
			byte_data = *(chan_addr);	//load second byte
			byte_data = ~byte_data;		//invert it bitwise			
			if (byte_data > correct[1]) byte_data -= correct[1];	//offsetadjustment (stefan put it here)
			else byte_data = 0;
			if (inverse == 1)
			{			
				temp_int = zero2 - byte_data;
				if (temp_int < 0) temp_int = 0;		//limit to byte
				else if (temp_int > 255) temp_int = 255;	
				byte_data = temp_int;				
			}	
			if (averageval != 0) //then start averaging				
			{
				temp_byte = *(DataArray2 + 1);		//load old value as byte
				byte_data = (unsigned char)(((unsigned short)byte_data + (unsigned short)temp_byte) >> 1);
			}
			*(DataArray2 + 1) = byte_data;	//store result	
			
			byte_data = *(chan_addr);	//load third byte
			byte_data = ~byte_data;		//invert it bitwise			
			if (byte_data > correct[2]) byte_data -= correct[2];	//offsetadjustment (stefan put it here)
			else byte_data = 0;
			if (inverse == 1)
			{			
				temp_int = zero2 - byte_data;
				if (temp_int < 0) temp_int = 0;		//limit to byte
				else if (temp_int > 255) temp_int = 255;	
				byte_data = temp_int;				
			}	
			if (averageval != 0) //then start averaging				
			{
				temp_byte = *(DataArray2 + 2);		//load old value as byte
				byte_data = (unsigned char)(((unsigned short)byte_data + (unsigned short)temp_byte) >> 1);
			}
			*(DataArray2 + 2) = byte_data;	//store result	
			
			byte_data = *(chan_addr);	//load last byte
			byte_data = ~byte_data;		//invert it bitwise			
			if (byte_data > correct[3]) byte_data -= correct[3];	//offsetadjustment (stefan put it here)
			else byte_data = 0;
			if (inverse == 1)
			{			
				temp_int = zero2 - byte_data;
				if (temp_int < 0) temp_int = 0;		//limit to byte
				else if (temp_int > 255) temp_int = 255;	
				byte_data = temp_int;				
			}	
			if (averageval != 0) //then start averaging				
			{
				temp_byte = *(DataArray2 + 3);		//load old value as byte
				byte_data = (unsigned char)(((unsigned short)byte_data + (unsigned short)temp_byte) >> 1);
			}
			*(DataArray2 + 3) = byte_data;	//store result	
			DataArray2 += 4;
			chan_addr += 4;
		}	
	}	
	else	//timebase > 6: only use ADC0
	{
		for (loop = 0; loop < lw_count; loop++)		
		{	
			byte_data = *(chan_addr);	//load one byte
			byte_data = ~byte_data;		//invert it bitwise	
			// nothing to correct as only one ADC is used		
			//if (byte_data > correct[0]) byte_data -= correct[0];	//offsetadjustment (stefan put it here)
			//else byte_data = 0;
			if (inverse == 1)
			{			
				temp_int = zero2 - byte_data;
				if (temp_int < 0) temp_int = 0;		//limit to byte
				else if (temp_int > 255) temp_int = 255;	
				byte_data = temp_int;				
			}	
			if (averageval != 0) //then start averaging				
			{
				temp_byte = *(DataArray2);		//load old value as byte
				byte_data = (unsigned char)(((unsigned short)byte_data + (unsigned short)temp_byte) >> 1);
			}
			*(DataArray2) = byte_data;	//store result	
			DataArray2 += 1;
			chan_addr += 4;		
		}
	}

}


//#####################################################################################################################################################

void Hardware::DoEnableADCInterrupt(void)							// Enable ADC service routine
{
	acq_ready->np_pioedgecapture = 0x00; 							// clear existing IRQ conditions
	acq_ready->np_piodirection = 0;								// set bit to input
	acq_ready->np_piointerruptmask = 0x01;							// enable interrupt

	nr_installuserisr(na_data_acq_interrupt_irq,ISR_ADC_INT,(int)acq_ready);		// Install ISR for ADC
#ifdef _Debug_IRQ_
	if (Debug_Mode) printf("\nADC interrupt enabled.\n"); 							// print on console
#endif
}
//#####################################################################################################################################################

void Hardware::DoDisableADCInterrupt(void)							// Disable ADC service routine
{
	
	nr_installuserisr(na_data_acq_interrupt_irq,0,0); 				// Install empty routine for adc irq
	acq_ready->np_piointerruptmask = 0x00;							// disable all IRQs
	
#ifdef _Debug_IRQ_
	if (Debug_Mode) printf("\nADC interrupt disabled.\n"); 							// print on console
#endif	
}
//#####################################################################################################################################################

void Hardware::ISR_ADC_INT(int context)						// ADC interrupt subroutine
{
	long buffer;
	int ix2;
	
	//BF del tc_test_var2++;
	
	adc_started = false;
	
	acq_ready->np_pioedgecapture = 0;
	
	ADC_Data_Available = 1;
	//printf("ADC ready - data available\n");

}
//#####################################################################################################################################################

int Hardware::Read_IRQ(void)
{
    return acq_ready->np_piodata;
}
//#####################################################################################################################################################
void Hardware::Handle_ADC(void)						// ADC handler
{
	
	//out_test->np_piodata = 0x01;	// Testbit+++++++++++++++++++++++
	volatile long buffer_addr = 0;	
	volatile long buffer_peak = 0;	
	volatile long buffer_written = 0;	
	volatile long buffer_adradd = 0;

	int channel_trig = 0;

	// BF if test signals are generated, don't handle ADC
	//if(test_signal)  return;

//printf("\nentering ADC-handler \n");	
	
	//BF add  don't handle ADC if user interface must be handled
	if (UI_request)	return;
	//if (UI_request){ printf("\nUI-request occured\n");	return;	}


	//if no new data is available return	
	if (ADC_Data_Available == 0) return;
	//if (ADC_Data_Available == 0){ printf("\nno new ADC-data available\n"); return; }

	//reset availability flag	
	ADC_Data_Available = 0;

//printf("\r\nnew ADC-data available\r\n");	

	//if (Signal_Loaded) return;	//BF -> not used

//printf("\nreading signal...\n");	

/* BF del should be handled in ISR	
	//BF added for new start/stop logic
	Stop_Record();
*/

	signal_zoomed1 = false;
	signal_zoomed2 = false;
	signal_zoomed3 = false;
	signal_zoomed4 = false;
	
	data_adr->np_piodata = 0x01;

	if ((Selected_Trigger_Source == 3) || (Selected_Trigger_Source == 4))	
	{
		buffer_addr = READADC(3);
		buffer_peak = READADC(3);
	}
	else
	{
		buffer_addr = READADC(1);
		buffer_peak = READADC(1);
	}
	
	AutoFreeRun = false;
	
#ifdef _Debug_	
if ((Debug_Mode) && (ADC_Debug_Mode)) printf("Peak %x \n", buffer_peak);
#endif

	if ((buffer_addr & 0x00001000) == 0x00001000)
	{
		if ((buffer_addr & 0x00000FFF) == 0x00000000)
		{
			// buffer_written = (buffer_addr & 0x00000FFF) + ((pre_reg - 8) >> 1);
			if (Selected_Timebase < 9) buffer_written = (buffer_addr & 0x00000FFF) + ((pre_reg - 8) >> 1);
			else buffer_written = (buffer_addr & 0x00000FFF) + ((pre_reg - 8));
		}
		else
		{
			//buffer_written = pre_reg >> 1;
			if (Selected_Timebase < 9) buffer_written = pre_reg >> 1;
			else buffer_written = pre_reg;
		}
	
		AutoFreeRun = true;
		
		//printf("Auto Free Run   RA : %4x  RW : %4x\n", buffer_addr, buffer_written);
	}
	else if (Selected_Timebase < 7) buffer_written = ((buffer_addr & 0x0FFF) - (pre_reg >> 1)) & 0x00000FFF;
	else buffer_written = ((buffer_addr & 0x0FFF) - pre_reg) & 0x00000FFF;
			
   	channel_trig = (buffer_addr & 0xC000) >> 14;

#ifdef _Debug_   	
if (Debug_Mode) printf("ChannelTrig %d\n", channel_trig);
#endif   	

#ifdef _Debug_
if ((Debug_Mode) && (ADC_Debug_Mode)) printf("RTA : %x  WTA : %x PreReg %x\n", buffer_addr, buffer_written, pre_reg);
#endif




	if (USTB_Mode == USTB_OFF)	//don't trigger if ultra slow tb mode is active
	{
		if (NumberOfChannels < 4)
		{				
			if ((triggering != 0) || (Selected_Trigger_Source == 5))
			{
				WRITEADC(1, buffer_written);
				WRITEADC(2, buffer_written);
#ifdef _Debug_
if ((Debug_Mode) && (ADC_Debug_Mode)) printf("Wr Tr ADR %x \n", buffer_written);
#endif			
			} 
			else
			{
				WRITEADC(1, ram_adress_reg + buffer_adradd);
				WRITEADC(2, ram_adress_reg + buffer_adradd);
		//   printf("Write FreeRun Address 0x00 \n");
			}
		}
		else
		{				
			if ((triggering != 0) || (Selected_Trigger_Source == 5))
			{		
				WRITEADC(1, buffer_written);
				WRITEADC(2, buffer_written);
				WRITEADC(3, buffer_written);
				WRITEADC(4, buffer_written);
#ifdef _Debug_
if ((Debug_Mode) && (ADC_Debug_Mode)) printf("Wr Tr ADR %x \n", buffer_written);
#endif			
			}
			else
			{
				WRITEADC(1, ram_adress_reg + buffer_adradd);
				WRITEADC(2, ram_adress_reg + buffer_adradd);
				WRITEADC(3, ram_adress_reg + buffer_adradd);
				WRITEADC(4, ram_adress_reg + buffer_adradd);
			//	printf("Write FreeRun Address 0x00 \n");
			}
		}
	
	}	


	data_adr->np_piodata = 0x00;
	
	// generate test signals
	if(test_signal)
	{ Display::TestSignalGenerate(); }
	else
	{
		if (Channel_1_Active == 1)
		{ ReadOut_Signal(1, buffer_addr & 0x3FFF); }
		
		if (Channel_2_Active == 1)
		{ ReadOut_Signal(2, buffer_addr & 0x3FFF); }	
		
		if (NumberOfChannels > 2)
		{	
			if (Channel_3_Active == 1)
			{ ReadOut_Signal(3, buffer_addr & 0x3FFF); }
		
			if (Channel_4_Active == 1)
			{ ReadOut_Signal(4, buffer_addr & 0x3FFF); }
		}	
	}

	//----------------------------------------------------------------------------------
	//				Trigger Offset
	//----------------------------------------------------------------------------------
	if (USTB_Mode == USTB_OFF)	//don't trigger if ultra slow tb mode is active
	{
		//BF del if ((Selected_Timebase < 7) && ((Selected_Trigger_Source > 0) && (Selected_Trigger_Source < 5)) && (AutoFreeRun == false))
		//BF -> hint from Stefan to delete the TB 7 statement!!
		if (triggering != 0)
		{
			if (((Selected_Trigger_Source > 0) && (Selected_Trigger_Source < 5)) && (AutoFreeRun == false))
			{
//BF test
				//BF del Trigger_Offset_Calc = 50 - ((Trig_Pos_Mem + 50) - FindTrigger(Selected_Trigger_Source, MenuStatus[MENU_TRIGGEREDGE][0] - 2, Trig_Pos_Mem + 50));

				//BF -> this is only to make the triggered signal less "nervous" and more stable, but it works also with
				//	a constant value of 80 for Trigger_Offset_Calc
				Trigger_Offset_Calc = FindTrigger(Selected_Trigger_Source, MenuStatus[MENU_TRIGGEREDGE][0] - 2, Trig_Pos_Mem + 50) - Trig_Pos_Mem;
				//Trigger_Offset_Calc = 80;
//BF test
			}
			else
			{ Trigger_Offset_Calc = -15; }
		}
		else
		{ Trigger_Offset_Calc = 0; }
		
		//printf("TOC %d\r\n", Trigger_Offset_Calc);
	}


	


        //-----------------------------------------------------------------------
	//		handle single mode
	//-----------------------------------------------------------------------
	if (SingleMode == 1)
	{
	  	Single_Restart = 0;

		// Run/Stop LED red
		LED_ON[12] = 0;
		LED_ON[13] = 1;			
		
		// Single Mode LED green
		LED_ON[14] = 0;
		LED_ON[15] = 0;				
		Send_LED();		
	}

	
//    if ((QM_Enabled) && (QM_Type[0] > 0)) Display::CALCQMDATA();	
	

//#ifdef _Debug_	
//	if ((ADC_Debug_Mode) && (Debug_Mode)) printf("ADC IRQ handled %d\n", triggering);
//#endif

	//----------------------------------------------------
	//BF FFT mode
	//----------------------------------------------------
	if (FFT_Mode != FFT_OFF)	
	{ FFT_NewData = 1; }


	//----------------------------------------------------
	//BF new USTB mode
	//----------------------------------------------------
	if (USTB_Mode == USTB_OFF)	//ultra slow tb mode off
	{
		//BF add new start/stop logic
		if ((!SingleMode) && (Continius) && (!OneShotRestart))
		{ Start_Record(); } 
	}
	else if	((USTB_Mode != USTB_OFF) && Continius)//ultra slow tb mode on
	{
		USTB_NewData = 1;	//New data for roll/shift mode available

		//BF timer is running in continious mode without start/stop now
		//Start_Timer2();		//start new timer sequenz
		
		//BF test
		//Start_Record();
	}

 
}
//#####################################################################################################################################################
// BF deleted unused parameter -> found by Stefan
void Hardware::ReadOut_Signal(char channel, unsigned long adr_read)
{
	int ix, ix2, ix3, enddata;
	int chk_calc     = 0;
	long buffer_long = 0;
	unsigned int read_out_count = 4096;
	int Virtual_Zero;	//BF new

	//if (MenuStatus[MENU_TIMEBASE][2] == 1) read_out_count = 0x100;

	if (USTB_Mode != USTB_OFF)	//ultra slow tb mode off
	read_out_count = 128;
	else
	read_out_count = 4096;

	switch(channel)
	{	
		case 1 :	//Channel 1
		{
			Virtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH1 / scale_factor[Selected_Voltage_CH1]);
			//BF test Virtual_Zero = ADC_ZERO + int( (float)Virtual_ZeroLevelCH1 / (ZeroScaleFactor[0][Selected_Voltage_CH1] * 2));
			if (Virtual_Zero > 255) Virtual_Zero = 255;	//Limiter
			if (Virtual_Zero < 0) Virtual_Zero = 0;
			
			//channel coupling = ground -> set all values to zero (ADC_ZERO = 127) 		BF -> new ground function 
			if (MenuStatus[MENU_CHANNEL1][0] == 6) //GND-coupling
			{ for(int i=0;i<0x4000;i++) SIGNAL1[i] = Virtual_Zero; }
			else
			{
				buffer_long = READADC(1);    // Read correction
				buffer_long = READADC(1);

//BF test coding 		
				if(test_sw1)	//BF -> new C-routines for testing
				{
					ADC_ReadData(1, &readout_sigbuf[0], read_out_count);
					 					
					if (Selected_Timebase < 7 || USTB_Mode != USTB_OFF) //Highspeed
					{
						if (MenuStatus[MENU_ACQUIRE][1] == 1)
						{ ADC_ProcessData(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 1, 1); }	
						else
						{ ADC_ProcessData(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 0, 1); }	
				
					}
					else	//Lowspeed
					{
						if (MenuStatus[MENU_ACQUIRE][1] == 1)
						{ ADC_ProcessData(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 1, 0); }	
						else
						{ ADC_ProcessData(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 0, 0); }	
					}
				}
//BF test end	
				else	//BF -> Assembler routines as standard
				{
					READADC_ALL2(1, &readout_sigbuf[0], read_out_count);
					PREPARE_READADC(ADC_Offset[0][0],ADC_Offset[0][1],ADC_Offset[0][2],ADC_Offset[0][3], read_out_count);	
					
					if (Selected_Timebase < 7 || USTB_Mode != USTB_OFF) //Highspeed
					{
						if (MenuStatus[MENU_ACQUIRE][1] == 1)
						{ READADC_ALL(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 1, 1); }	
						else
						{ READADC_ALL(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 0, 1); }	
				
					}
					else	//Lowspeed
					{
						if (MenuStatus[MENU_ACQUIRE][1] == 1)
						{ READADC_ALL(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 1, 0); }	
						else
						{ READADC_ALL(1, &SIGNAL1[0], MenuStatus[MENU_CHANNEL1][2] - 240, Virtual_Zero, 0, 0); }	
					}
				}
			}
	
			//USB transfer
			if (((USB_Data_Requested) || (USB_Data_Trans)) && (Transfer_man_data == false))
			{
				// Submit Data to USB Client
				if (USB_Data_Requested) enddata = 511;
				else enddata = 75;
		
				if (USB_Data_Trans)
				{
					if (USB_SendAllData) enddata = 511;
					else enddata = 75;
				
					USB_Data_Requested = true;
				}
		
				if (USB_OnlyTrigger == false)
				{
		
					send_buffer[0] = 100 + channel;								// Kennung Data	
						
					for (ix2 = 0; ix2 <= enddata; ix2++)
					{
						ix3 = ix2 * 32;
			
						send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
						send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
						
						chk_calc = 0;	
						for (ix = 0; ix < 32; ix++)
						{	
							chk_calc += readout_sigbuf_char[(ix2 * 32) + ix];
							send_buffer[3 + ix] = readout_sigbuf_char[(ix2 * 32) + ix];
						}	
							
						send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
						send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
												
						SendData(send_buffer);
							
						//printf("DS %3d %3d %3d\n", send_buffer[2], send_buffer[3], send_buffer[4]);
						nr_delay(10);
					}
				}	
			}    
	
			break;
		}

		case 2 :	//Channel 2
		{
			Virtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH2 / scale_factor[Selected_Voltage_CH2]);
			if (Virtual_Zero > 255) Virtual_Zero = 255;	//Limiter
			if (Virtual_Zero < 0) Virtual_Zero = 0;

			//channel coupling = ground -> set all values to zero (ADC_ZERO = 127) 		BF -> new ground function 
			if (MenuStatus[MENU_CHANNEL2][0] == 6) 
			{ for(int i=0;i<0x4000;i++) SIGNAL2[i] = Virtual_Zero; }
			else
			{
				buffer_long = READADC(2);    // Read correction
				buffer_long = READADC(2);
					
				READADC_ALL2(2, &readout_sigbuf[0], read_out_count);
				PREPARE_READADC(ADC_Offset[1][0],ADC_Offset[1][1],ADC_Offset[1][2],ADC_Offset[1][3], read_out_count);
		
				if (Selected_Timebase < 7 || USTB_Mode != USTB_OFF) //Highspeed
				{
					if (MenuStatus[MENU_ACQUIRE][1] == 1)
					{ READADC_ALL(2, &SIGNAL2[0], MenuStatus[MENU_CHANNEL2][2] - 240, Virtual_Zero, 1, 1); }
					else
					{ READADC_ALL(2, &SIGNAL2[0], MenuStatus[MENU_CHANNEL2][2] - 240, Virtual_Zero, 0, 1); }
			
				}
				else	//Lowspeed
				{
					if (MenuStatus[MENU_ACQUIRE][1] == 1)
					{ READADC_ALL(2, &SIGNAL2[0], MenuStatus[MENU_CHANNEL2][2] - 240, Virtual_Zero, 1, 0); }
					else
					{ READADC_ALL(2, &SIGNAL2[0], MenuStatus[MENU_CHANNEL2][2] - 240, Virtual_Zero, 0, 0); }
				}
			}

			if (((USB_Data_Requested) || (USB_Data_Trans)) && (Transfer_man_data == false))
			{
				// Submit Data to USB Client
				if (USB_Data_Requested) enddata = 511;
				else enddata = 75;
		
				if (USB_Data_Trans)
				{
					if (USB_SendAllData) enddata = 511;
					else enddata = 75;
				
					USB_Data_Requested = true;
				}
		
				if (USB_OnlyTrigger == false)
				{
		
					send_buffer[0] = 100 + channel;								// Kennung Data	
						
					for (ix2 = 0; ix2 <= enddata; ix2++)
					{
						ix3 = ix2 * 32;
			
						send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
						send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
						
						chk_calc = 0;	
						for (ix = 0; ix < 32; ix++)
						{	
						chk_calc += readout_sigbuf_char[(ix2 * 32) + ix];
						send_buffer[3 + ix] = readout_sigbuf_char[(ix2 * 32) + ix];
						}	
							
						send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
						send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
												
						SendData(send_buffer);
							
						//printf("DS %3d %3d %3d\n", send_buffer[2], send_buffer[3], send_buffer[4]);
						nr_delay(10);
					}
				}	
			}

            		break;
        	}

		case 3 :	//Channel 3
		{
			Virtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH3 / scale_factor[Selected_Voltage_CH3]);
			if (Virtual_Zero > 255) Virtual_Zero = 255;	//Limiter
			if (Virtual_Zero < 0) Virtual_Zero = 0;

			//channel coupling = ground -> set all values to zero (ADC_ZERO = 127) 		BF -> new ground function 
			if (MenuStatus[MENU_CHANNEL3][0] == 6) 
			{ for(int i=0;i<0x4000;i++) SIGNAL3[i] = Virtual_Zero; }
			else
			{
				buffer_long = READADC(3);    // Read correction
				buffer_long = READADC(3);
				buffer_long = READADC(3);    // Read correction
				
				// Get new Signal Data
				READADC_ALL2(3, &readout_sigbuf[0], read_out_count);
				PREPARE_READADC(ADC_Offset[2][0],ADC_Offset[2][1],ADC_Offset[2][2],ADC_Offset[2][3], read_out_count);
			
				if (Selected_Timebase < 7 || USTB_Mode != USTB_OFF)
				{
					if (MenuStatus[MENU_ACQUIRE][1] == 1)
					{ READADC_ALL(3, &SIGNAL3[0], MenuStatus[MENU_CHANNEL3][2] - 240, Virtual_Zero, 1, 1); }
					else
					{ READADC_ALL(3, &SIGNAL3[0], MenuStatus[MENU_CHANNEL3][2] - 240, Virtual_Zero, 0, 1); }
			
				}
				else
				{
					if (MenuStatus[MENU_ACQUIRE][1] == 1)
					{ READADC_ALL(3, &SIGNAL3[0], MenuStatus[MENU_CHANNEL3][2] - 240, Virtual_Zero, 1, 0); }
					else
					{ READADC_ALL(3, &SIGNAL3[0], MenuStatus[MENU_CHANNEL3][2] - 240, Virtual_Zero, 0, 0); }
			
				}
			}
					
			if (((USB_Data_Requested) || (USB_Data_Trans)) && (Transfer_man_data == false))
			{
				// Submit Data to USB Client
				if (USB_Data_Requested) enddata = 511;
				else enddata = 75;
		
				if (USB_Data_Trans)
				{
					if (USB_SendAllData) enddata = 511;
					else enddata = 75;
				
					USB_Data_Requested = true;
				}
		
				if (USB_OnlyTrigger == false)
				{
		
					send_buffer[0] = 100 + channel;								// Kennung Data	
						
					for (ix2 = 0; ix2 <= enddata; ix2++)
					{
						ix3 = ix2 * 32;
			
						send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
						send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
						
						chk_calc = 0;	
						for (ix = 0; ix < 32; ix++)
						{	
							chk_calc += readout_sigbuf_char[(ix2 * 32) + ix];
							send_buffer[3 + ix] = readout_sigbuf_char[(ix2 * 32) + ix];
						}	
							
						send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
						send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
												
						SendData(send_buffer);
							
						//printf("DS %3d %3d %3d\n", send_buffer[2], send_buffer[3], send_buffer[4]);
						nr_delay(10);
					}
				}	
			}
		
			break;
		}
		
		case 4 :	//Channel 4
		{
			Virtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH4 / scale_factor[Selected_Voltage_CH4]);
			if (Virtual_Zero > 255) Virtual_Zero = 255;	//Limiter
			if (Virtual_Zero < 0) Virtual_Zero = 0;

			//channel coupling = ground -> set all values to zero (ADC_ZERO = 127) 		BF -> new ground function 
			if (MenuStatus[MENU_CHANNEL4][0] == 6) 
			{ for(int i=0;i<0x4000;i++) SIGNAL4[i] = Virtual_Zero; }
			else
			{
				buffer_long = READADC(4);    // Read correction
				buffer_long = READADC(4);
				buffer_long = READADC(4);
				
				// Get new Signal Data
				READADC_ALL2(4, &readout_sigbuf[0], read_out_count);
				PREPARE_READADC(ADC_Offset[3][0],ADC_Offset[3][1],ADC_Offset[3][2],ADC_Offset[3][3], read_out_count);
	
				if (Selected_Timebase < 7 || USTB_Mode != USTB_OFF)
				{
					if (MenuStatus[MENU_ACQUIRE][1] == 1)
					{ READADC_ALL(4, &SIGNAL4[0], MenuStatus[MENU_CHANNEL4][2] - 240, Virtual_Zero, 1, 1); }
					else
					{ READADC_ALL(4, &SIGNAL4[0], MenuStatus[MENU_CHANNEL4][2] - 240, Virtual_Zero, 0, 1); }
				}
				else
				{
					if (MenuStatus[MENU_ACQUIRE][1] == 1)
					{ READADC_ALL(4, &SIGNAL4[0], MenuStatus[MENU_CHANNEL4][2] - 240, Virtual_Zero, 1, 0); }
					else
					{ READADC_ALL(4, &SIGNAL4[0], MenuStatus[MENU_CHANNEL4][2] - 240, Virtual_Zero, 0, 0); }
				}
			}

				
			if (((USB_Data_Requested) || (USB_Data_Trans)) && (Transfer_man_data == false))
			{
				// Submit Data to USB Client
				if (USB_Data_Requested) enddata = 511;
				else enddata = 75;
		
				if (USB_Data_Trans)
				{
					if (USB_SendAllData) enddata = 511;
					else enddata = 75;
				
					USB_Data_Requested = true;
				}
		
				if (USB_OnlyTrigger == false)
				{
		
					send_buffer[0] = 100 + channel;								// Kennung Data	
						
					for (ix2 = 0; ix2 <= enddata; ix2++)
					{
						ix3 = ix2 * 32;
			
						send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
						send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
						
						chk_calc = 0;	
						for (ix = 0; ix < 32; ix++)
						{	
						chk_calc += readout_sigbuf_char[(ix2 * 32) + ix];
						send_buffer[3 + ix] = readout_sigbuf_char[(ix2 * 32) + ix];
						}	
							
						send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
						send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
												
						SendData(send_buffer);
							
						//printf("DS %3d %3d %3d\n", send_buffer[2], send_buffer[3], send_buffer[4]);
						nr_delay(10);
					}
				}	
			}
			break;

		}

	}//Ende switch channel
}

/* BF not used
void Hardware::Do_Gen_Signal(void)	
{
    float wert;
    float grad;
    int icnt;

#ifdef _Debug_FFT_
    printf("starting generate signal\n");
#endif
    for(icnt = 0; icnt <= FFT_LENGTH; icnt++)
    {
        grad = (float) (icnt);
        
        if (((int)(grad * 0.015625) %2) == 0) wert = -1.0; // 0.03125
        else wert = 1.0;
               
	//BF change ->reactivated
        //fft_values[icnt] = wert;
        //BF change end
        //SIGNAL1[icnt] = ((unsigned char) ((wert * 30) + 128));
       // printf( "%d\n", (int) wert );
    }
#ifdef _Debug_FFT_
    printf("generate signal ready\n");
#endif
}
*/

//##############################################################################################################################################
//BF new fix for trigger calculating by Stefan
int Hardware::FindTrigger(unsigned char channel, unsigned char negativ, int TriggerPos)
{
	int ix, foundat = 0, range = 50;
	int tl_buf = 0;
	
	unsigned char neg_buf = negativ;
	
	// if channel inverted
	if (MenuStatus[channel][2] == 241)
	{
		if (negativ) negativ = 0;
		else negativ = 1;
	}
	
	switch(channel)
	{
		case 1 : tl_buf = (int)((float)(Trigger_Pos_CH1-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH1])+ADC_ZERO; break;//Stefan
		case 2 : tl_buf = (int)((float)(Trigger_Pos_CH2-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH2])+ADC_ZERO; break;
		case 3 : tl_buf = (int)((float)(Trigger_Pos_CH3-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH3])+ADC_ZERO; break;
		case 4 : tl_buf = (int)((float)(Trigger_Pos_CH4-GRID_HEIGHT/2)/scale_factor[Selected_Voltage_CH4])+ADC_ZERO; break;
	}
	
	if (negativ)
	{
		switch(channel)
		{
			case 1 :
			{
				foundat = TriggerPos;
				for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
				{
					if (SIGNAL1[ix] > tl_buf)
					{
						foundat = ix;
						break;
					}
				}
				break;
			}
			case 2 :
			{
				foundat = TriggerPos;
				for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
				{
					if (SIGNAL2[ix] > tl_buf)
					{
						foundat = ix;
						break;
					}
				}
				break;
			}
			case 3 :
			{
				foundat = TriggerPos;
				for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
				{
					if (SIGNAL3[ix] > tl_buf)
					{
						foundat = ix;
						break;
					}
				}
				break;
			}
			case 4 :
			{
				foundat = TriggerPos;
				for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
				{
					if (SIGNAL4[ix] > tl_buf)
					{
						foundat = ix;
						break;
					}
				}
				break;
			}
		}
	}
	else
	{
		switch(channel)
		{
		case 1 :
		{
			foundat = TriggerPos;
			for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
			{
				if (SIGNAL1[ix] < tl_buf)
				{
					foundat = ix;
					break;
				}
			}
			break;
		}
		case 2 :
		{
			foundat = TriggerPos;
			for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
			{
				if (SIGNAL2[ix] < tl_buf)
				{
					foundat = ix;
					break;
				}
			}
			break;
		}
		case 3 :
		{
			foundat = TriggerPos;
			for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
			{
				if (SIGNAL3[ix] < tl_buf)
				{
					foundat = ix;
					break;
				}
			}
			break;
		}
		case 4 :
		{
			foundat = TriggerPos;
			for (ix = TriggerPos - range; ix < TriggerPos + range; ix++)
			{
				if (SIGNAL4[ix] < tl_buf)
				{
					foundat = ix;
					break;
				}
			}
			break;
		}
		}
	}
	
	return foundat;
}

//Auto scale
int Hardware::AutoScale(void)
{
	int result = 0;
	
	triggering_bak   = triggering;
	ctrl_reg_bak     = ctrl_reg;
	adc_ctrl_reg_bak = adc_ctrl_reg;
	
	Channel_1_Active_bak = Channel_1_Active;
	Channel_2_Active_bak = Channel_2_Active;
	Channel_3_Active_bak = Channel_3_Active;
	Channel_4_Active_bak = Channel_4_Active;
	
	Selected_Timebase_bak  = Selected_Timebase;
	SIGNALFaktor_idx_bak   = SIGNALFaktor_idx;
	SIGNAL_StartFr_idx_bak = SIGNAL_StartFr_idx;
	timebase_reg_bak       = timebase_reg;
	Display_Timebase_bak   = Display_Timebase;
	Continius_bak          = Continius;
	SingleMode_bak         = SingleMode;
	
	Selected_Voltage_CH1_bak = Selected_Voltage_CH1;
	Selected_Voltage_CH2_bak = Selected_Voltage_CH2;
	Selected_Voltage_CH3_bak = Selected_Voltage_CH3;
	Selected_Voltage_CH4_bak = Selected_Voltage_CH4;   	
	
	ZeroLevelCH1_bak = ZeroLevelCH1;
	ZeroLevelCH2_bak = ZeroLevelCH2;
	ZeroLevelCH3_bak = ZeroLevelCH3;
	ZeroLevelCH4_bak = ZeroLevelCH4;
	
	Virtual_ZeroLevelCH1_bak = Virtual_ZeroLevelCH1;
	Virtual_ZeroLevelCH2_bak = Virtual_ZeroLevelCH2;
	Virtual_ZeroLevelCH3_bak = Virtual_ZeroLevelCH3;
	Virtual_ZeroLevelCH4_bak = Virtual_ZeroLevelCH4;
	
	Trigger_Pos_CH1_bak = Trigger_Pos_CH1;	
	Trigger_Pos_CH2_bak = Trigger_Pos_CH2;
	Trigger_Pos_CH3_bak = Trigger_Pos_CH3;
	Trigger_Pos_CH4_bak = Trigger_Pos_CH4;
	
	Timebase_Offset_Pos_bak = Timebase_Offset_Pos;
	//Trigger_Offset_Pos_bak  = Trigger_Offset_Pos;	//BF del not used
	
	AC_CH1_bak = MenuStatus[MENU_CHANNEL1][0];
	AC_CH2_bak = MenuStatus[MENU_CHANNEL2][0];
	AC_CH3_bak = MenuStatus[MENU_CHANNEL3][0];
	AC_CH4_bak = MenuStatus[MENU_CHANNEL4][0];
	
	Invert_CH1_bak = MenuStatus[MENU_CHANNEL1][2];
	Invert_CH2_bak = MenuStatus[MENU_CHANNEL2][2];
	Invert_CH3_bak = MenuStatus[MENU_CHANNEL3][2];
	Invert_CH4_bak = MenuStatus[MENU_CHANNEL4][2];
	
	MAINMODE_bak = MenuStatus[MENU_TIMEBASE][0];
	//ROLLMODE_bak = MenuStatus[MENU_TIMEBASE][2];
	//BF del ROLLMODESTARTED_bak = ROLLMODE_STARTED;
	
	Acquire_bak_0 = MenuStatus[MENU_ACQUIRE][0];
	Acquire_bak_1 = MenuStatus[MENU_ACQUIRE][1];
	
	AUTOMODE_bak = MenuStatus[MENU_TRIGGERMODE][0];
				
	Stop_Record();			
	AutoTimerOff = true;
	Search_Mode  = true;
	
	DoDisableUARTInterrupt();
	DoDisableADCInterrupt();
	DoDisableKeyInterrupt();
	DoDisableRotInterrupt();
	
	ADC_Data_Available = 0;
	acq_ready->np_pioedgecapture = 0;
		
	MenuStatus[MENU_TRIGGERMODE][0] = 93;
	MenuPopupStatus[9][0] = 3;
	MenuPopupStatus[9][1] = 2;
	
	// Averaging off			
	MenuStatus[MENU_ACQUIRE][1] = 0;
	MenuStatus[MENU_ACQUIRE][0] = 1;
				
	
	// All AC
	MenuStatus[MENU_CHANNEL1][0] = 7;
	MenuStatus[MENU_CHANNEL2][0] = 7;
	MenuStatus[MENU_CHANNEL3][0] = 7;
	MenuStatus[MENU_CHANNEL4][0] = 7;
	
	// All invert off
	MenuStatus[MENU_CHANNEL1][2] = 240;
	MenuStatus[MENU_CHANNEL2][2] = 240;
	MenuStatus[MENU_CHANNEL3][2] = 240;
	MenuStatus[MENU_CHANNEL4][2] = 240;
	
	
	
	Selected_Timebase  = 4;                                         //  50 nS
	SIGNALFaktor_idx   = 0;                                         // zoom factor 1 = 50 nS
	SIGNAL_StartFr_idx = 0;                                         // running. so 0
	
	timebase_reg = tb_value[Selected_Timebase];
	Display_Timebase = 4;                                          // Displayed timebase is 50 ns
	
	triggering    = 0;								
	ctrl_reg      = 0x0087;							            // Trigger_Master / Trigger_INT / Free Run
	adc_ctrl_reg &= 0xFFF0;						                    // Disable Trigger sources
	
	pre_reg = 0x006C;
	//Trigger_Offset_Pos  = 353;	//BF not used
	Timebase_Offset_Pos = -300;
	
	// TMW complete changed (2-Channel Version)
	
	Virtual_ZeroLevelCH1 = 0;
	//BF del    CH1_Zero_Offset      = 0;
	
	Virtual_ZeroLevelCH2 = 0;
	//BF del    CH2_Zero_Offset      = 0;
	
	Rotary_Steps = 0;
	ON_Zero_Channel_1();
	Rotary_Steps = 0;
	ON_Zero_Channel_2();
	
  	if ( NumberOfChannels == 4) // TMW complete changed (4-Channel Version)
 	{
		Virtual_ZeroLevelCH3 = 0;
//BF del    		CH3_Zero_Offset      = 0;
    		Virtual_ZeroLevelCH4 = 0;
//BF del    		CH4_Zero_Offset      = 0;

    		Rotary_Steps = 0;
    		ON_Zero_Channel_3();
    		Rotary_Steps = 0;
    		ON_Zero_Channel_4();
	}
 
	Trigger_Pos_CH1 = ZeroLevelCH1;
	Trigger_Pos_CH2 = ZeroLevelCH2;
	Trigger_Pos_CH3 = ZeroLevelCH3;
	Trigger_Pos_CH4 = ZeroLevelCH4;
	
	if (Channel_1_Active) result = FindTimebase(1);
	else if (Channel_2_Active) result = FindTimebase(2);
	else if (Channel_3_Active) result = FindTimebase(3);
	else if (Channel_4_Active) result = FindTimebase(4);

  // TMW complete changed (2-Channel Version)

   	 Virtual_ZeroLevelCH1 = 0;
//BF del    CH1_Zero_Offset      = 0;

  	  Virtual_ZeroLevelCH2 = 0;
//BF del    CH2_Zero_Offset      = 0;

	Rotary_Steps = 0;
	ON_Zero_Channel_1();
	Rotary_Steps = 0;
	ON_Zero_Channel_2();
	
  	if ( NumberOfChannels == 4) // TMW complete changed (4-Channel Version)
 	{
		Virtual_ZeroLevelCH3 = 0;
//BF del		CH3_Zero_Offset      = 0;
	
		Virtual_ZeroLevelCH4 = 0;
//BF del		CH4_Zero_Offset      = 0;
	
		Rotary_Steps = 0;
		ON_Zero_Channel_3();
		Rotary_Steps = 0;
		ON_Zero_Channel_4();
	}
 
	Trigger_Pos_CH1 = ZeroLevelCH1;
	Trigger_Pos_CH2 = ZeroLevelCH2;
	Trigger_Pos_CH3 = ZeroLevelCH3;
	Trigger_Pos_CH4 = ZeroLevelCH4;

			
	if (Channel_1_Active) FindVoltage(1);
	if (Channel_2_Active) FindVoltage(2);

	if (NumberOfChannels > 2)
	{
		if (Channel_3_Active) FindVoltage(3);
		if (Channel_4_Active) FindVoltage(4);
	}


    			
	AutoTimerOff = false;
	Search_Mode  = false;
	
	triggering = triggering_bak;
	ctrl_reg = ctrl_reg_bak;
	adc_ctrl_reg = adc_ctrl_reg_bak;
	
	Continius = Continius_bak;
	SingleMode = SingleMode_bak;
//BF del    UserIface_active = 0;
/*
    Trigger_Pos_CH1 = Trigger_Pos_CH1_bak;
    Trigger_Pos_CH2 = Trigger_Pos_CH2_bak;
    Trigger_Pos_CH3 = Trigger_Pos_CH3_bak;
    Trigger_Pos_CH4 = Trigger_Pos_CH4_bak;
*/


  	if ( NumberOfChannels == 2) // TMW complete changed (2-Channel Version)
	{
		if (Channel_2_Active)
			Virtual_ZeroLevelCH1 = -1 * GRID_HEIGHT / 4; 	//-96; BF
		else
			Virtual_ZeroLevelCH1 = 0;
		
//BF del		CH1_Zero_Offset = 0;
	
		if (Channel_1_Active)
			Virtual_ZeroLevelCH2 = GRID_HEIGHT / 4;		//96; BF
		else
			Virtual_ZeroLevelCH2 = 0;
		
//BF del		CH2_Zero_Offset = 0;
	
		Rotary_Steps = 0;
		if (Channel_1_Active)
		{
			ON_Zero_Channel_1();
			Trigger_Pos_CH1 = ZeroLevelCH1 - 5;
		
			SetDacOffset(1);
			SetCHDacOffset(1);
		}
	
		Rotary_Steps = 0;
		if (Channel_2_Active)
		{
			ON_Zero_Channel_2();
			Trigger_Pos_CH2 = ZeroLevelCH2 - 5;
		
			SetDacOffset(2);
			SetCHDacOffset(2);
		}
    	}
  	else // TMW complete changed (4-Channel Version)
	{
       		Virtual_ZeroLevelCH1 = -120;           
//BF del       		CH1_Zero_Offset = 0;
       		if (Channel_1_Active)
       		{
       			Rotary_Steps = 0;
            		ON_Zero_Channel_1();
            		Trigger_Pos_CH1 = ZeroLevelCH1 - 5;

            		SetDacOffset(1);
            		SetCHDacOffset(1);
        	}
       	
		Virtual_ZeroLevelCH2 = -24; 
//BF del	      	CH2_Zero_Offset = 0;
       		if (Channel_2_Active)
       		{
       			Rotary_Steps = 0;
            		ON_Zero_Channel_2();
            		Trigger_Pos_CH2 = ZeroLevelCH2 - 5;

            		SetDacOffset(2);
            		SetCHDacOffset(2);
        	}
			
		Virtual_ZeroLevelCH3 = 72;           
//BF del       		CH3_Zero_Offset = 0;
       		if (Channel_3_Active)
       		{
       			Rotary_Steps = 0;
           	 	ON_Zero_Channel_3();
            		Trigger_Pos_CH3 = ZeroLevelCH3 - 5;

           		SetDacOffset(3);
           		SetCHDacOffset(3);
        	}
			
		Virtual_ZeroLevelCH4 = 168; 
//BF del       		CH4_Zero_Offset = 0;
       		if (Channel_4_Active)
       		{
       			Rotary_Steps = 0;
            		ON_Zero_Channel_4();
            		Trigger_Pos_CH4 = ZeroLevelCH4 - 5;

            		SetDacOffset(4);
            		SetCHDacOffset(4);
        	}

	}


	acq_ready->np_pioedgecapture = 0;
	
	DoEnableRotInterrupt();
	DoEnableKeyInterrupt();
	DoEnableADCInterrupt();
	DoEnableUARTInterrupt();
	
	Recalc_Vars();
	
	UpdateTrigger(35);
	
	TimebaseChanged = 1;
	TimeOffsetChanged = 1;
	TriggerLevelChanged = 1;
	TriggerModeChanged = 1;
	TriggerWayChanged = 1;
	VoltageChangedCh1 = 1;									// Was Voltage changed
	VoltageChangedCh2 = 1;									// Was Voltage changed
	VoltageChangedCh3 = 1;									// Was Voltage changed
	VoltageChangedCh4 = 1;									// Was Voltage changed          		
			
	Display::StatusUpdate();


/* TMW 	if (Memory_Window_visible)
	{
        Display::DRAWMEMORY(0, 0, 1);
    } TMW*/

	if (Cursor_Enabled)
	{
		Display::CALCCURSORDATA();
		Menu_Changed = 1;
		CursorChanged = 4;
	}
	
	if (QM_Enabled)
	{
		Display::CALCQMDATA();
		Menu_Changed = 1;
	}
	
	Display::DRAW_ALL_CURSOR();
	
	LED_ON[12] = 1;
	LED_ON[13] = 0;
	
	LED_ON[14] = 0;
	LED_ON[15] = 0;
	
	Send_LED();
	
	nr_delay(10);

	SetupADC();
	
	Start_Record();

//    RemovePlane |= 0x1F;
 //   ClearPlanes();

    	return 0;
}

int Hardware::FindTimebase(char channel)
{
    volatile int ix, result, max_cnt, cnt = 0, cnt2 = 0;
    volatile int buf_int = 0;
    volatile long buf_long = 0;

    volatile unsigned char buf_byte = 0;
    volatile unsigned char buf_byte2 = 0;

    int max_tb = 22;

#ifdef _Debug_FindTimebase_
    printf("Start FTB Channel %d\n", channel);
#endif

    switch(channel)
    {
        case 1: serdata->np_piodata = 0x70000015; break;
        case 2: serdata->np_piodata = 0x50000015; break;
        case 3: serdata->np_piodata = 0x10000015; break;
        case 4: serdata->np_piodata = 0x30000015; break;
    }


	serstartsw->np_piodata = 1;
	serstartsw->np_piodata = 0;
	nr_delay(20);



    Selected_Timebase = 4;                                          //  50 nS
    SIGNALFaktor_idx = 0;                                           // zoom factor 1 = 50 nS
    SIGNAL_StartFr_idx = 0;                                         // running. so 0

    timebase_reg = tb_value[Selected_Timebase];
    Display_Timebase = 4;                                          // Displayed timebase is 50 ns

    triggering = 0;								
    ctrl_reg = 0x0087;							                    // Trigger_Master / Trigger_INT / Free Run
    adc_ctrl_reg &= 0xFFF0;						                    // Disable Trigger sources

    SetupADC();

    result = 0;

    max_cnt = 0;

    if (MenuStatus[MENU_AUTOSCALE][1] == 240) max_tb = 16;
			
    while ((result < 15) || (result > 50))
    {
        max_cnt++;

        start_acq->np_piodata = 0x01;				//start record Port On
        start_acq->np_piodata = 0x00;				//start record Port Off

        while (acq_ready->np_piodata == 0x01) {}

        data_adr->np_piodata = 0x01;

        buf_long = READADC(1);
        buf_long = READADC(1);

        WRITEADC(1, ram_adress_reg);
        WRITEADC(2, ram_adress_reg);

        if (NumberOfChannels > 2)
        {
            WRITEADC(3, ram_adress_reg);
            WRITEADC(4, ram_adress_reg);
        }
    	
        data_adr->np_piodata = 0x00;   	

        switch(channel)
        {
            case 1 : ReadOut_Signal(1, 0); break;
            case 2 : ReadOut_Signal(2, 0); break;
            case 3 : ReadOut_Signal(3, 0); break;
            case 4 : ReadOut_Signal(4, 0); break;
        }

        result = 0;
        buf_byte = 0;
        cnt = 0;

        buf_int = (int) ZFT_float;

        if (buf_int <= 0) buf_int = 1;

        switch(channel)
        {
            case 1 :
            {
                buf_min = 255;
                buf_max = 0;

                for (ix = 50; ix < 650; ix++)
                {
                    buf_byte = SIGNAL1[ix * buf_int];
                    buf_arr[cnt++] = buf_byte;
                    if (buf_min < buf_byte) buf_min = buf_byte;
                    if (buf_max > buf_byte) buf_max = buf_byte;
                }

                buf_byte2 = (unsigned char) (((int) buf_min + (int) buf_max) >> 1);

                for (ix = 3; ix < 596; ix++)
                {
                    if ((buf_arr[ix - 3] > buf_byte2 + 1) && (buf_arr[ix + 3] < buf_byte2 - 1)) result++;
                    if ((buf_arr[ix - 3] < buf_byte2 - 1) && (buf_arr[ix + 3] > buf_byte2 + 1)) result++;
                }
#ifdef _Debug_FindTimebase_

                printf("FTB %d cnt %d bi %d st %d sfi %d bb %d bmin %d bmax %d\n", result, cnt, buf_int, Selected_Timebase, SIGNALFaktor_idx, buf_byte2, buf_min, buf_max);
#endif
                break;
            }

            case 2 :
            {
                buf_min = 255;
                buf_max = 0;

                for (ix = 50; ix < 650; ix++)
                {
                    buf_byte = SIGNAL2[ix * buf_int];
                    buf_arr[cnt++] = buf_byte;
                    if (buf_min < buf_byte) buf_min = buf_byte;
                    if (buf_max > buf_byte) buf_max = buf_byte;
                }

                buf_byte2 = (unsigned char) (((int) buf_min + (int) buf_max) >> 1);

                for (ix = 1; ix < 599; ix++)
                {
                    if ((buf_arr[ix - 3] > buf_byte2 + 1) && (buf_arr[ix + 3] < buf_byte2 - 1)) result++;
                    if ((buf_arr[ix - 3] < buf_byte2 - 1) && (buf_arr[ix + 3] > buf_byte2 + 1)) result++;
                }
#ifdef _Debug_FindTimebase_


                printf("FTB %d cnt %d bi %d st %d sfi %d bb %d bmin %d bmax %d\n", result, cnt, buf_int, Selected_Timebase, SIGNALFaktor_idx, buf_byte2, buf_min, buf_max);
#endif
                break;
            }

            case 3 :
            {
                buf_min = 255;
                buf_max = 0;

                for (ix = 50; ix < 650; ix++)
                {
                    buf_byte = SIGNAL3[ix * buf_int];
                    buf_arr[cnt++] = buf_byte;
                    if (buf_min < buf_byte) buf_min = buf_byte;
                    if (buf_max > buf_byte) buf_max = buf_byte;
                }

                buf_byte2 = (unsigned char) (((int) buf_min + (int) buf_max) >> 1);

                for (ix = 1; ix < 599; ix++)
                {
                    if ((buf_arr[ix - 3] > buf_byte2 + 1) && (buf_arr[ix + 3] < buf_byte2 - 1)) result++;
                    if ((buf_arr[ix - 3] < buf_byte2 - 1) && (buf_arr[ix + 3] > buf_byte2 + 1)) result++;
                }
#ifdef _Debug_FindTimebase_


                printf("FTB %d cnt %d bi %d st %d sfi %d bb %d bmin %d bmax %d\n", result, cnt, buf_int, Selected_Timebase, SIGNALFaktor_idx, buf_byte2, buf_min, buf_max);
#endif
                break;
            }

            case 4 :
            {
                buf_min = 255;
                buf_max = 0;

                for (ix = 50; ix < 650; ix++)
                {
                    buf_byte = SIGNAL4[ix * buf_int];
                    buf_arr[cnt++] = buf_byte;
                    if (buf_min < buf_byte) buf_min = buf_byte;
                    if (buf_max > buf_byte) buf_max = buf_byte;
                }

                buf_byte2 = (unsigned char) (((int) buf_min + (int) buf_max) >> 1);

                for (ix = 1; ix < 599; ix++)
                {
                    if ((buf_arr[ix - 3] > buf_byte2 + 1) && (buf_arr[ix + 3] < buf_byte2 - 1)) result++;
                    if ((buf_arr[ix - 3] < buf_byte2 - 1) && (buf_arr[ix + 3] > buf_byte2 + 1)) result++;
                }
#ifdef _Debug_FindTimebase_

                for (cnt2 = 0; cnt2 < 35; cnt2++)
                {
                    printf("%2d : %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d\n", cnt, buf_arr[(cnt * 16) + 0], buf_arr[(cnt * 16) + 1], buf_arr[(cnt * 16) + 2], buf_arr[(cnt * 16) + 3], buf_arr[(cnt * 16) + 4], buf_arr[(cnt * 16) + 5], buf_arr[(cnt * 16) + 6], buf_arr[(cnt * 16) + 7], buf_arr[(cnt * 16) + 8], buf_arr[(cnt * 16) + 9], buf_arr[(cnt * 16) + 10], buf_arr[(cnt * 16) + 11], buf_arr[(cnt * 16) + 12], buf_arr[(cnt * 16) + 13], buf_arr[(cnt * 16) + 14], buf_arr[(cnt * 16) + 15]);
                }

                printf("FTB %d cnt %d bi %d st %d sfi %d bb %d bmin %d bmax %d\n", result, cnt, buf_int, Selected_Timebase, SIGNALFaktor_idx, buf_byte2, buf_min, buf_max);
#endif
                break;
            }
        }
	
        if (result < 15)
        {
            Selected_Timebase_Old = Selected_Timebase;

            if ((Selected_Timebase < 4) && (SIGNALFaktor_idx == 0)) Selected_Timebase++;
            else if ((Selected_Timebase < 7) && (SIGNALFaktor_idx < 4)) SIGNALFaktor_idx++;
            else if ((Selected_Timebase > 6) && (SIGNALFaktor_idx < 2)) SIGNALFaktor_idx++;
            else if (Selected_Timebase < max_tb) Selected_Timebase++;

            if ((Selected_Timebase == 7) && (SIGNALFaktor_idx == 4))
            {
                if (Selected_Timebase_Old == 6)
                {
                    Selected_Timebase = 9;
                    SIGNALFaktor_idx = 2;
                }
            }

            if ((Selected_Timebase == 8) && (SIGNALFaktor_idx == 2))
            {
                if (Selected_Timebase_Old == 9)
                {
                    Selected_Timebase = 6;
                    SIGNALFaktor_idx = 4;
                }
            }

            timebase_reg = tb_value[Selected_Timebase];
            
            if (Selected_Timebase > 7) adc_change12_reg |= 0x01000000;
            else adc_change12_reg &= 0xFEFFFFFF;
            
            SetupADC();
        }

        if (result > 50)
        {
            Selected_Timebase_Old = Selected_Timebase;

            if ((Selected_Timebase > 4) && (SIGNALFaktor_idx == 4)) Selected_Timebase--;
            else if (SIGNALFaktor_idx > 0) SIGNALFaktor_idx--;
            else if ((Selected_Timebase > 2) && (SIGNALFaktor_idx == 0)) Selected_Timebase--;

            if ((Selected_Timebase == 7) && (SIGNALFaktor_idx == 4))
            {
                if (Selected_Timebase_Old == 6)
                {
                    Selected_Timebase = 9;
                    SIGNALFaktor_idx = 2;
                }
            }

            if ((Selected_Timebase == 8) && (SIGNALFaktor_idx == 2))
            {
                if (Selected_Timebase_Old == 9)
                {
                    Selected_Timebase = 6;
                    SIGNALFaktor_idx = 4;
                }
            }

			if ( Selected_Timebase <4 )
				Selected_Timebase =4;

            timebase_reg = tb_value[Selected_Timebase];
            
            if (Selected_Timebase > 7) adc_change12_reg |= 0x01000000;
            else adc_change12_reg &= 0xFEFFFFFF;
            
            SetupADC();

            if ((Selected_Timebase == 2) && (SIGNALFaktor_idx == 0)) result = 25;   // set break condition
        }


        if (Selected_Timebase == max_tb) result = 25;   // set break condition
        if (max_cnt == 25) result = 25;   // set break condition
    }

    Display_Timebase = Selected_Timebase + SIGNALFaktor_idx;

    Stop_Record();

    serdata->np_piodata = 0x700000CA;
	serstartsw->np_piodata = 1;
	serstartsw->np_piodata = 0;
	nr_delay(50);

    serdata->np_piodata = 0x500000CA;
	serstartsw->np_piodata = 1;
	serstartsw->np_piodata = 0;
	nr_delay(50);
	
	if (NumberOfChannels != 2)
	{
        serdata->np_piodata = 0x100000CA;
	    serstartsw->np_piodata = 1;
	    serstartsw->np_piodata = 0;
	    nr_delay(50);

        serdata->np_piodata = 0x300000CA;
	    serstartsw->np_piodata = 1;
	    serstartsw->np_piodata = 0;
	    nr_delay(50);	
    }
	
    nr_delay(300);

    return result;
}

int Hardware::FindVoltage(char channel)
{
    int ix, ix2, buf_int, volt = 12;
    long buf_long = 0;
    volatile unsigned char buf_byte = 0;

    int deltaV = 100;
    int topV = 40;
    int bottomV = 220;

    int posmin = 0, posmax = 0;

#ifdef _Debug_FindVoltage_
    printf("Start Channel %d\n", channel);
#endif

        			
    while (1)
    {
        if (volt > 3)
        {
            volt--;
#ifdef _Debug_FindVoltage_
            printf("decrement volt %d\n", volt);
#endif
        }
        else break;

        topV = 30;
        bottomV = 226;

                /*
        if ((Channel_1_Active) && (Channel_2_Active))
        {
            if (channel == 1)
            {
                topV = 30;
                bottomV = 128;
            }
            else
            {
                topV = 128;
                bottomV = 226;
            }
        }     */

        SetSwitches(channel, volt);

#ifdef _Debug_FindVoltage_
            printf("switches set\n");
#endif
/*
        Selected_Timebase = 15;                                          //  50 nS
        SIGNALFaktor_idx = 2;                                           // zoom factor 1 = 50 nS
//        Selected_Timebase = 4;                                          //  50 nS
//        SIGNALFaktor_idx = 0;                                           // zoom factor 1 = 50 nS
        SIGNAL_StartFr_idx = 0;                                         // running. so 0

        SIGNAL_StartFr_idx = 0;                                         // running. so 0

        timebase_reg = tb_value[Selected_Timebase];
        Display_Timebase = 17;                                          // Displayed timebase is 50 ns
//        Display_Timebase = 4;                                          // Displayed timebase is 50 ns
*/
        triggering = 0;								
        ctrl_reg = 0x0087;							                    // Trigger_Master / Trigger_INT / Free Run
        adc_ctrl_reg &= 0xFFF0;						                    // Disable Trigger sources

        pre_reg = 0x002D;
        //Trigger_Offset_Pos = 162;		//BF del not used

        if (Display_Timebase == 4)
        {
            pre_reg = 0x002D;
            //Trigger_Offset_Pos = 162;		//BF del not used
        }
        else if (Display_Timebase == 5)
        {
            pre_reg = 0x003C;
            //Trigger_Offset_Pos = 162;		//BF del not used
        }
        else if (Display_Timebase == 6)
        {
            pre_reg = 0x0055;
            //Trigger_Offset_Pos = 262;		//BF del not used
        }
        else if (Display_Timebase == 7)
        {
            pre_reg = 0x00A1;
            //Trigger_Offset_Pos = 560;		//BF del not used
        }
        else if (Display_Timebase == 8)
        {
            pre_reg = 0x0120;
            //Trigger_Offset_Pos = 1075;	//BF del not used
        }
        else if (Display_Timebase == 9)
        {
            pre_reg = 0x0120;
            //Trigger_Offset_Pos = 1075;	//BF del not used
        }
        else if (Display_Timebase == 10)
        {
            pre_reg = 0x0120;
            //Trigger_Offset_Pos = 1075;	//BF del not used
        }
        else if (Display_Timebase > 10)
        {
            pre_reg = 0x0110;
            //Trigger_Offset_Pos = 252;		//BF del not used
        }

        SetupADC();


#ifdef _Debug_FindVoltage_
            printf("Setup ADC - start record ctrl %x  pre %x  trig %d   irq %d\n", ctrl_reg, pre_reg, triggering, acq_ready->np_piodata);
#endif

        // first reag
        start_acq->np_piodata = 0x01;				//start record Port On
        start_acq->np_piodata = 0x00;				//start record Port Off	

        while (acq_ready->np_piodata == 0x01) {}

#ifdef _Debug_FindVoltage_
            printf("Data received\n");
#endif

        data_adr->np_piodata = 0x01;

        buf_long = READADC(1);
        buf_long = READADC(1);

        WRITEADC(1, ram_adress_reg);
        WRITEADC(2, ram_adress_reg);

        if (NumberOfChannels > 2)
        {
            WRITEADC(3, ram_adress_reg);
            WRITEADC(4, ram_adress_reg);
        }
    	
        data_adr->np_piodata = 0x00;

#ifdef _Debug_FindVoltage_
            printf("Start read out\n");
#endif         	

        switch(channel)
        {
            case 1 : ReadOut_Signal(1, 0); break;
            case 2 : ReadOut_Signal(2, 0); break;
            case 3 : ReadOut_Signal(3, 0); break;
            case 4 : ReadOut_Signal(4, 0); break;
        }

        buf_int = (int) ZFT_float;

        if (buf_int <= 0) buf_int = 1;


        switch(channel)
        {
            case 1 :
            {

                buf_min = 255;
                buf_max = 0;

#ifdef _Debug_FindVoltage_
                printf("acquire data\n");
#endif
                ix2 = 0;

                for (ix = 150; ix < 650; ix++)
                {
                    buf_byte = SIGNAL1[ix * buf_int];
                    buf_arr[ix2++] = buf_byte;
                    if (buf_min > buf_byte)
                    {
                        buf_min = buf_byte;
                        posmin = ix;
                    }
                    if (buf_max < buf_byte)
                    {
                        buf_max = buf_byte;
                        posmax = ix;
                    }
                }

                break;
            }
            case 2 :
            {
                buf_min = 255;
                buf_max = 0;

                ix2 = 0;

                for (ix = 150; ix < 650; ix++)
                {
                    buf_byte = SIGNAL2[ix * buf_int];
                    buf_arr[ix2++] = buf_byte;
                    if (buf_min > buf_byte)
                    {
                        buf_min = buf_byte;
                        posmin = ix;
                    }
                    if (buf_max < buf_byte)
                    {
                        buf_max = buf_byte;
                        posmax = ix;
                    }
                }

                break;
            }
            case 3 :
            {
                buf_min = 255;
                buf_max = 0;

                ix2 = 0;

                for (ix = 150; ix < 650; ix++)
                {
                    buf_byte = SIGNAL3[ix * buf_int];
                    buf_arr[ix2++] = buf_byte;
                    if (buf_min > buf_byte)
                    {
                        buf_min = buf_byte;
                        posmin = ix;
                    }
                    if (buf_max < buf_byte)
                    {
                        buf_max = buf_byte;
                        posmax = ix;
                    }
                }


                break;
            }
            case 4 :
            {
                buf_min = 255;
                buf_max = 0;

                ix2 = 0;

                for (ix = 150; ix < 650; ix++)
                {
                    buf_byte = SIGNAL4[ix * buf_int];
                    buf_arr[ix2++] = buf_byte;
                    if (buf_min > buf_byte)
                    {
                        buf_min = buf_byte;
                        posmin = ix;
                    }
                    if (buf_max < buf_byte)
                    {
                        buf_max = buf_byte;
                        posmax = ix;
                    }
                }

                break;
            }
        }

#ifdef _Debug_FindVoltage_
        printf("Min %d  Max %d  Volt %d \n", buf_min, buf_max, volt);

        for (ix2 = (posmin - 1); ix2 < (posmin + 10); ix2++) printf("S1[%3d] : %d\n", ix2, buf_arr[ix2]);
#endif
        if ((buf_min > topV) && (buf_max < bottomV) && (abs(buf_max - buf_min) > 40)) break;
    }
#ifdef _Debug_FindVoltage_
    printf("Res : Min %d  Max %d  Volt %d \n", buf_min, buf_max, volt);
#endif

	
    switch(channel)
    {
        case 1 : Selected_Voltage_CH1 = volt; SetSwitches(1, Selected_Voltage_CH1); VoltageChangedCh1 = 1; Display::DRAWSTATUS(1, 0); Rotary_Steps = 0; ON_Zero_Channel_1();break;											// Draw Voltage Channel 1
        case 2 : Selected_Voltage_CH2 = volt; SetSwitches(2, Selected_Voltage_CH2); VoltageChangedCh2 = 1; Display::DRAWSTATUS(2, 0); Rotary_Steps = 0; ON_Zero_Channel_2();break;											// Draw Voltage Channel 2
        case 3 : Selected_Voltage_CH3 = volt; SetSwitches(3, Selected_Voltage_CH3); VoltageChangedCh3 = 1; Display::DRAWSTATUS(3, 0); Rotary_Steps = 0; ON_Zero_Channel_3();break;											// Draw Voltage Channel 3
        case 4 : Selected_Voltage_CH4 = volt; SetSwitches(4, Selected_Voltage_CH4); VoltageChangedCh4 = 1; Display::DRAWSTATUS(4, 0); Rotary_Steps = 0; ON_Zero_Channel_4();break;											// Draw Voltage Channel 4

    }
    Display::DRAWSTATUS(6, 0);											// Draw TriggerLevel

#ifdef _Debug_FindVoltage_
    printf("Ready FV\n");
#endif
}
/* BF not used
void Hardware::FindSlope(void)
{
	long buf_long = 0, buf_long1 = 0;
	int cnt = 0;
	// Only two channels so far
	
    Hardware::DoDisableUARTInterrupt();
    Hardware::DoDisableADCInterrupt();
    Hardware::DoDisableKeyInterrupt();
    Hardware::DoDisableRotInterrupt();

    Stop_Record();


    AutoTimerOff = true;    	
	
//    Display::DRAWROUNDBUTTON(230, 180, 220, 80, 0, 0);
//    Display::TEXTOUTxvbig("For startup calibration", 247, 192, 1, UI_Plane2);
//    Display::TEXTOUTxvbig("remove all input lines.", 247, 212, 1, UI_Plane2);
//    Display::TEXTOUTxvbig("Press any key to continue.", 247, 232, 1, UI_Plane2);

  //  printf("Press a key\n");

//	key_reset->np_piodata = 0;										// Reset Keyboard
//	nr_delay(1);
//	key_reset->np_piodata = 1;
//	key_int->np_pioedgecapture = 0;									// clear IRQ conditions	

 //   while (key_int->np_pioedgecapture == 0) {};

//   printf("Yes, a key\n");
	
	// Backup old
    triggering_bak = triggering;
    ctrl_reg_bak = ctrl_reg;
    adc_ctrl_reg_bak = adc_ctrl_reg;
    adc_change12_reg_bak = adc_change12_reg;
    adc_change34_reg_bak = adc_change34_reg;

    Selected_Timebase_bak = Selected_Timebase;
    SIGNALFaktor_idx_bak = SIGNALFaktor_idx;
    SIGNAL_StartFr_idx_bak = SIGNAL_StartFr_idx;
    timebase_reg_bak = timebase_reg;
    Display_Timebase_bak = Display_Timebase;
    Continius_bak = Continius;
    SingleMode_bak = SingleMode;

    Selected_Voltage_CH1_bak = Selected_Voltage_CH1;
    Selected_Voltage_CH2_bak = Selected_Voltage_CH2;
    Selected_Voltage_CH3_bak = Selected_Voltage_CH3;
    Selected_Voltage_CH4_bak = Selected_Voltage_CH4;   	

    ZeroLevelCH1_bak = ZeroLevelCH1;
    ZeroLevelCH2_bak = ZeroLevelCH2;
    ZeroLevelCH3_bak = ZeroLevelCH3;
    ZeroLevelCH4_bak = ZeroLevelCH4;

    Virtual_ZeroLevelCH1_bak = Virtual_ZeroLevelCH1;
    Virtual_ZeroLevelCH2_bak = Virtual_ZeroLevelCH2;
    Virtual_ZeroLevelCH3_bak = Virtual_ZeroLevelCH3;
    Virtual_ZeroLevelCH4_bak = Virtual_ZeroLevelCH4;


    CH1_DAC_Correction_1_bak = CH1_DAC_Correction_1;	
    CH1_DAC_Correction_2_bak = CH1_DAC_Correction_2;
    CH1_DAC_Correction_3_bak = CH1_DAC_Correction_3;

    CH2_DAC_Correction_1_bak = CH2_DAC_Correction_1;	
    CH2_DAC_Correction_2_bak = CH2_DAC_Correction_2;
    CH2_DAC_Correction_3_bak = CH2_DAC_Correction_3;

    CH3_DAC_Correction_1_bak = CH3_DAC_Correction_1;	
    CH3_DAC_Correction_2_bak = CH3_DAC_Correction_2;
    CH3_DAC_Correction_3_bak = CH3_DAC_Correction_3;

    CH4_DAC_Correction_1_bak = CH4_DAC_Correction_1;	
    CH4_DAC_Correction_2_bak = CH4_DAC_Correction_2;
    CH4_DAC_Correction_3_bak = CH4_DAC_Correction_3;
	
	// set test data
	
    CH1_DAC_Correction_1 = 0;	
    CH1_DAC_Correction_2 = 0;
    CH1_DAC_Correction_3 = 0;

    CH2_DAC_Correction_1 = 0;	
    CH2_DAC_Correction_2 = 0;
    CH2_DAC_Correction_3 = 0;

    CH3_DAC_Correction_1 = 0;	
    CH3_DAC_Correction_2 = 0;
    CH3_DAC_Correction_3 = 0;

    CH4_DAC_Correction_1 = 0;	
    CH4_DAC_Correction_2 = 0;
    CH4_DAC_Correction_3 = 0;	

    ZeroLevelCH1 = GRID_HEIGHT / 2;
    Virtual_ZeroLevelCH1 = 0;                                 // Virtual ZeroLevel
    //BF del	CH1_Zero_Offset = 0;                                        // Shift offset when stopped

    ZeroLevelCH2 = GRID_HEIGHT / 2;
    Virtual_ZeroLevelCH2 = 0;                                 // Virtual ZeroLevel
    //BF del	CH2_Zero_Offset = 0;                                        // Shift offset when stopped

    Rotary_Steps = 0;
    Hardware::ON_Zero_Channel_1();

    nr_delay(100);

    Rotary_Steps = 0;
    Hardware::ON_Zero_Channel_2();

    Hardware::SetSwitches(1, 11);

    nr_delay(100);

    Hardware::SetSwitches(2, 11);    	

    nr_delay(100);

    Selected_Timebase  = 4;                                          //  50 nS
    SIGNALFaktor_idx   = 0;                                           // zoom factor 1 = 50 nS
    SIGNAL_StartFr_idx = 0;                                         // running. so 0

    timebase_reg = tb_value[Selected_Timebase];
    Display_Timebase = 4;                                          // Displayed timebase is 50 ns

    HoldOff_Value = 0;
    triggering = 0;								
    //ctrl_reg &= 0xC0FF;							// Clear Pulse and HoldOff bits
    ctrl_reg = 0x0087;							                    // Trigger_Master / Trigger_INT / Free Run
    adc_ctrl_reg &= 0x0100;						                    // Disable Trigger sources
	                     	

    // test generator settings
    adc_change12_reg = 0x30000000;                //  Bit 28 - TestGenerator  - Filter
    adc_change34_reg = 0x10000000;                //  Bit 28 - TestGenerator
    SwitchesCH2 = 0x66DA;                       // TestCounter CH I - IV + 5V Channel II
					
    Hardware::SetSwitches(2, -1);


    la_pulse->np_piodata = 0x01;				//stop record Port On
    la_pulse->np_piodata = 0x00;				//stop record Port Off	
                             																						
    Hardware::SetupADC();
    nr_delay(100);
    Hardware::SetupADC();

    // Run as long not found


//    Hardware::READADC(1);

    acq_ready->np_pioedgecapture = 0;
    acq_ready->np_piodata = 0x00;

 //   while ((buf_long & 0x1000) == 0)
    {
        // first reag
        start_acq->np_piodata = 0x01;				//start record Port On
        start_acq->np_piodata = 0x00;				//start record Port Off

        //printf("slope started\n");	

        while (acq_ready->np_piodata == 0x01)
        {
//#ifdef _Debug_
            //printf("1\n");
            nr_delay(500);

//            Hardware::SetupADC();
//            start_acq->np_piodata = 0x01;				//start record Port On
//            start_acq->np_piodata = 0x00;				//start record Port Off	

            cnt++;
            if (cnt == 20)
            {
//                printf("Slope stoped");
                break;
            }
//#endif
        }


        data_adr->np_piodata = 0x01;

        buf_long  = Hardware::READADC(1);
        buf_long1 = Hardware::READADC(1);

        Hardware::WRITEADC(1, ram_adress_reg);
        Hardware::WRITEADC(2, ram_adress_reg);

        if (NumberOfChannels > 2)
        {
            Hardware::WRITEADC(3, ram_adress_reg);
            Hardware::WRITEADC(4, ram_adress_reg);
        }
    	
        data_adr->np_piodata = 0x00;

        ReadOut_Signal(1, buf_long, 0);
        ReadOut_Signal(2, buf_long, 0);
        if (NumberOfChannels > 2)
        {
            ReadOut_Signal(3, buf_long, 0);
            ReadOut_Signal(4, buf_long, 0);
        }
#ifdef _Debug_
        printf("bl %04x bl1 %08x\n", buf_long, buf_long1);
#endif
    }

    la_gate->np_piodata = 0x00;
    slope_value = la_data->np_piodata;


    // restore old
    triggering = triggering_bak;
    ctrl_reg = ctrl_reg_bak;
    adc_ctrl_reg = adc_ctrl_reg_bak;

    Continius = Continius_bak;
    SingleMode = SingleMode_bak;

    SwitchesCH2 &= 0x00FF;
    adc_change12_reg = adc_change12_reg_bak;
    adc_change34_reg = adc_change34_reg_bak;

    Selected_Timebase = Selected_Timebase_bak;
    SIGNALFaktor_idx = SIGNALFaktor_idx_bak;
    SIGNAL_StartFr_idx = SIGNAL_StartFr_idx_bak;
    timebase_reg = timebase_reg_bak;
    Display_Timebase = Display_Timebase_bak;

    Selected_Voltage_CH1 = Selected_Voltage_CH1_bak;
    Selected_Voltage_CH2 = Selected_Voltage_CH2_bak;
    Selected_Voltage_CH3 = Selected_Voltage_CH3_bak;
    Selected_Voltage_CH4 = Selected_Voltage_CH4_bak;   	

    ZeroLevelCH1 = ZeroLevelCH1_bak;
    ZeroLevelCH2 = ZeroLevelCH2_bak;
    ZeroLevelCH3 = ZeroLevelCH3_bak;
    ZeroLevelCH4 = ZeroLevelCH4_bak;

    Virtual_ZeroLevelCH1 = Virtual_ZeroLevelCH1_bak;
    Virtual_ZeroLevelCH2 = Virtual_ZeroLevelCH2_bak;
    Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3_bak;
    Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4_bak;

    CH1_DAC_Correction_1 = CH1_DAC_Correction_1_bak;	
    CH1_DAC_Correction_2 = CH1_DAC_Correction_2_bak;
    CH1_DAC_Correction_3 = CH1_DAC_Correction_3_bak;

    CH2_DAC_Correction_1 = CH2_DAC_Correction_1_bak;	
    CH2_DAC_Correction_2 = CH2_DAC_Correction_2_bak;
    CH2_DAC_Correction_3 = CH2_DAC_Correction_3_bak;

    CH3_DAC_Correction_1 = CH3_DAC_Correction_1_bak;	
    CH3_DAC_Correction_2 = CH3_DAC_Correction_2_bak;
    CH3_DAC_Correction_3 = CH3_DAC_Correction_3_bak;

    CH4_DAC_Correction_1 = CH4_DAC_Correction_1_bak;	
    CH4_DAC_Correction_2 = CH4_DAC_Correction_2_bak;
    CH4_DAC_Correction_3 = CH4_DAC_Correction_3_bak;

    Hardware::UpdateTrigger(33);

    Rotary_Steps = 0;
    Hardware::ON_Zero_Channel_1();
    Rotary_Steps = 0;
    Hardware::ON_Zero_Channel_2();

    Hardware::SetSwitches(1, Selected_Voltage_CH1);
    Hardware::SetSwitches(2, Selected_Voltage_CH2);



//    Display::DRAWROUNDBUTTON(230, 180, 220, 80, 0, 1);
//    Display::TEXTOUTxvbig("For startup calibration", 247, 192, 0, UI_Plane2);
//    Display::TEXTOUTxvbig("remove all input lines.", 247, 212, 0, UI_Plane2);
//    Display::TEXTOUTxvbig("Press any key to continue.", 247, 232, 0, UI_Plane2);	

    AutoTimerOff = false;    	

    Hardware::DoEnableRotInterrupt();
    Hardware::DoEnableKeyInterrupt();
    Hardware::DoEnableADCInterrupt();
    Hardware::DoEnableUARTInterrupt();	
#ifdef _Debug_
    printf("Slope : %x\n", slope_value);
#endif
}
*/

void Hardware::DoEnableReadVSyncInterrupt(void)						// Enable ReadVSync service routine
{

	read_vsync->np_pioedgecapture = 0x00; 							// clear existing IRQ conditions
	read_vsync->np_piodirection = 0;								// set bit to input
	read_vsync->np_piointerruptmask = 0x01;							// enable interrupt

	nr_installuserisr(na_read_vsync_irq,ISR_ReadVSync_INT,(int)read_vsync);		// Install ISR for ReadVSync
#ifdef _Debug_IRQ_
	if (Debug_Mode) printf("read_vsync interrupt enabled.\n"); 					// print on console
#endif	

}

void Hardware::DoDisableReadVSyncInterrupt(void)					// Disable ReadVSync service routine
{
	nr_installuserisr(na_read_vsync_irq,0,0); 						// Install empty routine for ReadVSync irq
	read_vsync->np_piointerruptmask = 0x00;							// disable all IRQs
}

void Hardware::ISR_ReadVSync_INT(int context)						// ReadVSync interrupt subroutine
{
    	//BF del tc_test_var2++;
	VSync_Needed = 1;	
	vs_counter++;
	read_vsync->np_pioedgecapture = 0;								// clear IRQ conditions	

#ifdef _Debug_IRQ_
	//if (Debug_Mode) printf("read_vsync interrupt enabled.\n"); 					// print on console
#endif		
}

void Hardware::TransferPlanes(void)
{
	int cnt;
	
	if (VSync_Needed == 0) return;
	if (MenuPopupActive > -1) return;
	
	if (UpdateMarkerPlane) TransferPlanes_asm_persistant(0x008CABE4, 0x009D9DF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);
	UpdateMarkerPlane = false;
	
	if (UpdateMenuTextPlane)
	{
		if ((QM_Enabled == 1) || (Cursor_Enabled == 1))				//BF add by Guido
		{
			TransferDataPlane_asm_persistant(0x008DBB24, 0x00970F30);	//BF add by Guido	
		}
		else
		{
			TransferDataPlane_asm_persistant(0x008DC254, 0x00971660);	//BF -> fixed by Guido 			
		}
		//TransferDataPlane_asm_persistant(0x008DC254, 0x00971660);	//BF -> fixed by Guido 
		
	}
	UpdateMenuTextPlane = false;
	
	if (Splash_drawed) return;
	
//!!!!!!!!!!!!!!!!!!! BF TEST !!!!!!!!!!!!!!!!!!!	
	//if (UI_request) return;	
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if (MenuStatus[MENU_DISPLAY][0] == 240)
    {
        switch(ClearPlane)
        {
            case 0x01 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break;
            case 0x02 : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break;
            case 0x03 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x00000000, 0x00000000, 2); break;
            case 0x04 : TransferPlanes_asm(0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break;	
            case 0x05 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 2); break;
            case 0x06 : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 2); break;	
            case 0x07 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 3); break;
            case 0x08 : TransferPlanes_asm(0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break;
            case 0x09 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2); break;
            case 0x0A : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2); break;	
            case 0x0B : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 3); break;
            case 0x0C : TransferPlanes_asm(0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2); break;	
            case 0x0D : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 3); break;
            case 0x0E : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 3); break;

            case 0x0F :
            {
                TransferPlane_Set_Buffer_Adr(0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                break;
            }

            case 0x10 : TransferPlanes_asm(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break;	
            case 0x11 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2); break;
            case 0x12 : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2); break;	
            case 0x13 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009311F0, 0x009B45F0, 3); break;	
            case 0x14 : TransferPlanes_asm(0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2); break;
            case 0x15 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 3); break;	
            case 0x16 : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 3); break;

            case 0x17 :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                break;
            }

            case 0x18 : TransferPlanes_asm(0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2); break;		
            case 0x19 : TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3); break;		
            case 0x1A : TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3); break;		

            case 0x1B :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 4);
                break;
            }

            case 0x1C : TransferPlanes_asm(0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3); break;	

            case 0x1D :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                break;
            }

            case 0x1E :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                else TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                break;
            }

            case 0x1F :
            {
                TransferPlane_Set_Buffer_Adr(0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 5);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 5);
                break;
            }  		
        }
    }
    else
    {	
        switch(ClearPlane)
        {
            case 0x01 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);break;
            case 0x02 : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);break;
            case 0x03 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x00000000, 0x00000000, 2);break;
            case 0x04 : TransferPlanes_asm_persistant(0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);break;	
            case 0x05 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 2);break;
            case 0x06 : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 2);break;
            case 0x07 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 3);break;
            case 0x08 : TransferPlanes_asm_persistant(0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);break;                               		
            case 0x09 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2);break;
            case 0x0A : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2);break;
            case 0x0B : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 3);break;
            case 0x0C : TransferPlanes_asm_persistant(0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2);break;
            case 0x0D : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 3);break;
            case 0x0E : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 3);break;

            case 0x0F :
            {
                TransferPlane_Set_Buffer_Adr(0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                break;
            }

            case 0x10 : TransferPlanes_asm_persistant(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);break;
            case 0x11 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);break;
            case 0x12 : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);break;
            case 0x13 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009311F0, 0x009B45F0, 3);break;
            case 0x14 : TransferPlanes_asm_persistant(0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);break;
            case 0x15 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 3);break;
            case 0x16 : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 3);break;

            case 0x17 :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
                break;
            }

            case 0x18 : TransferPlanes_asm_persistant(0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);break;                              		
            case 0x19 : TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3);break;     		
            case 0x1A : TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3);break;

            case 0x1B :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 4);
                break;
            }

            case 0x1C : TransferPlanes_asm_persistant(0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3);break;

            case 0x1D :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                break;
            }

            case 0x1E :
            {
                TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                else TransferPlanes_asm_persistant(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
                break;
            }

            case 0x1F :
            {
                TransferPlane_Set_Buffer_Adr(0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0);
                if (MenuStatus[MENU_DISPLAY][0] == 240) TransferPlanes_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 5);
                else TransferPlanes_asm_persistant(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 5);
                break;
            }
        }
    }

     /*
	// pixel error correction
	if ((ClearPlane & 0x01) == 0x01)
    {
    //    for (cnt = 20; cnt < 480; cnt++) Buffer_Plane1[cnt * 20] = Buffer_Plane1[cnt * 20] << 2;	
        	
    }

    for (cnt = 20; cnt < 480; cnt++)
    {
        if ((ClearPlane & 0x01) == 0x01) Channel_Plane1[cnt * 20] = Channel_Plane1[cnt * 20] << 2;
        if ((ClearPlane & 0x02) == 0x02) Channel_Plane2[cnt * 20] = Channel_Plane2[cnt * 20] << 2;
        if ((ClearPlane & 0x04) == 0x04) Channel_Plane3[cnt * 20] = Channel_Plane3[cnt * 20] << 2;
        if ((ClearPlane & 0x08) == 0x08) Channel_Plane4[cnt * 20] = Channel_Plane4[cnt * 20] << 2;
        if ((ClearPlane & 0x10) == 0x10) Channel_Math_Plane[cnt * 20] = Channel_Math_Plane[cnt * 20] << 2;

    }
    */

	if (Splash_drawed == false)
	{
        if (init_done) Display::DRAWSIGNS();

        if (Menu_Changed) Display::UpdateMenu();
    }

	ClearPlane &= 0xE0;	
    	VSync_Needed = 0;
    	
	//reset_watchdog->np_piodata = 0x01;								// Enable WatchDog	

}

void Hardware::ClearPlanes(void)
{
//	reset_watchdog->np_piodata = 0x00;								// Disable WatchDog
	
    if (Channel_1_Active == 1) DrawPlane |= 0x01;	
    if (Channel_2_Active == 1) DrawPlane |= 0x02;
    if (Channel_Math_Active == 1) DrawPlane |= 0x10;

    if (NumberOfChannels > 2)
    {
        if (Channel_3_Active == 1) DrawPlane |= 0x04;
        if (Channel_4_Active == 1) DrawPlane |= 0x08;
    }
#ifdef _Debug_
    printf("we clear\n");
#endif       	
	ClearPlane = DrawPlane | RemovePlane;
	DrawPlane = 0;
   	   	
	switch(ClearPlane)
	{
		case 0x01 :
		{ TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break; }
		case 0x02 :
		{ TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break; }
		case 0x03 :
		{ TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x00000000, 0x00000000, 2); break; }
		case 0x04 :
		{ TransferPlanes_clear_asm(0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break; }
		case 0x05 :
		{ TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 2); break; }
		case 0x06 :
		{ TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x00000000, 0x00000000, 2); break; }
		case 0x07 :
		{ TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 3); break; }	
		case 0x08 :
	    	{ TransferPlanes_clear_asm(0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1); break; }
        	case 0x09 :
	    	{ TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2); break; }
        	case 0x0A :
	    	{ TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2); break; }
        case 0x0B :
	    {
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 3);
            break;
		}
        case 0x0C :
	    {
            TransferPlanes_clear_asm(0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000, 2);
            break;	
		}
        case 0x0D :
	    {
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 3);
            break;
		}
        case 0x0E :
	    {
            TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 3);
            break;
		}
        case 0x0F :
	    {
            TransferPlane_Set_Buffer_Adr(0x009569F0, 0x009AAFF0, 0x00000000, 0x00000000);
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
            break;
		}     	
	    case 0x10 :
	    {
            TransferPlanes_clear_asm(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 1);
            break;	
		}
	    case 0x11 :
	    {
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);
            break;
		}
	    case 0x12 :
	    {
            TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);
            break;	
		}
	    case 0x13 :
	    {  	
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009311F0, 0x009B45F0, 3);
            break;	
		}
	    case 0x14 :
	    {
            TransferPlanes_clear_asm(0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);
            break;
		}
	    case 0x15 :
	    {
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 3);
            break;	
		}
	    case 0x16 :
	    {
            TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009311F0, 0x009B45F0, 3);
            break;
		}
	    case 0x17 :
	    {
            TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 4);
            break;		
		}
        case 0x18 :
	    {
            TransferPlanes_clear_asm(0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 0x00000000, 0x00000000, 2);
            break;		
		}                                        		
        case 0x19 :
	    {
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3);
            break;		
		}               		
        case 0x1A :
	    {
            TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3);
            break;		
		}
        case 0x1B :
	    {
            TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);	
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x009569F0, 0x009AAFF0, 4);
            break;		
		}
        case 0x1C :
	    {
            TransferPlanes_clear_asm(0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0, 3);
            break;	
		}
        case 0x1D :
	    {
            TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
            break;
		}
        case 0x1E :
	    {
            TransferPlane_Set_Buffer_Adr(0x009311F0, 0x009B45F0, 0x00000000, 0x00000000);
            TransferPlanes_clear_asm(0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 0x009569F0, 0x009AAFF0, 4);
            break;	
		}           		
        case 0x1F :
	    {
            TransferPlane_Set_Buffer_Adr(0x009569F0, 0x009AAFF0, 0x009311F0, 0x009B45F0);
            TransferPlanes_clear_asm(0x0093A7F0, 0x0098EDF0, 0x00943DF0, 0x009983F0, 0x0094D3F0, 0x009A19F0, 5);
            break;
		}		
	}	
	
	if (init_done) Display::DRAWSIGNS();

	ClearPlane &= 0xE0;	
    	
//	reset_watchdog->np_piodata = 0x01;								// Enable WatchDog	
}
//#####################################################################################################################################
//BF chanded by Guido
void Hardware::TransferDataPlane_asm_persistant(unsigned long Buffer_Adr1, unsigned long Plane_Adr1)
{
	if ((QM_Enabled == 1) || (Cursor_Enabled == 1))
	{
		asm("
            		PFX	    %hi(1460)                	; //Set Counter 	BF-> change from 1460 to 1000 for new grid to avoid pixel error
            		MOVI	%l1,%lo(1460)			; //BF-> new values calculated by Guido

            		loopmtpp1:
            		LD     %l0, [%i0]                  	; //Load Buffer Data to %r0 	
            		ST     [%i1], %l0                  	; //Store it to Plane

            		ADDI   %i0, 4               		; //Add Address Counter
            		ADDI   %i1, 4	
	
            		SUBI   %l1, 1              		; //Decrement Line Counter
            		SKPS   cc_z
            		BR     loopmtpp1
            		NOP 	
        		");
	}
	else
	{
		asm("
            		PFX	    %hi(1000)                	; //Set Counter 	BF-> change from 1460 to 1000 for new grid to avoid pixel error
            		MOVI	%l1,%lo(1000)			; //BF-> new values calculated by Guido

            		loopmtpp1_a:
            		LD     %l0, [%i0]                  	; //Load Buffer Data to %r0 	
            		ST     [%i1], %l0                  	; //Store it to Plane

            		ADDI   %i0, 4               		; //Add Address Counter
            		ADDI   %i1, 4	
	
            		SUBI   %l1, 1              		; //Decrement Line Counter
            		SKPS   cc_z
            		BR     loopmtpp1_a
            		NOP 	
        		");
	}
}

void Hardware::TransferPlane_Set_Buffer_Adr(unsigned long Buffer_Adr1, unsigned long Plane_Adr1, unsigned long Buffer_Adr2, unsigned long Plane_Adr2)
{
    asm("
            MOV		%r4,%i0	
            MOV		%r5,%i1

            MOV		%r6,%i2
            MOV		%r7,%i3
        ");
}

void Hardware::TransferPlanes_asm(unsigned long Buffer_Adr1, unsigned long Plane_Adr1, unsigned long Buffer_Adr2, unsigned long Plane_Adr2, unsigned long Buffer_Adr3, unsigned long Plane_Adr3, unsigned char count)
{
	switch(count)
	{
	    case 1 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptp1:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane
                    ST     [%i0], %l2                        ; Clear Buffer

                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptp1
                    NOP 	
                ");
            break;
        }
	    case 2 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptp2:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane
                    ST     [%i0], %l2                        ; Clear Buffer

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane
                    ST     [%i2], %l2                        ; Clear Buffer
                                                              	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptp2
                    NOP 	
                ");
            break;
        }

	    case 3 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptp3:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane
                    ST     [%i0], %l2                        ; Clear Buffer

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane
                    ST     [%i2], %l2                        ; Clear Buffer

                    LD     %l0, [%i4]                        ; Load Buffer Data to %r0
                    ST     [%i5], %l0                        ; Store it to Plane
                    ST     [%i4], %l2                        ; Clear Buffer
                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptp3
                    NOP 	
                ");
            break;
        }

	    case 4 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptp4:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane
                    ST     [%i0], %l2                        ; Clear Buffer

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane
                    ST     [%i2], %l2                        ; Clear Buffer

                    LD     %l0, [%i4]                        ; Load Buffer Data to %r0
                    ST     [%i5], %l0                        ; Store it to Plane
                    ST     [%i4], %l2                        ; Clear Buffer

                    LD     %l0, [%r4]                        ; Load Buffer Data to %r0
                    ST     [%r5], %l0                       ; Store it to Plane
                    ST     [%r4], %l2                        ; Clear Buffer
                          	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    ADDI   %r4, 4
                    ADDI   %r5, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptp4
                    NOP 	
                ");
            break;
        }                        	
	    case 5 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptp5:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane
                    ST     [%i0], %l2                        ; Clear Buffer

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane
                    ST     [%i2], %l2                        ; Clear Buffer

                    LD     %l0, [%i4]                        ; Load Buffer Data to %r0
                    ST     [%i5], %l0                        ; Store it to Plane
                    ST     [%i4], %l2                        ; Clear Buffer

                    LD     %l0, [%r4]                        ; Load Buffer Data to %r0
                    ST     [%r5], %l0                       ; Store it to Plane
                    ST     [%r4], %l2                        ; Clear Buffer

                    LD     %l0, [%r6]                        ; Load Buffer Data to %r0
                    ST     [%r7], %l0                       ; Store it to Plane
                    ST     [%r6], %l2                        ; Clear Buffer
                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    ADDI   %r4, 4
                    ADDI   %r5, 4	
	
                    ADDI   %r6, 4
                    ADDI   %r7, 4		
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptp5
                    NOP 	
                ");
            break;
        }
    }
}

void Hardware::TransferPlanes_asm_persistant(unsigned long Buffer_Adr1, unsigned long Plane_Adr1, unsigned long Buffer_Adr2, unsigned long Plane_Adr2, unsigned long Buffer_Adr3, unsigned long Plane_Adr3, unsigned char count)
{
	switch(count)
	{
	    case 1 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    looptpp1:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane
                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpp1
                    NOP 	
                ");
            break;
        }
	    case 2 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)
	
                    looptpp2:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane
                                                              	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpp2
                    NOP 	
                ");
            break;
        }

	    case 3 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)
	
                    looptpp3:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane

                    LD     %l0, [%i4]                        ; Load Buffer Data to %r0
                    ST     [%i5], %l0                        ; Store it to Plane
                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpp3
                    NOP 	
                ");
            break;
        }
	    case 4 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    looptpp4:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane

                    LD     %l0, [%i4]                        ; Load Buffer Data to %r0
                    ST     [%i5], %l0                        ; Store it to Plane

                    LD     %l0, [%r4]                        ; Load Buffer Data to %r0
                    ST     [%r5], %l0                       ; Store it to Plane
                          	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    ADDI   %r4, 4
                    ADDI   %r5, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpp4
                    NOP 	
                ");
            break;
        }                        	
	    case 5 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    looptpp5:
                    LD     %l0, [%i0]                        ; Load Buffer Data to %r0 	
                    ST     [%i1], %l0                        ; Store it to Plane

                    LD     %l0, [%i2]                        ; Load Buffer Data to %r0
                    ST     [%i3], %l0                        ; Store it to Plane

                    LD     %l0, [%i4]                        ; Load Buffer Data to %r0
                    ST     [%i5], %l0                        ; Store it to Plane

                    LD     %l0, [%r4]                        ; Load Buffer Data to %r0
                    ST     [%r5], %l0                       ; Store it to Plane

                    LD     %l0, [%r6]                        ; Load Buffer Data to %r0
                    ST     [%r7], %l0                       ; Store it to Plane
                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    ADDI   %r4, 4
                    ADDI   %r5, 4	
	
                    ADDI   %r6, 4
                    ADDI   %r7, 4		
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpp5
                    NOP 	
                ");
            break;
        }
    }
}

void Hardware::TransferPlanes_clear_asm(unsigned long Buffer_Adr1, unsigned long Plane_Adr1, unsigned long Buffer_Adr2, unsigned long Plane_Adr2, unsigned long Buffer_Adr3, unsigned long Plane_Adr3, unsigned char count)
{
	switch(count)
	{
	    case 1 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptpc1:
                    ST     [%i0], %l2                        ; Clear Buffer
                    ST     [%i1], %l2                        ; Store it to Plane

                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpc1
                    NOP 	
                ");
            break;
        }
	    case 2 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptpc2:
                    ST     [%i0], %l2                        ; Clear Buffer
                    ST     [%i1], %l2                        ; Store it to Plane

                    ST     [%i2], %l2                        ; Clear Buffer
                    ST     [%i3], %l2                        ; Store it to Plane
                                                              	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpc2
                    NOP 	
                ");
            break;
        }

	    case 3 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptpc3:
                    ST     [%i0], %l2                        ; Clear Buffer
                    ST     [%i1], %l2                        ; Store it to Plane

                    ST     [%i2], %l2                        ; Clear Buffer
                    ST     [%i3], %l2                        ; Store it to Plane

                    ST     [%i4], %l2                        ; Clear Buffer
                    ST     [%i5], %l2                        ; Store it to Plane
                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpc3
                    NOP 	
                ");
            break;
        }
	    case 4 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptpc4:
                    ST     [%i0], %l2                        ; Clear Buffer
                    ST     [%i1], %l2                        ; Store it to Plane

                    ST     [%i2], %l2                        ; Clear Buffer
                    ST     [%i3], %l2                        ; Store it to Plane

                    ST     [%i4], %l2                        ; Clear Buffer
                    ST     [%i5], %l2                        ; Store it to Plane

                    ST     [%r4], %l2                        ; Clear Buffer
                    ST     [%r5], %l2                        ; Store it to Plane
                          	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    ADDI   %r4, 4
                    ADDI   %r5, 4	
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpc4
                    NOP 	
                ");
            break;
        }                        	
	    case 5 :
	    {
	        asm("
                    PFX	    %hi(8060)                         ; Set Counter
                    MOVI	%l1,%lo(8060)

                    PFX	    %hi(0)                            ; Set Clear register
                    MOVI	%l2,%lo(0)
                    PFX	    %xhi(0)
                    MOVHI	%l2,%xlo(0)	
	
                    looptpc5:
                    ST     [%i0], %l2                        ; Clear Buffer
                    ST     [%i1], %l2                        ; Store it to Plane

                    ST     [%i2], %l2                        ; Clear Buffer
                    ST     [%i3], %l2                        ; Store it to Plane

                    ST     [%i4], %l2                        ; Clear Buffer
                    ST     [%i5], %l2                        ; Store it to Plane

                    ST     [%r4], %l2                        ; Clear Buffer
                    ST     [%r5], %l2                        ; Store it to Plane

                    ST     [%r6], %l2                        ; Clear Buffer
                    ST     [%r7], %l2                        ; Store it to Plane

                                                               	
                    ADDI   %i0, 4                            ; Add Address Counter
                    ADDI   %i1, 4	

                    ADDI   %i2, 4
                    ADDI   %i3, 4	

                    ADDI   %i4, 4
                    ADDI   %i5, 4	

                    ADDI   %r4, 4
                    ADDI   %r5, 4	
	
                    ADDI   %r6, 4
                    ADDI   %r7, 4		
	
                    SUBI   %l1, 1                            ; Decrement Line Counter
                    SKPS   cc_z
                    BR     looptpc5
                    NOP 	
                ");
            break;
        }
    }
}

void Hardware::Planes_clear_asm(unsigned long Buffer_Adr1)
{
	asm("
            PFX	    %hi(8060)                         ; Set Counter
            MOVI	%l1,%lo(8060)

            PFX	    %hi(0)                            ; Set Clear register
            MOVI	%l2,%lo(0)
            PFX	    %xhi(0)
            MOVHI	%l2,%xlo(0)	
	
        looptpcc1:
            ST     [%i0], %l2                        ; Clear Buffer

            ADDI   %i0, 4                            ; Add Address Counter
	
            SUBI   %l1, 1                            ; Decrement Line Counter
            SKPS   cc_z
            BR     looptpcc1
            NOP 	
        ");
}

void Hardware::Planes_clear_asm_all(unsigned char count, unsigned long Buffer_Adr1, unsigned long Buffer_Adr2, unsigned long Buffer_Adr3, unsigned long Buffer_Adr4, unsigned long Buffer_Adr5)
{
    switch(count)
    {
        case 1 :
        {
	       asm("
                PFX	    %hi(8060)                         ; Set Counter
                MOVI	%l1,%lo(8060)

                PFX	    %hi(0)                            ; Set Clear register
                MOVI	%l2,%lo(0)
                PFX	    %xhi(0)
                MOVHI	%l2,%xlo(0)	
	
            looptpcc21:
                ST     [%i1], %l2                        ; Clear Buffer

                ADDI   %i1, 4                            ; Add Address Counter
            	
                SUBI   %l1, 1                            ; Decrement Line Counter
                SKPS   cc_z
                BR     looptpcc21
                NOP 	
            ");
            break;
        }
        case 2 :
        {
	       asm("
                PFX	    %hi(8060)                         ; Set Counter
                MOVI	%l1,%lo(8060)

                PFX	    %hi(0)                            ; Set Clear register
                MOVI	%l2,%lo(0)
                PFX	    %xhi(0)
                MOVHI	%l2,%xlo(0)	
	
            looptpcc22:
                ST     [%i1], %l2                        ; Clear Buffer
                ST     [%i2], %l2                        ; Clear Buffer

                ADDI   %i1, 4                            ; Add Address Counter
                ADDI   %i2, 4                            ; Add Address Counter
            	
                SUBI   %l1, 1                            ; Decrement Line Counter
                SKPS   cc_z
                BR     looptpcc22
                NOP 	
            ");
            break;
        }
        case 3 :
        {
	       asm("
                PFX	    %hi(8060)                         ; Set Counter
                MOVI	%l1,%lo(8060)

                PFX	    %hi(0)                            ; Set Clear register
                MOVI	%l2,%lo(0)
                PFX	    %xhi(0)
                MOVHI	%l2,%xlo(0)	
	
            looptpcc23:
                ST     [%i1], %l2                        ; Clear Buffer
                ST     [%i2], %l2                        ; Clear Buffer
                ST     [%i3], %l2                        ; Clear Buffer

                ADDI   %i1, 4                            ; Add Address Counter
                ADDI   %i2, 4                            ; Add Address Counter
                ADDI   %i3, 4                            ; Add Address Counter
            	
                SUBI   %l1, 1                            ; Decrement Line Counter
                SKPS   cc_z
                BR     looptpcc23
                NOP 	
            ");
            break;
        }
        case 4 :
        {
	       asm("
                PFX	    %hi(8060)                         ; Set Counter
                MOVI	%l1,%lo(8060)

                PFX	    %hi(0)                            ; Set Clear register
                MOVI	%l2,%lo(0)
                PFX	    %xhi(0)
                MOVHI	%l2,%xlo(0)	
	
            looptpcc24:
                ST     [%i1], %l2                        ; Clear Buffer
                ST     [%i2], %l2                        ; Clear Buffer
                ST     [%i3], %l2                        ; Clear Buffer
                ST     [%i4], %l2                        ; Clear Buffer

                ADDI   %i1, 4                            ; Add Address Counter
                ADDI   %i2, 4                            ; Add Address Counter
                ADDI   %i3, 4                            ; Add Address Counter
                ADDI   %i4, 4                            ; Add Address Counter
            	
                SUBI   %l1, 1                            ; Decrement Line Counter
                SKPS   cc_z
                BR     looptpcc24
                NOP 	
            ");
            break;
        }
        case 5 :
        {
	       asm("
                PFX	    %hi(8060)                         ; Set Counter
                MOVI	%l1,%lo(8060)

                PFX	    %hi(0)                            ; Set Clear register
                MOVI	%l2,%lo(0)
                PFX	    %xhi(0)
                MOVHI	%l2,%xlo(0)	
	
            looptpcc25:
                ST     [%i1], %l2                        ; Clear Buffer
                ST     [%i2], %l2                        ; Clear Buffer
                ST     [%i3], %l2                        ; Clear Buffer
                ST     [%i4], %l2                        ; Clear Buffer
                ST     [%i5], %l2                        ; Clear Buffer

                ADDI   %i1, 4                            ; Add Address Counter
                ADDI   %i2, 4                            ; Add Address Counter
                ADDI   %i3, 4                            ; Add Address Counter
                ADDI   %i4, 4                            ; Add Address Counter
                ADDI   %i5, 4                            ; Add Address Counter
            	
                SUBI   %l1, 1                            ; Decrement Line Counter
                SKPS   cc_z
                BR     looptpcc25
                NOP 	
            ");
            break;
        }
    }
}

void Hardware::DoEnableLogicAnalyserInterrupt(void)							// Enable service routine
{
	la_interrupt->np_pioedgecapture = 0x00; 							// clear all existing IRQ conditions
	la_interrupt->np_piodirection = 0x00;								// set all bits to input
	la_interrupt->np_piointerruptmask = 0x01;							// enable Button IRQs
	la_interrupt->np_piodata = 0;

	nr_installuserisr(na_la_interrupt_irq,ISR_LogicAnalyser,(int)la_interrupt);	// Install ISR for parallel I/Os

#ifdef _Debug_IRQ_
	if (Debug_Mode) printf("\nLogicAnalyser interrupt enabled.\n"); 						// print on console
#endif	
}
	
void Hardware::DoDisableLogicAnalyserInterrupt(void)						// Disable parallel I/O service routine
{
	nr_installuserisr(na_la_interrupt_irq,0,0); 				// Install empty routine for pio irq
	la_interrupt->np_piointerruptmask = 0x00;						// disable all IRQs
}


void Hardware::ISR_LogicAnalyser(int context)
{
	char la_data_cnt;
	
	tc_test_var2++;

	la_gate->np_piodata = 0x01;
	
	for (la_data_cnt = 0; la_data_cnt < 32; la_data_cnt++)
	{
		la_pulse->np_piodata = 0x01;
		
		LogicData[la_data_cnt] = la_data-> np_piodata;
		
		la_pulse->np_piodata = 0x00;		
	}	
	
	la_gate->np_piodata = 0x00;
	
    la_interrupt->np_pioedgecapture = 0; 								// clear IRQ conditions		

	//if (USB_Data_Trans == 1)
	{
		send_buffer[0] = 3;						// Command Write Data
		send_buffer[1] = 20;
		send_buffer[2] = 1;
		
		SendData(send_buffer);	
	}
#ifdef _Debug_IRQ_	
	if (Debug_Mode) printf("\nLogicAnalyser interrupt received\n");
#endif	
}

/****************************************************************************/
/* clear: zeroize a FIR delay line                                          */
/****************************************************************************/
void clear(int ntaps, SAMPLE z[])
{
    int ii;
    for (ii = 0; ii < ntaps; ii++) {
        z[ii] = 0;
    }
}

/****************************************************************************
* fir_basic: Does the basic FIR algorithm: store input sample, calculate
* output sample, move delay line
*****************************************************************************/
SAMPLE fir_basic(SAMPLE input, int ntaps, const SAMPLE h[], SAMPLE z[])
{
    int ii;
    SAMPLE accum;

    /* store input at the beginning of the delay line */
    z[0] = input;

    /* calc FIR */
    accum = 0;
    for (ii = 0; ii < ntaps; ii++) {
        accum += h[ii] * z[ii];
    }

    /* shift delay line */
    for (ii = ntaps - 2; ii >= 0; ii--) {
        z[ii + 1] = z[ii];
    }

    return accum;
}

/****************************************************************************
* fir_circular: This function illustrates the use of "circular" buffers
* in FIR implementations.  The advantage of circular buffers is that they
* alleviate the need to move data samples around in the delay line (as
* was done in all the functions above).  Most DSP microprocessors implement
* circular buffers in hardware, which allows a single FIR tap can be
* calculated in a single instruction.  That works fine when programming in
* assembly, but since C doesn't have any constructs to represent circular
* buffers, you need to "fake" them in C by adding an extra "if" statement
* inside the FIR calculation, even if the DSP processor provides hardware to
* implement them without overhead.
*****************************************************************************/
SAMPLE fir_circular(SAMPLE input, int ntaps, const SAMPLE h[], SAMPLE z[],
                    int *p_state)
{
    int ii, state;
    SAMPLE accum;

    state = *p_state;               /* copy the filter's state to a local */

    /* store input at the beginning of the delay line */
    z[state] = input;
    if (++state >= ntaps) {         /* incr state and check for wrap */
        state = 0;
    }

    /* calc FIR and shift data */
    accum = 0;
    for (ii = ntaps - 1; ii >= 0; ii--) {
        accum += h[ii] * z[state];
        if (++state >= ntaps) {     /* incr state and check for wrap */
            state = 0;
        }
    }

    *p_state = state;               /* return new state to caller */

    return accum;
}

/****************************************************************************
* fir_shuffle: This is like fir_basic, except that data is shuffled by
* moving it _inside_ the calculation loop.  This is similar to the MACD
* instruction on TI's fixed-point processors
*****************************************************************************/
SAMPLE fir_shuffle(SAMPLE input, int ntaps, const SAMPLE h[], SAMPLE z[])
{
    int ii;
    SAMPLE accum;

    /* store input at the beginning of the delay line */
    z[0] = input;

    /* calc FIR and shift data */
    accum = h[ntaps - 1] * z[ntaps - 1];
    for (ii = ntaps - 2; ii >= 0; ii--) {
        accum += h[ii] * z[ii];
        z[ii + 1] = z[ii];
    }

    return accum;
}

/****************************************************************************
* fir_split: This splits the calculation into two parts so the circular
* buffer logic doesn't have to be done inside the calculation loop
*****************************************************************************/
SAMPLE fir_split(SAMPLE input, int ntaps, const SAMPLE h[], SAMPLE z[], int *p_state)
{
    int ii, end_ntaps, state = *p_state;
    SAMPLE accum;
    SAMPLE const *p_h;
    SAMPLE *p_z;

    /* setup the filter */
    accum = 0;
    p_h = h;

    /* calculate the end part */
    p_z = z + state;
    *p_z = input;
    end_ntaps = ntaps - state;
    for (ii = 0; ii < end_ntaps; ii++) {
        accum += *p_h++ * *p_z++;
    }

    /* calculate the beginning part */
    p_z = z;
    for (ii = 0; ii < state; ii++) {
        accum += *p_h++ * *p_z++;
    }

    /* decrement the state, wrapping if below zero */
    if (--state < 0) {
        state += ntaps;
    }
    *p_state = state;       /* return new state to caller */

    return accum;
}

/****************************************************************************
* fir_double_z: double the delay line so the FIR calculation always
* operates on a flat buffer
*****************************************************************************/
SAMPLE fir_double_z(SAMPLE input, int ntaps, const SAMPLE h[], SAMPLE z[], int *p_state)
{
    SAMPLE accum;
    int ii, state = *p_state;
    SAMPLE const *p_h, *p_z;

    /* store input at the beginning of the delay line as well as ntaps more */
    z[state] = z[state + ntaps] = input;

    /* calculate the filter */
    p_h = h;
    p_z = z + state;
    accum = 0;
    for (ii = 0; ii < ntaps; ii++) {
        accum += *p_h++ * *p_z++;
    }

    /* decrement state, wrapping if below zero */
    if (--state < 0) {
        state += ntaps;
    }
    *p_state = state;       /* return new state to caller */

    return accum;
}

/****************************************************************************
* fir_double_h: uses doubled coefficients (supplied by caller) so that the
* filter calculation always operates on a flat buffer.
*****************************************************************************/
SAMPLE fir_double_h(SAMPLE input, int ntaps, const SAMPLE h[], SAMPLE z[], int *p_state)
{
    SAMPLE accum;
    int ii, state = *p_state;
    SAMPLE const *p_h, *p_z;

    /* store input at the beginning of the delay line */
    z[state] = input;

    /* calculate the filter */
    p_h = h + ntaps - state;
    p_z = z;
    accum = 0;
    for (ii = 0; ii < ntaps; ii++) {
        accum += *p_h++ * *p_z++;
    }

    /* decrement state, wrapping if below zero */
    if (--state < 0) {
        state += ntaps;
    }
    *p_state = state;       /* return new state to caller */

    return accum;
}

/****************************************************************************
* main: This provides a simple test suite for the functions above.  An
* impulse is fed into each filter implementation, so the output should be
* the "impulse response", that is, the coefficients of the filter.  You
* should see some zeroes, followed by the "coefficents" below, followed by a
* few more zeroes.
*****************************************************************************/
int Hardware::TestFir(void)
{
    static const SAMPLE h[NTAPS] = { 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2 };
    static SAMPLE h2[2 * NTAPS];
    static SAMPLE z[2 * NTAPS];
    static SAMPLE imp[IMP_SIZE];

    SAMPLE output;
    int ii, state;

    /* make impulse input signal */
    clear(IMP_SIZE, imp);


    imp[0]  = 0.0;
    imp[1]  = 0.0;
    imp[2]  = 1.0;
    imp[3]  = 2.0;
    imp[4]  = 3.0;
    imp[5]  = 4.0;
    imp[6]  = 5.0;
    imp[7]  = 4.0;
    imp[8]  = 3.0;
    imp[9]  = 2.0;
    imp[10] = 1.0;
    imp[11] = 0.0;
    imp[12] = -1.0;
    imp[13] = -2.0;
    imp[14] = -3.0;
    imp[15] = -4.0;
    imp[16] = -5.0;
    imp[17] = -4.0;
    imp[18] = -3.0;
    imp[19] = -2.0;
    imp[20] = -1.0;
    imp[21] = 0.0;
    imp[22] = 1.0;
    imp[23] = 2.0;
    imp[24] = 3.0;
    imp[25] = 4.0;
    imp[26] = 5.0;
    imp[27] = 4.0;
    imp[28] = 3.0;
    imp[29] = 2.0;
    imp[30] = 1.0;
    imp[31] = 0.0;
    imp[32] = 0.0;
/*
    imp[0]  = 0.0;
    imp[1]  = 0.0;
    imp[2]  = 0.0;
    imp[3]  = 0.0;
    imp[4]  = 0.0;
    imp[5]  = 0.0;
    imp[6]  = 0.0;
    imp[7]  = 0.0;
    imp[8]  = 0.0;
    imp[9]  = 0.0;
    imp[10] = 0.0;
    imp[11] = 0.0;
    imp[12] = 0.0;
    imp[13] = 0.0;
    imp[14] = 0.0;
    imp[15] = 0.0;
    imp[16] = 0.0;
    imp[17] = 0.0;
    imp[18] = 0.0;
    imp[19] = 0.0;
    imp[20] = 0.0;
*/
/*
    imp[0]  = 0.0;
    imp[1]  = 0.0;
    imp[2]  = 0.0;
    imp[3]  = 0.0;
    imp[4]  = 0.0;
    imp[5]  = 0.0;
    imp[6]  = 0.0;
    imp[7]  = 0.0;
    imp[8]  = 0.0;
    imp[9]  = 0.0;
    imp[10] = 0.0;
    imp[11] = 0.0;
    imp[12] = 0.0;
    imp[13] = 0.0;
    imp[14] = 0.0;
    imp[15] = 0.0;
    imp[16] = 0.0;
    imp[17] = 0.0;
    imp[18] = 0.0;
    imp[19] = 0.0;
    imp[20] = 0.0;
*/

    /* create a SAMPLEd h */
    for (ii = 0; ii < NTAPS; ii++) {
        h2[ii] = h2[ii + NTAPS] = h[ii];
    }

    /* test FIR algorithms */

    printf("Testing fir_basic:\n   ");
    clear(NTAPS, z);
    for (ii = 0; ii < IMP_SIZE; ii++) {
        output = fir_basic(imp[ii], NTAPS, h, z);
        printf("%3.1lf ", (double) output);
    }
    printf("\n\n");

    printf("Testing fir_shuffle:\n   ");
    clear(NTAPS, z);
    state = 0;
    for (ii = 0; ii < IMP_SIZE; ii++) {
        output = fir_shuffle(imp[ii], NTAPS, h, z);
        printf("%3.1lf ", (double) output);
    }
    printf("\n\n");

    printf("Testing fir_circular:\n   ");
    clear(NTAPS, z);
    state = 0;
    for (ii = 0; ii < IMP_SIZE; ii++) {
        output = fir_circular(imp[ii], NTAPS, h, z, &state);
        printf("%3.1lf ", (double) output);
    }
    printf("\n\n");

    printf("Testing fir_split:\n   ");
    clear(NTAPS, z);
    state = 0;
    for (ii = 0; ii < IMP_SIZE; ii++) {
        output = fir_split(imp[ii], NTAPS, h, z, &state);
        printf("%3.1lf ", (double) output);
    }
    printf("\n\n");

    printf("Testing fir_double_z:\n   ");
    clear(2 * NTAPS, z);
    state = 0;
    for (ii = 0; ii < IMP_SIZE; ii++) {
        output = fir_double_z(imp[ii], NTAPS, h, z, &state);
        printf("%3.1lf ", (double) output);
    }
    printf("\n\n");

    printf("Testing fir_double_h:\n   ");
    clear(NTAPS, z);
    state = 0;
    for (ii = 0; ii < IMP_SIZE; ii++) {
        output = fir_double_h(imp[ii], NTAPS, h2, z, &state);
        printf("%3.1lf ", (double) output);
    }

    #ifdef WIN32
        printf("\n\nHit any key to continue.");
        getch();
    #endif

    return 0;
}

//#########################################################################################################################################################
/* BF */

/*
void Hardware::Do_FFT(void)
{

	int icnt;
		//Speicher auf dem Stack reservieren
	int   z,l,i,j,la,r,ar,v;
	float z1,z2,z3,z4,xr,xi,yr,yi;
	int d[LEVEL];      		// Inhalt: LEVEL-1  {Umwandlung}

#ifdef _Debug_FFT_
    printf("starting fft\n");
#endif

//+++++++++++++++++++++++++++++++++++++++++++++++
// get time signal and make a window overlay
//+++++++++++++++++++++++++++++++++++++++++++++++






//+++++++++++++++++++++++++++++++++++++++++++++++
//             calculate FFT
//+++++++++++++++++++++++++++++++++++++++++++++++
	
	//sort timevalues bitreversal
	for(i=0;i<FFT_LENGTH;i++)
	{
		freq_re[i]=SIGNAL1[bit_rev[i]];
		freq_im[i]=0;
	}



	//calculate complex spectral values (butterflies)
	for(l=1;l<=LEVEL;l++)
	{
		for(i=0;i<=((1<<(LEVEL-l))-1);i++)
		{
			for(j=0;j<=((1<<(l-1))-1);j++)
			{
				r = j + i* (1 << l);
				ar= j * (FFT_LENGTH >> l);
				v = 1 << (l-1);
				
				z1 = cos_tab[ar] * freq_re[r+v];
				z2 = cos_tab[ar] * freq_im[r+v];
				z3 = sin_tab[ar] * freq_re[r+v];
				z4 = sin_tab[ar] * freq_im[r+v];
				xr = freq_re[r] + z1 + z4;
				xi = freq_im[r] - z3 + z2;
				yr = freq_re[r] - z1 - z4;
				yi = freq_im[r] + z3 - z2;
				freq_re[r] = xr;
				freq_im[r] = xi;
				freq_re[r+v] = yr;
				freq_im[r+v] = yi;
			}
		}
	}



// copy and scale FFT to math-signal
	for (icnt = 0; icnt < 600; icnt++)
	 SIGNALM[icnt] = 1;
	 //SIGNALM[icnt] = FFTOffsetY;


	//Nur von der Hälfte der Frequenzpunkte den Betrag bilden,
	//da das halbe Spektrum gespiegelt ist
	for (i=0;i <= FFT_LENGTH/2+1;i++)
	{
		z1=freq_re[i]/FFT_LENGTH;
		z2=freq_im[i]/FFT_LENGTH;
		z3=(float)sqrt(pow((double)z1,2) + pow((double)z2,2));
		SIGNALM[i] = (char)z3;	// Betrag des Spektrums
	}






#ifdef _Debug_FFT_
    printf("copy fft to math ready \n");
    printf("fft ready\n");
#endif
}

*/
//##########################################################################################################################################################

void Hardware::floatprintf(float fvalue)
{
	long int pre, aft,factor;
	int i;
	
	//calculating pre FP value
	pre = (long int)fvalue;
	if(pre == 0 && fvalue < 0)	//negativ
		printf("-%d.",pre);
	else
		printf("%d.",pre);
		
	//get leading zero
	if((fvalue - pre) != 0) //check if numbers after FP exist
	{
		for(factor = 10, i= 0 ;0 == (long int)((fvalue - pre) * factor) && i<11; factor*=10, i++)
		{ printf("0"); }
	}
	else
	{	
		printf("000");
		return;
	}
	
	//calc after FP value, minimum 3 numbers after FP
	aft = (long int)((fvalue - pre) * factor * 100);
	
	if(aft < 0)	//kill sign
	{ aft *= -1; }

	printf("%d",aft);

	if(i >= 11)
	printf("overflow");
}

//##########################################################################################################################################################
//BF added
// Calculate ADC offset for specified channel
void Hardware::Calc_ADC_Offset(int channel)
{
	long int ADC1 = 0, ADC2 = 0, ADC3 = 0, ADC4 = 0;
	int ix = 0, ref; 
	
	printf("\nChannel %d start calibrating ADC offsets\n", channel);

	switch(channel)
	{
		case 1:
		{
			//get sum of values separate for each of the four ADCs
			for (ix = 0; ix < 4000; ix+=4)
			{ ADC1 += SIGNAL1[ix];ADC2 += SIGNAL1[ix+1];ADC3 += SIGNAL1[ix+2];ADC4 += SIGNAL1[ix+3];}
			break;	
		}
		case 2:
		{
			//get sum of values separate for each of the four ADCs
			for (ix = 0; ix < 4000; ix+=4)
			{ ADC1 += SIGNAL2[ix];ADC2 += SIGNAL2[ix+1];ADC3 += SIGNAL2[ix+2];ADC4 += SIGNAL2[ix+3];}
			break;	
		}
		case 3:
		{
			//get sum of values separate for each of the four ADCs
			for (ix = 0; ix < 4000; ix+=4)
			{ ADC1 += SIGNAL3[ix];ADC2 += SIGNAL3[ix+1];ADC3 += SIGNAL3[ix+2];ADC4 += SIGNAL3[ix+3];}
			break;	
		}
		case 4:
		{
			//get sum of values separate for each of the four ADCs
			for (ix = 0; ix < 4000; ix+=4)
			{ ADC1 += SIGNAL4[ix];ADC2 += SIGNAL4[ix+1];ADC3 += SIGNAL4[ix+2];ADC4 += SIGNAL4[ix+3];}
			break;	
		}
	}

	//calculate average for each ADC	
	ix = ix >> 2;	

	ADC1 /= ix;
	ADC2 /= ix;
	ADC3 /= ix;
	ADC4 /= ix;

	//get ADC with smallest offset as  zero reference 
	ref = ADC1;
	if( ADC2 < ref ) ref = ADC2;
	if( ADC3 < ref ) ref = ADC3;
	if( ADC4 < ref ) ref = ADC4;
	
	//calculate offsets
        ADC_Offset[channel-1][0] = ADC1 - ref;
	ADC_Offset[channel-1][1] = ADC2 - ref;
	ADC_Offset[channel-1][2] = ADC3 - ref;
	ADC_Offset[channel-1][3] = ADC4 - ref;

	
	printf("ADC 1 Offset = %d\n",ADC_Offset[channel-1][0]);
	printf("ADC 2 Offset = %d\n",ADC_Offset[channel-1][1]);
	printf("ADC 3 Offset = %d\n",ADC_Offset[channel-1][2]);
	printf("ADC 4 Offset = %d\n",ADC_Offset[channel-1][3]);


}

//##########################################################################################################################################################
//BF added
//Calculate DAC offset correction for specified channel
void Hardware::Calc_DAC_Correction(int channel, int *Correction)
{

	//-------------------------------------------------------------------------------------------
	// BF new calibration	
	//------------------------------------------------------------------------------------------
	printf("\nChannel %d start calibrating DAC zero\n", channel);
	printf("DAC correction old  = %d\n", Correction[0]);

	long int ADC_sum = 0;
	int ADC_diff;
	int ix = 0, lvoltage_range = 0, lVirtual_Zero=0; 
	
	switch(channel)
	{
		case 1:
		{
			//get sum of values
			for (ix = 0; ix < 99; ix++)
			{ ADC_sum += SIGNAL1[ix]; }
			lvoltage_range = Selected_Voltage_CH1;
			lVirtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH1 / scale_factor[Selected_Voltage_CH1]);
			//lVirtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH1 / (ZeroScaleFactor[0][Selected_Voltage_CH1] * 2));	
			break;	
		}
		case 2:
		{
			//get sum of values
			for (ix = 0; ix < 99; ix++)
			{ ADC_sum += SIGNAL2[ix]; }
			lvoltage_range = Selected_Voltage_CH2;	
			lVirtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH2 / scale_factor[Selected_Voltage_CH2]);	
			break;	
		}
		case 3:
		{
			//get sum of values
			for (ix = 0; ix < 99; ix++)
			{ ADC_sum += SIGNAL3[ix]; }
			lvoltage_range = Selected_Voltage_CH3;	
			lVirtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH3 / scale_factor[Selected_Voltage_CH3]);	
			break;	
		}
		case 4:
		{
			//get sum of values
			for (ix = 0; ix < 99; ix++)
			{ ADC_sum += SIGNAL4[ix]; }
			lvoltage_range = Selected_Voltage_CH4;	
			lVirtual_Zero = ADC_ZERO + int((float)Virtual_ZeroLevelCH4 / scale_factor[Selected_Voltage_CH4]);	
			break;	
		}
	}

	//get average offset of each ADC-set
	
	ADC_sum /= ix;
	printf("ADC average value  = %d\n", ADC_sum);


	//ADC_diff = ADC_sum - ADC_ZERO;
	ADC_diff = ADC_sum - lVirtual_Zero;
	printf("ADC offset         = %d\n", ADC_diff);
	
	switch(lvoltage_range)
	{
		case 0: Correction[0] -= (ADC_diff << 1); break;//  1 mV
		case 1: Correction[0] -= (ADC_diff << 2); break;//  2 mV
		case 2: Correction[0] -= (ADC_diff << 2); break;//  5 mV
		case 3: Correction[0] -= (ADC_diff << 1); break;// 10 mV
		case 4: Correction[0] -= (ADC_diff << 2); break;// 20 mV
		case 5: Correction[0] -= (ADC_diff << 2); break;// 50 mV
		case 6: Correction[0] -= (ADC_diff << 1); break;//100 mV
		case 7: Correction[0] -= (ADC_diff << 2); break;//200 mV
		case 8: Correction[0] -= (ADC_diff << 2); break;//500 mV
		case 9: Correction[0] -= (ADC_diff << 1); break;// 1 V
		case 10: Correction[0] -= (ADC_diff << 2); break;//2 V
		case 11: Correction[0] -= (ADC_diff << 2); break;//5 V	
	}
		
	printf("DAC Correction new  = %d\n", Correction[0]);

	return;

}
//##########################################################################################################################################################
//BF added
//Calibrate all ADCs
void Hardware::Calibrate_ADC_ZeroOffsets(void)
{

	
	//out_test->np_piodata = 0x01;	// Testbit+++++++++++++++++++++++
	volatile long buffer_addr = 0;	
	volatile long buffer_peak = 0;	
	volatile long buffer_written = 0;	
	volatile long buffer_adradd = 0;

	int channel_trig = 0;

	Stop_Record();
	AutoTimerOff = true;


	Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 0);
	Display::TEXTOUTxvbig("Calibrating ADC Offsets.", 247, 192, 1, UI_Plane2);
	Display::TEXTOUTxvbig("Remove all inputs.", 247, 212, 1, UI_Plane2);
	//Display::TEXTOUTxvbig("Can take up to 1 min.", 247, 232, 1, UI_Plane2);



	//backup settings
	Channel_1_Active_bak = Channel_1_Active; Channel_1_Active = 1;
	Channel_2_Active_bak = Channel_2_Active; Channel_2_Active = 1;

	if (NumberOfChannels > 2)
	{	
		Channel_3_Active_bak = Channel_3_Active; Channel_3_Active = 1;
		Channel_4_Active_bak = Channel_4_Active; Channel_4_Active = 1;
	}
	
	//Wait until ADC is ready
	if (adc_started)
	{
		while (acq_ready->np_piodata == 0x01)
		{}
		adc_started = false;
	}

	//if no new data is available return	
	//if (ADC_Data_Available == 0) return;

	//reset availability flag	
	ADC_Data_Available = 0;

	Start_Record();

	//wait a little bit
	nr_delay(300);	

	//wait for ADC
	for(int timeout = 0;timeout < 100 && !ADC_Data_Available;timeout++)
	nr_delay(10);

	//if no new data is available send message
	if (ADC_Data_Available == 0)
	{ printf("\nNo new Data available for DAC-Calibration\n"); }

	//reset availability flag	
	ADC_Data_Available = 0;

	Stop_Record();

	data_adr->np_piodata = 0x01;


	data_adr->np_piodata = 0x00;
	
	
	//read signal and calibrate ADC-offsets
	if (Channel_1_Active)
	{
		//reset offsets
		ADC_Offset[0][0] = 0;
		ADC_Offset[0][1] = 0;
		ADC_Offset[0][2] = 0;
		ADC_Offset[0][3] = 0;
		ReadOut_Signal(1, buffer_addr & 0x3FFF);
		Calc_ADC_Offset(1);
	}
	
	if (Channel_2_Active)
	{ 
		//reset offsets
		ADC_Offset[1][0] = 0;
		ADC_Offset[1][1] = 0;
		ADC_Offset[1][2] = 0;
		ADC_Offset[1][3] = 0;
		ReadOut_Signal(2, buffer_addr & 0x3FFF);
		Calc_ADC_Offset(2);
	}	
	
	if (NumberOfChannels > 2)
	{	
		if (Channel_3_Active)
		{ 
			//reset offsets
			ADC_Offset[2][0] = 0;
			ADC_Offset[2][1] = 0;
			ADC_Offset[2][2] = 0;
			ADC_Offset[2][3] = 0;
			ReadOut_Signal(3, buffer_addr & 0x3FFF);
			Calc_ADC_Offset(3);
		}
	
		if (Channel_4_Active)
		{
			//reset offsets
			ADC_Offset[3][0] = 0;
			ADC_Offset[3][1] = 0;
			ADC_Offset[3][2] = 0;
			ADC_Offset[3][3] = 0;
			ReadOut_Signal(4, buffer_addr & 0x3FFF);
			Calc_ADC_Offset(4);
		}
	}	


	//restore settings
	Channel_1_Active = Channel_1_Active_bak;
	Channel_2_Active = Channel_2_Active_bak;
	
	if (NumberOfChannels > 2)
	{	
		Channel_3_Active = Channel_3_Active_bak;
		Channel_4_Active = Channel_4_Active_bak;
	}

	//Save new values to flash
   	AMDFlash::Write_Protected_Flash();


	//wait a little bit
	nr_delay(1000);	

	//Delete popup
	Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 1);
	Display::TEXTOUTxvbig("Calibrating ADC Offsets.", 247, 192, 0, UI_Plane2);
	Display::TEXTOUTxvbig("Remove all inputs.", 247, 212, 0, UI_Plane2);
	//Display::TEXTOUTxvbig("Still under construction", 247, 232, 0, UI_Plane2);

	Start_Record();



}

//##########################################################################################################################################################
//BF added
//Calibrate DACs for active channels and active voltage ranges
void Hardware::Calibrate_DAC_ZeroOffsets(void)
{
	volatile long buffer_addr = 0;	
	volatile long buffer_peak = 0;	
	volatile long buffer_written = 0;	
	volatile long buffer_adradd = 0;
	         long timebase_reg_bak;

//	int channel_trig = 0;



	Stop_Record();
	//AutoTimerOff = true;


	Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 0);
	Display::TEXTOUTxvbig("Calibrating DAC Offsets.", 247, 192, 1, UI_Plane2);
	Display::TEXTOUTxvbig("of active channels.", 247, 212, 1, UI_Plane2);
	Display::TEXTOUTxvbig("Remove all inputs.", 247, 232, 1, UI_Plane2);

/*BF -> calibrate only active channels
	//backup settings
	Channel_1_Active_bak = Channel_1_Active; Channel_1_Active = 1;
	Channel_2_Active_bak = Channel_2_Active; Channel_2_Active = 1;

	if (NumberOfChannels > 2)
	{	
		Channel_3_Active_bak = Channel_3_Active; Channel_3_Active = 1;
		Channel_4_Active_bak = Channel_4_Active; Channel_4_Active = 1;
	}
*/




	//Wait until ADC is ready
	if (adc_started)
	{
		while (acq_ready->np_piodata == 0x01)
		{}
		adc_started = false;
	}

	//backup timebase
	timebase_reg_bak = timebase_reg;	

	timebase_reg = 0xFFFFFFFF;                                      // real timebase 50ns (1GSa/s)
 	adc_change12_reg &= 0xFEFFFFFF;

//	nr_delay(300);

	SetupADC();

//	nr_delay(300);

	//make several calibration runs to approximate zero
	for(int i=0; i<5 ; i++)
	{
		Start_Record();
	
		//wait for ADC
		for(int timeout = 0;timeout < 100 && !ADC_Data_Available;timeout++)
		nr_delay(10);
	
		//if no new data is available send error message
		if (ADC_Data_Available == 0)
		{ printf("\nError, no new Data available for DAC-Calibration\n");  }
	
		//reset availability flag	
		ADC_Data_Available = 0;
	
		Stop_Record();
	
	//data_adr->np_piodata = 0x01;
		
	//data_adr->np_piodata = 0x00;
		
	
		//read signal and calibrate DAC-offsets
		if (Channel_1_Active)
		{ 
			ReadOut_Signal(1, buffer_addr & 0x3FFF);
			//long buffer_long; 
			//buffer_long = READADC(1);    // Read correction
			//buffer_long = READADC(1);
			//READADC_ALL2(1, &readout_sigbuf[0], 4096);
			//PREPARE_READADC(ADC_Offset[0][0],ADC_Offset[0][1],ADC_Offset[0][2],ADC_Offset[0][3], 4096);	
			//READADC_ALL(1, &SIGNAL1[0], 0, ADC_ZERO, 0, 1);
	
			switch(Selected_Voltage_CH1)
			{
				case 0: Calc_DAC_Correction(1, &DAC_Correction[0][0]); break;//  1 mV
				case 1: Calc_DAC_Correction(1, &DAC_Correction[0][1]); break;//  2 mV
				case 2: Calc_DAC_Correction(1, &DAC_Correction[0][2]); break;//  5 mV
				case 3: Calc_DAC_Correction(1, &DAC_Correction[0][0]); break;// 10 mV
				case 4: Calc_DAC_Correction(1, &DAC_Correction[0][1]); break;// 20 mV
				case 5: Calc_DAC_Correction(1, &DAC_Correction[0][2]); break;// 50 mV
				case 6: Calc_DAC_Correction(1, &DAC_Correction[0][0]); break;//100 mV
				case 7: Calc_DAC_Correction(1, &DAC_Correction[0][1]); break;//200 mV
				case 8: Calc_DAC_Correction(1, &DAC_Correction[0][2]); break;//500 mV
				case 9: Calc_DAC_Correction(1, &DAC_Correction[0][0]); break;// 1 V
				case 10: Calc_DAC_Correction(1, &DAC_Correction[0][1]); break;//2 V
				case 11: Calc_DAC_Correction(1, &DAC_Correction[0][2]); break;//5 V	
			}
	
		}
		
		if (Channel_2_Active)
		{
			ReadOut_Signal(2, buffer_addr & 0x3FFF); 
			switch(Selected_Voltage_CH2)
			{
				case 0: Calc_DAC_Correction(2, &DAC_Correction[1][0]); break;//  1 mV
				case 1: Calc_DAC_Correction(2, &DAC_Correction[1][1]); break;//  2 mV
				case 2: Calc_DAC_Correction(2, &DAC_Correction[1][2]); break;//  5 mV
				case 3: Calc_DAC_Correction(2, &DAC_Correction[1][0]); break;// 10 mV
				case 4: Calc_DAC_Correction(2, &DAC_Correction[1][1]); break;// 20 mV
				case 5: Calc_DAC_Correction(2, &DAC_Correction[1][2]); break;// 50 mV
				case 6: Calc_DAC_Correction(2, &DAC_Correction[1][0]); break;//100 mV
				case 7: Calc_DAC_Correction(2, &DAC_Correction[1][1]); break;//200 mV
				case 8: Calc_DAC_Correction(2, &DAC_Correction[1][2]); break;//500 mV
				case 9: Calc_DAC_Correction(2, &DAC_Correction[1][0]); break;// 1 V
				case 10: Calc_DAC_Correction(2, &DAC_Correction[1][1]); break;//2 V
				case 11: Calc_DAC_Correction(2, &DAC_Correction[1][2]); break;//5 V	
			}	
		}	
		
		if (NumberOfChannels > 2)
		{	
			if (Channel_3_Active)
			{ 
				ReadOut_Signal(3, buffer_addr & 0x3FFF);
				switch(Selected_Voltage_CH3)
				{
					case 0: Calc_DAC_Correction(3, &DAC_Correction[2][0]); break;//  1 mV
					case 1: Calc_DAC_Correction(3, &DAC_Correction[2][1]); break;//  2 mV
					case 2: Calc_DAC_Correction(3, &DAC_Correction[2][2]); break;//  5 mV
					case 3: Calc_DAC_Correction(3, &DAC_Correction[2][0]); break;// 10 mV
					case 4: Calc_DAC_Correction(3, &DAC_Correction[2][1]); break;// 20 mV
					case 5: Calc_DAC_Correction(3, &DAC_Correction[2][2]); break;// 50 mV
					case 6: Calc_DAC_Correction(3, &DAC_Correction[2][0]); break;//100 mV
					case 7: Calc_DAC_Correction(3, &DAC_Correction[2][1]); break;//200 mV
					case 8: Calc_DAC_Correction(3, &DAC_Correction[2][2]); break;//500 mV
					case 9: Calc_DAC_Correction(3, &DAC_Correction[2][0]); break;// 1 V
					case 10: Calc_DAC_Correction(3, &DAC_Correction[2][1]); break;//2 V
					case 11: Calc_DAC_Correction(3, &DAC_Correction[2][2]); break;//5 V	
				}
			}
		
			if (Channel_4_Active)
			{ 
				ReadOut_Signal(4, buffer_addr & 0x3FFF); 
				switch(Selected_Voltage_CH4)
				{
					case 0: Calc_DAC_Correction(4, &DAC_Correction[3][0]); break;//  1 mV
					case 1: Calc_DAC_Correction(4, &DAC_Correction[3][1]); break;//  2 mV
					case 2: Calc_DAC_Correction(4, &DAC_Correction[3][2]); break;//  5 mV
					case 3: Calc_DAC_Correction(4, &DAC_Correction[3][0]); break;// 10 mV
					case 4: Calc_DAC_Correction(4, &DAC_Correction[3][1]); break;// 20 mV
					case 5: Calc_DAC_Correction(4, &DAC_Correction[3][2]); break;// 50 mV
					case 6: Calc_DAC_Correction(4, &DAC_Correction[3][0]); break;//100 mV
					case 7: Calc_DAC_Correction(4, &DAC_Correction[3][1]); break;//200 mV
					case 8: Calc_DAC_Correction(4, &DAC_Correction[3][2]); break;//500 mV
					case 9: Calc_DAC_Correction(4, &DAC_Correction[3][0]); break;// 1 V
					case 10: Calc_DAC_Correction(4, &DAC_Correction[3][1]); break;//2 V
					case 11: Calc_DAC_Correction(4, &DAC_Correction[3][2]); break;//5 V	
				}
	
			}
		}	
		
		//activate new settings
		Rotary_Steps = 0;
		ON_Zero_Channel_1();
		Rotary_Steps = 0;
		ON_Zero_Channel_2();
	
		if (NumberOfChannels > 2)
		{		
			Rotary_Steps = 0;
			ON_Zero_Channel_3();
			Rotary_Steps = 0;
			ON_Zero_Channel_4();
		}
		
		//wait a little bit
		nr_delay(50);	
	
	
	}//for loop end


/*
	//restore settings
	CH1_DAC_Offset = CH1_DAC_Offset_bak;
	CH2_DAC_Offset = CH2_DAC_Offset_bak;
	CH3_DAC_Offset = CH3_DAC_Offset_bak;
	CH4_DAC_Offset = CH4_DAC_Offset_bak;

	//restore zerolevels
	ZeroLevelCH1 = ZeroLevelCH1_bak;
	ZeroLevelCH2 = ZeroLevelCH2_bak;
	ZeroLevelCH3 = ZeroLevelCH3_bak;
	ZeroLevelCH4 = ZeroLevelCH4_bak;

	Virtual_ZeroLevelCH1 = Virtual_ZeroLevelCH1_bak;
	Virtual_ZeroLevelCH2 = Virtual_ZeroLevelCH2_bak;
	Virtual_ZeroLevelCH3 = Virtual_ZeroLevelCH3_bak;
	Virtual_ZeroLevelCH4 = Virtual_ZeroLevelCH4_bak;
*/

/*
	Channel_1_Active = Channel_1_Active_bak;
	Channel_2_Active = Channel_2_Active_bak;
*/	

/*
	//activate new settings
	Rotary_Steps = 0;
	ON_Zero_Channel_1();
	Rotary_Steps = 0;
	ON_Zero_Channel_2();

	if (NumberOfChannels > 2)
	{	
		//Channel_3_Active = Channel_3_Active_bak;
		//Channel_4_Active = Channel_4_Active_bak;
	
		//activate new settings
		Rotary_Steps = 0;
		ON_Zero_Channel_3();
		Rotary_Steps = 0;
		ON_Zero_Channel_4();
	}
*/

	//restore timebase settings
	timebase_reg = tb_value[Selected_Timebase];
    
	if (Selected_Timebase > 7)
	{ adc_change12_reg |= 0x01000000; }
	else
	{ adc_change12_reg &= 0xFEFFFFFF; }

	SetupADC();	

	Start_Record();

	//Save new values to flash
	config_changed = true;
	

	//Delete popup
	Display::DRAWROUNDBUTTON(230, 180, 200, 80, 0, 1);
	Display::TEXTOUTxvbig("Calibrating DAC Offsets.", 247, 192, 0, UI_Plane2);
	Display::TEXTOUTxvbig("of active channels.", 247, 212, 0, UI_Plane2);
	Display::TEXTOUTxvbig("Remove all inputs.", 247, 232, 0, UI_Plane2);


}

//##########################################################################################################################################################
//BF added -> coding transferred from Handle_ADC()

void Hardware::Transfer_USB_Data(void)
{
	long ix, ix2, ix3, enddata = 0;
	int chk_calc = 0;
	
	volatile long buffer_addr = 0;	
	volatile long buffer_peak = 0;	
	volatile long buffer_written = 0;	
	
	int channel_trig = 0;

//BF test UI Interupt!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	if (UI_request) return;	
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


	//-----------------------------------------------------------------------------------
	//       			 USB transfer
	//-----------------------------------------------------------------------------------

	// Submit Data to USB Client
	if (USB_Data_Requested) enddata = 511;
	else enddata = 75;

	if (USB_Data_Trans)
	{
		if (USB_SendAllData) enddata = 511;
		else enddata = 75;
		
		USB_Data_Requested = true;
	}
		
	if ((USB_Data_Requested) && (Transfer_man_data))
	{
        //printf("ba : %x bp : %x bw : %x\n", buffer_addr, buffer_peak, buffer_written);		
		
		

		
	
		if ((Channel_1_Active == 1) && (USB_OnlyTrigger == false))
		{

			send_buffer[0] = 101;								// Kennung Data
			//send_buffer[1] = 1;								// Kennung Channel
			
			
			for (ix2 = 0; ix2 <= enddata; ix2++)
			{
                		ix3 = ix2 * 32;

				send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
				send_buffer[2] = (unsigned char) (ix3 & 0x00FF);		// Address Low
			
                		chk_calc = 0;
                
				for (ix = 0; ix < 32; ix++)
				{	
					chk_calc += SIGNAL1[(ix2 * 32) + ix];
					send_buffer[3 + ix] = SIGNAL1[(ix2 * 32) + ix];
				}
                
				send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
				send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
                							
				SendData(send_buffer);
				
				//printf("DS %3d %3d %3d\n", send_buffer[2], send_buffer[3], send_buffer[4]);
				nr_delay(10);
			}	
		}
		
		if ((Channel_2_Active == 1) && (USB_OnlyTrigger == false))
		{
			send_buffer[0] = 102;								// Kennung Data
			//send_buffer[1] = 2;									// Kennung Channel
			
			for (ix2 = 0; ix2 <= enddata; ix2++)
			{
                		ix3 = ix2 * 32;

				send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
				send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
				
				chk_calc = 0;
				
				for (ix = 0; ix < 32; ix++)
				{	
					chk_calc += SIGNAL2[(ix2 * 32) + ix];
					send_buffer[3 + ix] = SIGNAL2[(ix2 * 32) + ix];
				}

				send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
				send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
				
				SendData(send_buffer);
				nr_delay(10);
			}	
		}
		
		if (NumberOfChannels > 2)
		{
			if ((Channel_3_Active == 1) && (USB_OnlyTrigger == false))
			{
				send_buffer[0] = 103;								// Kennung Data
				//send_buffer[1] = 3;									// Kennung Channel
				
				for (ix2 = 0; ix2 <= enddata; ix2++)
				{
                    			ix3 = ix2 * 32;

					send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
					send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
				
				    	chk_calc = 0;
					for (ix = 0; ix < 32; ix++)
					{	
						chk_calc += SIGNAL3[(ix2 * 32) + ix];
						send_buffer[3 + ix] = SIGNAL3[(ix2 * 32) + ix];
				    	}	
				
					send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
					send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));				
					
					SendData(send_buffer);
					nr_delay(10);
                		}
			}
			
			if ((Channel_4_Active == 1) && (USB_OnlyTrigger == false))
			{		
				send_buffer[0] = 104;								// Kennung Data
				//send_buffer[1] = 4;									// Kennung Channel
				
				for (ix2 = 0; ix2 <= enddata; ix2++)
				{
                    			ix3 = ix2 * 32;

					send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
					send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
					
					chk_calc = 0;
					for (ix = 0; ix < 32; ix++)
					{	
						chk_calc += SIGNAL4[(ix2 * 32) + ix];
						send_buffer[3 + ix] = SIGNAL4[(ix2 * 32) + ix];
				    	}	
				
					send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
					send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
							
					SendData(send_buffer);
					nr_delay(10);
				}
			}		
			
	
		}

		
		if ((Channel_Math_Active == 1) && (USB_OnlyTrigger == false))
		{

			send_buffer[0] = 105;								// Kennung Data
			//send_buffer[1] = 1;									// Kennung Channel
			
			
			for (ix2 = 0; ix2 <= enddata; ix2++)
			{
                		ix3 = ix2 * 32;

				send_buffer[1] = (unsigned char) ((ix3 & 0xFF00) >> 8);		// Address Hight
				send_buffer[2] = (unsigned char) (ix3 & 0x00FF);			// Address Low
			
				chk_calc = 0;	
				for (ix = 0; ix < 32; ix++)
				{	
					chk_calc += SIGNALM[(ix2 * 32) + ix];
					send_buffer[3 + ix] = SIGNALM[(ix2 * 32) + ix];
				}	
				
				send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
				send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));
                							
				SendData(send_buffer);
				
				//printf("DS %3d %3d %3d\n", send_buffer[2], send_buffer[3], send_buffer[4]);
				nr_delay(10);
			}	
		}
		
		send_buffer[0] = 100;								// Kennung Data
//		send_buffer[1] = 0;									// Kennung Datablock

		send_buffer[2] = (unsigned char) (buffer_addr & 0x000000FF);
		send_buffer[3] = (unsigned char) ((buffer_addr & 0x0000FF00) >> 8);
		send_buffer[4] = (unsigned char) ((buffer_addr & 0x00FF0000) >> 16);
		send_buffer[5] = (unsigned char) ((buffer_addr & 0xFF000000) >> 24);

		send_buffer[6] = (unsigned char) (buffer_peak & 0x000000FF);
		send_buffer[7] = (unsigned char) ((buffer_peak & 0x0000FF00) >> 8);
		send_buffer[8] = (unsigned char) ((buffer_peak & 0x00FF0000) >> 16);
		send_buffer[9] = (unsigned char) ((buffer_peak & 0xFF000000) >> 24);

		send_buffer[10] = (unsigned char) (buffer_written & 0x000000FF);
		send_buffer[11] = (unsigned char) ((buffer_written & 0x0000FF00) >> 8);
		send_buffer[12] = (unsigned char) ((buffer_written & 0x00FF0000) >> 16);
		send_buffer[13] = (unsigned char) ((buffer_written & 0xFF000000) >> 24);
		send_buffer[14] = (unsigned char) Selected_Timebase;
		send_buffer[15] = (unsigned char) SIGNALFaktor_idx;
		
		chk_calc = 0;	
		for (ix = 0; ix < 32; ix++)
		{	
			chk_calc += send_buffer[3 + ix];
		}	
					
		send_buffer[37] = (unsigned char)(0xFF - (chk_calc & 0x00FF));
		send_buffer[38] = (unsigned char)(0xFF - ((chk_calc & 0xFF00) >> 8));		
		
		SendData(send_buffer);
		nr_delay(10);		
        		
		if (USB_OnlyTrigger == false)
		{
			SendCtrlBlock();
			nr_delay(50);			
			SendCtrlBlock3();		
			nr_delay(50);	
			SendCtrlBlock2();		
			nr_delay(50);
	        }

        //if (MenuStatus[MENU_QUICKPRINT][2] == 144) MenuStatus[MENU_QUICKPRINT][2] = 143;	
        //Menu_Changed = 1;		

//		reset_watchdog->np_piodata = 0x01;							// Enable WatchDog
		
		USB_Data_Requested = false;
	}

}
//##########################################################################################################################################################

void Hardware::FFT_Set_Channel(unsigned char backup)
{
	if (backup)
	{
		//Backup channel status
		Channel_1_Active_Old = Channel_1_Active;
		Channel_2_Active_Old = Channel_2_Active;
		//if(NumberOfChannels == 4)
		//{
			Channel_3_Active_Old = Channel_3_Active;	
			Channel_4_Active_Old = Channel_4_Active;
		/*}
		else
		{
			Channel_3_Active_Old = Channel_3_Active = 0;	
			Channel_4_Active_Old = Channel_4_Active = 0;
		}*/
	}

	// which channel has to be active?
	switch(MenuStatus[MENU_FFT][0])	//FFT source
	{
		case 138: Channel_1_Active = 1;	Channel_2_Active = 0; Channel_3_Active = 0; Channel_4_Active = 0;
				Set_LED(0); Reset_LED(1); Reset_LED(2); Reset_LED(3); break;	
		case 139: Channel_1_Active = 0;	Channel_2_Active = 1; Channel_3_Active = 0; Channel_4_Active = 0;
				Reset_LED(0); Set_LED(1); Reset_LED(2); Reset_LED(3); break;	
		case 140: Channel_1_Active = 0;	Channel_2_Active = 0; Channel_3_Active = 1; Channel_4_Active = 0;
				Reset_LED(0); Reset_LED(1); Set_LED(2); Reset_LED(3); break;	
		case 141: Channel_1_Active = 0;	Channel_2_Active = 0; Channel_3_Active = 0; Channel_4_Active = 1;
				Reset_LED(0); Reset_LED(1); Reset_LED(2); Set_LED(3); break;	
	}
	//config_changed = 1;
	nr_delay(5);
	Send_LED();
	nr_delay(1);

	// force new output in statusbar
	VoltageChangedCh1 = 1;
	VoltageChangedCh2 = 1;
	VoltageChangedCh3 = 1;
	VoltageChangedCh4 = 1;

}
//##########################################################################################################################################################

void Hardware::FFT_Restore_Channels(void)
{
	//restore channel setting
	Channel_1_Active = Channel_1_Active_Old;
	Channel_2_Active = Channel_2_Active_Old;
	//if(NumberOfChannels == 4)
	//{
		Channel_3_Active = Channel_3_Active_Old;	
		Channel_4_Active = Channel_4_Active_Old;
	/*}
	else
	{
		Channel_3_Active_Old = Channel_3_Active = 0;	
		Channel_4_Active_Old = Channel_4_Active = 0;
	}*/


	// set LEDs
	if (Channel_1_Active) Set_LED(0);
	else Reset_LED(0);

	// set LEDs
	if (Channel_2_Active) Set_LED(1);
	else Reset_LED(1);

	// set LEDs
	if (Channel_3_Active) Set_LED(2);
	else Reset_LED(2);

	// set LEDs
	if (Channel_4_Active) Set_LED(3);
	else Reset_LED(3);

	nr_delay(5);
	Send_LED();
	nr_delay(1);

	// force new output in statusbar
	VoltageChangedCh1 = 1;
	VoltageChangedCh2 = 1;
	VoltageChangedCh3 = 1;
	VoltageChangedCh4 = 1;
}


