Index: trunk/MultiChannelUSB/Paella.dpf
===================================================================
--- trunk/MultiChannelUSB/Paella.dpf	(revision 104)
+++ trunk/MultiChannelUSB/Paella.dpf	(revision 159)
@@ -3,21 +3,21 @@
 <pin_planner>
 	<pin_info>
+		<pin name="ADC_D[2]" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_D[2](n)" >
+		</pin>
+		<pin name="ADC_D[1]" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_D[1](n)" >
+		</pin>
+		<pin name="ADC_D[0]" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_D[0](n)" >
+		</pin>
 		<pin name="ADC_DCO" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_DCO(n)" >
+		</pin>
+		<pin name="ADC_FCO" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_FCO(n)" >
 		</pin>
 		<pin name="ADC_DCO(n)" direction="Input" source="Assignments" diff_pair_node="ADC_DCO" >
 		</pin>
-		<pin name="ADC_FCO" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_FCO(n)" >
-		</pin>
 		<pin name="ADC_FCO(n)" direction="Input" source="Assignments" diff_pair_node="ADC_FCO" >
-		</pin>
-		<pin name="ADC_D[0]" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_D[0](n)" >
 		</pin>
 		<pin name="ADC_D[0](n)" direction="Input" source="Assignments" diff_pair_node="ADC_D[0]" >
 		</pin>
-		<pin name="ADC_D[1]" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_D[1](n)" >
-		</pin>
 		<pin name="ADC_D[1](n)" direction="Input" source="Assignments" diff_pair_node="ADC_D[1]" >
-		</pin>
-		<pin name="ADC_D[2]" direction="Input" source="Hierarchy Database" diff_pair_node="ADC_D[2](n)" >
 		</pin>
 		<pin name="ADC_D[2](n)" direction="Input" source="Assignments" diff_pair_node="ADC_D[2]" >
Index: trunk/MultiChannelUSB/Paella.qsf
===================================================================
--- trunk/MultiChannelUSB/Paella.qsf	(revision 104)
+++ trunk/MultiChannelUSB/Paella.qsf	(revision 159)
@@ -42,5 +42,5 @@
 set_global_assignment -name ORIGINAL_QUARTUS_VERSION 9.0
 set_global_assignment -name PROJECT_CREATION_TIME_DATE "14:14:14  AUGUST 28, 2009"
-set_global_assignment -name LAST_QUARTUS_VERSION 9.0
+set_global_assignment -name LAST_QUARTUS_VERSION "9.1 SP2"
 set_global_assignment -name DEVICE_FILTER_PACKAGE "ANY QFP"
 set_global_assignment -name DEVICE_FILTER_PIN_COUNT 240
@@ -49,25 +49,6 @@
 set_global_assignment -name AUTO_SHIFT_REGISTER_RECOGNITION OFF
 set_global_assignment -name MISC_FILE Paella.dpf
-set_global_assignment -name VERILOG_FILE Paella.v
-set_global_assignment -name VERILOG_FILE adc_fifo.v
-set_global_assignment -name VERILOG_FILE adc_lvds.v
-set_global_assignment -name VERILOG_FILE adc_para.v
-set_global_assignment -name VERILOG_FILE adc_pll.v
-set_global_assignment -name VERILOG_FILE control.v
-set_global_assignment -name VERILOG_FILE analyser.v
-set_global_assignment -name VERILOG_FILE counter.v
-set_global_assignment -name VERILOG_FILE histogram.v
-set_global_assignment -name VERILOG_FILE trigger.v
-set_global_assignment -name VERILOG_FILE oscilloscope.v
-set_global_assignment -name VERILOG_FILE configuration.v
-set_global_assignment -name VERILOG_FILE usb_fifo.v
-set_global_assignment -name VERILOG_FILE i2c_fifo.v
-set_global_assignment -name VERILOG_FILE uwt_bior31.v
-set_global_assignment -name VERILOG_FILE test.v
-set_global_assignment -name VERILOG_FILE test_pll.v
-set_global_assignment -name VERILOG_FILE sys_pll.v
 set_global_assignment -name USE_TIMEQUEST_TIMING_ANALYZER OFF
 set_global_assignment -name ENABLE_CLOCK_LATENCY ON
-set_instance_assignment -name PARTITION_HIERARCHY root_partition -to | -section_id Top
 set_global_assignment -name PARTITION_NETLIST_TYPE SOURCE -section_id Top
 set_global_assignment -name PARTITION_COLOR 16764057 -section_id Top
@@ -92,5 +73,4 @@
 set_global_assignment -name IOBANK_VCCIO 3.3V -section_id 8
 set_location_assignment PIN_21 -to LED
-set_location_assignment PIN_33 -to CLK_50MHz
 set_location_assignment PIN_37 -to USB_PA7
 set_location_assignment PIN_38 -to USB_PA6
@@ -157,6 +137,7 @@
 set_location_assignment PIN_146 -to CON_B[14]
 set_location_assignment PIN_147 -to CON_B[15]
-set_location_assignment PIN_149 -to CON_BCLK[0]
-set_location_assignment PIN_150 -to CON_BCLK[1]
+set_location_assignment PIN_148 -to CON_B[16]
+set_location_assignment PIN_149 -to CON_BCLK
+set_location_assignment PIN_150 -to CLK_50MHz
 set_location_assignment PIN_151 -to CON_CCLK[0]
 set_location_assignment PIN_152 -to CON_CCLK[1]
@@ -266,6 +247,5 @@
 set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_B[14]
 set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_B[15]
-set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_BCLK[0]
-set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_BCLK[1]
+set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_BCLK
 set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_C[0]
 set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CON_C[1]
@@ -324,2 +304,24 @@
 set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to RAM_DQB[6]
 set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to RAM_DQB[7]
+
+set_global_assignment -name VERILOG_FILE clip.v
+set_global_assignment -name VERILOG_FILE shift.v
+set_global_assignment -name VERILOG_FILE Paella.v
+set_global_assignment -name VERILOG_FILE adc_lvds.v
+set_global_assignment -name VERILOG_FILE sys_pll.v
+set_global_assignment -name VERILOG_FILE control.v
+set_global_assignment -name VERILOG_FILE filter.v
+set_global_assignment -name VERILOG_FILE amplitude.v
+set_global_assignment -name VERILOG_FILE delay.v
+set_global_assignment -name VERILOG_FILE coincidence.v
+set_global_assignment -name VERILOG_FILE counter.v
+set_global_assignment -name VERILOG_FILE histogram16.v
+set_global_assignment -name VERILOG_FILE histogram32.v
+set_global_assignment -name VERILOG_FILE trigger.v
+set_global_assignment -name VERILOG_FILE oscilloscope.v
+set_global_assignment -name VERILOG_FILE configuration.v
+set_global_assignment -name VERILOG_FILE usb_fifo.v
+set_global_assignment -name VERILOG_FILE i2c_fifo.v
+set_global_assignment -name VERILOG_FILE test.v
+
+set_instance_assignment -name PARTITION_HIERARCHY root_partition -to | -section_id Top
Index: trunk/MultiChannelUSB/Paella.v
===================================================================
--- trunk/MultiChannelUSB/Paella.v	(revision 104)
+++ trunk/MultiChannelUSB/Paella.v	(revision 159)
@@ -8,7 +8,7 @@
 		inout	wire			I2C_SCL,
 		inout	wire	[4:0]	CON_A,
-		input	wire	[15:0]	CON_B,
+		input	wire	[16:0]	CON_B,
 		input	wire	[12:0]	CON_C,
-		input	wire	[1:0]	CON_BCLK,
+		input	wire			CON_BCLK,
 		input	wire	[1:0]	CON_CCLK,
 
@@ -68,6 +68,5 @@
 
 	assign	USB_PA2		=	~usb_rden;
-	assign	USB_PA4		=	usb_addr[0];
-	assign	USB_PA5		=	usb_addr[1];
+	assign	USB_PA5		=	1'b1;
 	assign	USB_PA6		=	~usb_pktend;
 
@@ -76,5 +75,4 @@
 	wire			usb_tx_full, usb_rx_empty;
 	wire	[7:0]	usb_tx_data, usb_rx_data;
-	wire	[1:0]	usb_addr;
 
 	assign	USB_SLRD = ~usb_rdreq;
@@ -83,5 +81,5 @@
 	usb_fifo usb_unit
 	(
-		.usb_clk(USB_IFCLK),
+		.usb_clock(USB_IFCLK),
 		.usb_data(USB_PB),
 		.usb_full(~USB_FLAGB),
@@ -91,7 +89,7 @@
 		.usb_rden(usb_rden),
 		.usb_pktend(usb_pktend),
-		.usb_addr(usb_addr),
-
-		.clk(sys_clock),
+		.usb_addr(USB_PA4),
+
+		.clock(sys_clock),
 
 		.tx_full(usb_tx_full),
@@ -103,59 +101,42 @@
 		.rx_q(usb_rx_data)
 	);
-		
-	wire			ana_dead [N-1:0];
-	wire			ana_good [N-1:0];
-	wire	[11:0]	ana_data [N-1:0];
-	wire	[11:0]	ana_base [N-1:0];
-
-	wire			cnt_good [N-1:0];
-
-	wire	[11:0]	osc_mux_data [N-1:0];
+/*
+	reg		[31:0]	led_counter;
+	always @(posedge CLK_50MHz)
+	begin
+		led_counter = led_counter + 32'd1;
+	end
+	assign LED = led_counter[28];
+*/	
+	wire	[11:0]	osc_mux_data [4:0];
 
 	wire	[11:0]	trg_mux_data;
 	wire			trg_flag;
 
-	wire	[83:0]	int_mux_data [N-1:0];
+	wire	[4*12-1:0]	int_mux_data [N-1:0];
+
+	wire	[1:0]	amp_flag [2*N-1:0];
+	wire	[11:0]	amp_data [2*N-1:0];
+
+	wire			cnt_good [N-1:0];
+	wire	[15:0]	cnt_bits_wire;
 
 	wire			sys_clock, sys_frame;
 
-	wire 	[11:0]	adc_data [N-1:0];
-    wire	[11:0]	int_data [N-1:0];
+    wire	[11:0]	adc_data [N-1:0];
     wire	[11:0]	sys_data [N-1:0];
-    wire	[11:0]	cmp_data;
-	wire	[11:0]	nowhere;
-
-	wire 	[31:0]	uwt_d1 [N-1:0];
-	wire 	[31:0]	uwt_a1 [N-1:0];
-	wire 	[31:0]	uwt_peak1 [N-1:0];
-	wire 	[31:0]	uwt_d2 [N-1:0];
-	wire 	[31:0]	uwt_a2 [N-1:0];
-	wire 	[31:0]	uwt_peak2 [N-1:0];
-	wire 	[31:0]	uwt_d3 [N-1:0];
-	wire 	[31:0]	uwt_a3 [N-1:0];
-	wire 	[31:0]	uwt_peak3 [N-1:0];
-
-	wire 	[1:0]	uwt_flag1 [N-1:0];
-	wire 	[1:0]	uwt_flag2 [N-1:0];
-	wire 	[1:0]	uwt_flag3 [N-1:0];
-	
+	wire	[11:0]	tst_data;
+
+    wire	[1:0]	cmp_data;
+    wire	[1:0]	del_data;
+
+	wire	[19:0]	cic_data [N-1:0];
+
+	wire	[11:0]	dec_data [N-1:0];
+	wire	[11:0]	clp_data [N-1:0];
+	wire	[11:0]	tmp_data;
+
+
 	wire			i2c_reset;
-
-/*
-	adc_para adc_para_unit (
-		.lvds_dco(ADC_DCO),
-		.lvds_fco(ADC_FCO),
-		.para_good(CON_CCLK[0]),
- 		.para_data(CON_C[11:0]),
-		.adc_data(adc_data[2]));
-*/
- 
-	wire			adc_pll_clk;
-
-/*
-	adc_pll adc_pll_unit(
-		.inclk0(ADC_FCO),
-		.c0(adc_pll_clk));
-*/
 
 	sys_pll sys_pll_unit(
@@ -165,48 +146,40 @@
 	test test_unit(
 		.clk(ADC_FCO),
-		.data(adc_data[2]));
-//		.data(nowhere));
+		.data(tst_data));
 
 	adc_lvds #(
 		.size(3),
 		.width(12)) adc_lvds_unit (
+		.clock(sys_clock),
 		.lvds_dco(ADC_DCO),
-//		.lvds_dco(adc_pll_clk),
 		.lvds_fco(ADC_FCO),
-		.lvds_d(ADC_D[2:0]),
-//		.adc_data({	adc_data[2],
-		.adc_data({	nowhere,
-					adc_data[1],
-					adc_data[0] }));
-
-/*					
-	assign			cmp_data = CON_B[11:0];
-	assign			sys_clock = ADC_DCO;
-	assign			sys_frame = ADC_FCO;
-*/
-
-	wire	[15:0]	cfg_bits [31:0];
-	wire	[511:0]	int_cfg_bits;
-
-	wire	[31:0]	cfg_mux_selector;
+		.lvds_d(ADC_D),
+		.trig(TRG[1:0]),
+		.adc_frame(sys_frame),
+		.adc_data({cmp_data, adc_data[2], adc_data[1], adc_data[0]}));
+
+	wire	[15:0]		cfg_bits [63:0];
+	wire	[1023:0]	int_cfg_bits;
+
+	wire	[39:0]	cfg_mux_selector;
 
 	wire 			cfg_reset;
 
-	wire 	[8:0]	bus_ssel;
+	wire 	[11:0]	bus_ssel;
 	wire			bus_wren;
 	wire	[31:0]	bus_addr;
 	wire	[15:0]	bus_mosi;
-	wire 	[15:0]	bus_miso [7:0];
-	wire 	[8:0]	bus_busy;
+	wire 	[15:0]	bus_miso [10:0];
+	wire 	[11:0]	bus_busy;
 
 	wire 	[15:0]	mrg_bus_miso;
 	wire 			mrg_bus_busy;
 
-	wire 	[127:0]	int_bus_miso;
+	wire 	[11*16-1:0]	int_bus_miso;
 
 	genvar j;
 
 	generate
-		for (j = 0; j < 32; j = j + 1)
+		for (j = 0; j < 64; j = j + 1)
 		begin : CONFIGURATION_OUTPUT
 			assign cfg_bits[j] = int_cfg_bits[j*16+15:j*16];
@@ -229,35 +202,32 @@
 		begin : MUX_DATA
 			assign int_mux_data[j] = {
-				{ana_good[j], 11'd0},
-				ana_data[j],
-				ana_base[j],
-				uwt_a3[j][20:9],
-				uwt_a2[j][17:6],
-				uwt_a1[j][14:3],
+				{4'd0, amp_flag[0+2*j][0], 7'd0},
+				amp_data[0+2*j],
+				clp_data[j],
 				sys_data[j]};
 		end
 	endgenerate
 
-	assign cfg_mux_selector = {cfg_bits[3], cfg_bits[2]};
+	assign cfg_mux_selector = {cfg_bits[4][7:0], cfg_bits[3], cfg_bits[2]};
 
 	lpm_mux #(
-		.lpm_size(21),
+		.lpm_size(4*3),
 		.lpm_type("LPM_MUX"),
 		.lpm_width(12),
-		.lpm_widths(5)) trg_mux_unit (
-		.sel(cfg_mux_selector[28:24]),
+		.lpm_widths(4)) trg_mux_unit (
+		.sel(cfg_bits[4][11:8]),
 		.data({int_mux_data[2], int_mux_data[1], int_mux_data[0]}),
 		.result(trg_mux_data));
 
 	generate
-		for (j = 0; j < 3; j = j + 1)
+		for (j = 0; j < 5; j = j + 1)
 		begin : OSC_CHAIN
 		
 			lpm_mux #(
-				.lpm_size(21),
+				.lpm_size(4*3),
 				.lpm_type("LPM_MUX"),
 				.lpm_width(12),
-				.lpm_widths(5)) osc_mux_unit (
-				.sel(cfg_mux_selector[j*8+4:j*8]),
+				.lpm_widths(4)) osc_mux_unit (
+				.sel(cfg_mux_selector[j*8+3:j*8]),
 				.data({int_mux_data[2], int_mux_data[1], int_mux_data[0]}),
 				.result(osc_mux_data[j]));
@@ -278,7 +248,7 @@
 		.frame(sys_frame),
 		.reset(cfg_bits[0][1]),
-		.cfg_data(cfg_bits[4][0]),
+		.cfg_data(cfg_bits[5][12]),
 		.trg_flag(trg_flag),
-		.osc_data({cmp_data, osc_mux_data[2], osc_mux_data[1], osc_mux_data[0]}),
+		.osc_data({2'd0, cmp_data, osc_mux_data[4], osc_mux_data[3], osc_mux_data[2], osc_mux_data[1], osc_mux_data[0]}),
 		.ram_wren(RAM_WE),
 		.ram_addr(RAM_ADDR),
@@ -291,89 +261,145 @@
 		.bus_busy(bus_busy[1]));
 
-
-	adc_fifo #(.W(48)) adc_fifo_unit (
-		.adc_clock(ADC_FCO),
-		.adc_data({CON_B[11:0], adc_data[2], adc_data[1], adc_data[0]}),
-		.sys_clock(sys_clock),
-		.sys_frame(sys_frame),
-		.sys_data({cmp_data, int_data[2], int_data[1], int_data[0]}));
-
-
+	filter #(.size(3), .width(12)) filter_unit (
+		.clock(sys_clock),
+		.frame(sys_frame),
+		.reset(1'b0),
+		.inp_data({sys_data[2], sys_data[1], sys_data[0]}),
+		.out_data({cic_data[2], cic_data[1], cic_data[0]}));
+		
+
+/*        
+	clip #(.shift(19), .width(19), .widthr(12)) clip_unit (
+		.clock(sys_clock),
+		.frame(sys_frame),
+		.reset(1'b0),
+		.del_data({cfg_bits[39][5:0], cfg_bits[37][5:0], cfg_bits[35+8][5:0], cfg_bits[33][5:0]}),
+		.amp_data({6'd6, 6'd6, 6'd6, 6'd6}),
+		.tau_data({cfg_bits[38], cfg_bits[36], cfg_bits[34], cfg_bits[32]}),
+		.inp_data({
+			19'd0, cic_data[2][18:0],
+			cic_data[1][18:0], cic_data[0][18:0]}),
+		.out_data({
+			tmp_data, clp_data[2], 
+			clp_data[1], clp_data[0]}));
+*/
 	generate
 		for (j = 0; j < 3; j = j + 1)
 		begin : MCA_CHAIN
-
-			assign sys_data[j] = (cfg_bits[1][4*j]) ? (int_data[j] ^ 12'hfff) : (int_data[j]);
-
-			uwt_bior31 #(.L(1)) uwt_1_unit (
+			
+			shift #(.shift(9), .width(19), .widthr(12)) shift_unit (
 				.clock(sys_clock),
 				.frame(sys_frame),
 				.reset(1'b0),
-				.x({20'h00000, sys_data[j]}),
-				.d(uwt_d1[j]),
-				.a(uwt_a1[j]),
-				.peak(uwt_peak1[j]),
-				.flag(uwt_flag1[j]));
-		
-			uwt_bior31 #(.L(2)) uwt_2_unit (
+				.amp_data(6'd5),
+				.inp_data(cic_data[j][18:0]),
+				.out_data(clp_data[j]));
+				
+			assign sys_data[j] = (cfg_bits[1][4*j]) ? (adc_data[j] ^ 12'hfff) : (adc_data[j]);
+
+			amplitude #(.width(12)) amplitude_unit_1 (
 				.clock(sys_clock),
 				.frame(sys_frame),
 				.reset(1'b0),
-				.x(uwt_a1[j]),
-				.d(uwt_d2[j]),
-				.a(uwt_a2[j]),
-				.peak(uwt_peak2[j]),
-				.flag(uwt_flag2[j]));
-		
-			uwt_bior31 #(.L(3)) uwt_3_unit (
+				.cfg_data(cfg_bits[6+2*j][11:0]),
+				.inp_data(clp_data[j]),
+				.out_flag(amp_flag[0+2*j]),
+				.out_data(amp_data[0+2*j]));
+
+			amplitude #(.width(12)) amplitude_unit_2 (
 				.clock(sys_clock),
 				.frame(sys_frame),
 				.reset(1'b0),
-				.x(uwt_a2[j]),
-				.d(uwt_d3[j]),
-				.a(uwt_a3[j]),
-				.peak(uwt_peak3[j]),
-				.flag(uwt_flag3[j]));
-	
-			analyser analyser_unit (
-				.clock(sys_clock),
-				.frame(sys_frame),
-				.reset(cfg_bits[0][2+j]),
-				.cfg_data({cfg_bits[7+2*j][12:0], cfg_bits[6+2*j][11:0]}),
-				.uwt_flag(uwt_flag3[j]),
-				.uwt_data(uwt_peak3[j]),
-				.ana_dead(ana_dead[j]),
-				.ana_good(ana_good[j]),
-				.ana_data(ana_data[j]),
-				.ana_base(ana_base[j]));
-
-			histogram histogram_unit (
-				.clock(sys_clock),
-				.frame(sys_frame),
-				.reset(cfg_bits[0][5+j]),
-				.hst_good((ana_good[j]) & (cnt_good[j])),
-				.hst_data(ana_data[j]),
-				.bus_ssel(bus_ssel[2+j]),
-				.bus_wren(bus_wren),
-				.bus_addr(bus_addr[12:0]),
-				.bus_mosi(bus_mosi),
-				.bus_miso(bus_miso[2+j]),
-				.bus_busy(bus_busy[2+j]));
-
-			counter counter_unit (
-				.clock(sys_clock),
-				.frame((sys_frame) & (~ana_dead[j])),
-				.reset(cfg_bits[0][8+j]),
-				.cfg_data(cfg_bits[12+j]),
-				.bus_ssel(bus_ssel[5+j]),
-				.bus_wren(bus_wren),
-				.bus_addr(bus_addr[1:0]),
-				.bus_mosi(bus_mosi),
-				.bus_miso(bus_miso[5+j]),
-				.bus_busy(bus_busy[5+j]),
-				.cnt_good(cnt_good[j]));
+				.cfg_data(cfg_bits[7+2*j][11:0]),
+				.inp_data(clp_data[j]),
+				.out_flag(amp_flag[1+2*j]),
+				.out_data(amp_data[1+2*j]));
 
 		end
 	endgenerate
+
+	histogram32 histogram32_unit (
+		.clock(sys_clock),
+		.frame(sys_frame),
+		.reset(cfg_bits[0][5]),
+		.hst_good((amp_flag[0][0]) & (cnt_good[0]) & (cfg_bits[13][1])),
+		.hst_data(amp_data[0]),
+/*
+		.hst_good((amp_flag[j]) & (cnt_good[j]) & (cfg_bits[13][1])),
+		.hst_data(amp_data[j]),
+*/
+		.bus_ssel(bus_ssel[2]),
+		.bus_wren(bus_wren),
+		.bus_addr(bus_addr[12:0]),
+		.bus_mosi(bus_mosi),
+		.bus_miso(bus_miso[2]),
+		.bus_busy(bus_busy[2]));
+
+	counter hst_counter_unit (
+		.clock(sys_clock),
+		.frame((sys_frame) & (~amp_flag[0][1])),
+//		.frame(sys_frame),
+		.reset(cfg_bits[0][8]),
+		.setup(cfg_bits[13][0]),
+		.count(cfg_bits[13][1]),
+		.bus_ssel(bus_ssel[5]),
+		.bus_wren(bus_wren),
+		.bus_addr(bus_addr[1:0]),
+		.bus_mosi(bus_mosi),
+		.bus_miso(bus_miso[5]),
+		.bus_busy(bus_busy[5]),
+		.cnt_good(cnt_good[0]));
+
+	histogram16 histogram16_unit (
+		.clock(sys_clock),
+		.frame(sys_frame),
+		.reset(cfg_bits[0][11]),
+		.hst_good((cnt_good[2]) & (~cnt_good[1])),
+		.hst_data(cnt_bits_wire),
+		.bus_ssel(bus_ssel[8]),
+		.bus_wren(bus_wren),
+		.bus_addr(bus_addr[13:0]),
+		.bus_mosi(bus_mosi),
+		.bus_miso(bus_miso[8]),
+		.bus_busy(bus_busy[8]));
+
+	counter rmt_counter_1 (
+		.clock(sys_clock),
+		.frame((sys_frame) & (~amp_flag[1][1])),
+//		.frame(sys_frame),
+		.reset(cfg_bits[0][12]),
+		.setup((sys_frame) & (~cnt_good[1])),
+		.count((cnt_good[2]) & (cfg_bits[16][1])),
+		.bus_ssel(bus_ssel[9]),
+		.bus_wren(bus_wren),
+		.bus_addr(bus_addr[1:0]),
+		.bus_mosi(bus_mosi),
+		.bus_miso(bus_miso[9]),
+		.bus_busy(bus_busy[9]),
+		.cnt_good(cnt_good[1]));
+
+	counter rmt_counter_2 (
+		.clock(sys_clock),
+		.frame((sys_frame) & (~cnt_good[1])),
+		.reset(cfg_bits[0][13]),
+		.setup(cfg_bits[16][0]),
+		.count(cfg_bits[16][1]),
+		.bus_ssel(bus_ssel[10]),
+		.bus_wren(bus_wren),
+		.bus_addr(bus_addr[1:0]),
+		.bus_mosi(bus_mosi),
+		.bus_miso(bus_miso[10]),
+		.bus_busy(bus_busy[10]),
+		.cnt_good(cnt_good[2]));
+
+	lpm_counter	#(
+		.lpm_direction("UP"),
+		.lpm_port_updown("PORT_UNUSED"),
+		.lpm_type("LPM_COUNTER"),
+		.lpm_width(16)) lpm_counter_component (
+		.sclr(((sys_frame) & (cnt_good[2]) & (~cnt_good[1])) | (cfg_bits[0][11])),
+		.clock(sys_clock),
+		.cnt_en((sys_frame) & (amp_flag[1][0]) & (cnt_good[1]) & (cnt_good[2]) & (cfg_bits[16][1])),
+		.q(cnt_bits_wire));
 
 	i2c_fifo i2c_unit(
@@ -390,11 +416,11 @@
 		.i2c_scl(I2C_SDA),
 		
-		.bus_ssel(bus_ssel[8]),
-		.bus_wren(bus_wren),
-		.bus_mosi(bus_mosi),
-		.bus_busy(bus_busy[8]));
+		.bus_ssel(bus_ssel[11]),
+		.bus_wren(bus_wren),
+		.bus_mosi(bus_mosi),
+		.bus_busy(bus_busy[11]));
 
 	generate
-		for (j = 0; j < 8; j = j + 1)
+		for (j = 0; j < 11; j = j + 1)
 		begin : BUS_OUTPUT
 			assign int_bus_miso[j*16+15:j*16] = bus_miso[j];
@@ -403,14 +429,14 @@
 
 	lpm_mux #(
-		.lpm_size(8),
+		.lpm_size(11),
 		.lpm_type("LPM_MUX"),
 		.lpm_width(16),
-		.lpm_widths(3)) bus_miso_mux_unit (
-		.sel(bus_addr[30:28]),
+		.lpm_widths(4)) bus_miso_mux_unit (
+		.sel(bus_addr[31:28]),
 		.data(int_bus_miso),
 		.result(mrg_bus_miso));
 
 	lpm_mux #(
-		.lpm_size(9),
+		.lpm_size(12),
 		.lpm_type("LPM_MUX"),
 		.lpm_width(1),
@@ -420,23 +446,11 @@
 		.result(mrg_bus_busy));
 
-/*
-	lpm_or #(
-		.lpm_size(6),
-		.lpm_type("LPM_OR"),
-		.lpm_width(16)) bus_miso_or_unit (
-		.data(int_bus_miso),
-		.result(mrg_bus_miso));
-*/
-
 	lpm_decode #(
-		.lpm_decodes(9),
+		.lpm_decodes(12),
 		.lpm_type("LPM_DECODE"),
 		.lpm_width(4)) lpm_decode_unit (
 		.data(bus_addr[31:28]),
-		.eq(bus_ssel),
-		.aclr(),
-		.clken(),
-		.clock(),
-		.enable());
+		.eq(bus_ssel));
+
 
 	control control_unit (
Index: trunk/MultiChannelUSB/UserInterface.tcl
===================================================================
--- trunk/MultiChannelUSB/UserInterface.tcl	(revision 104)
+++ trunk/MultiChannelUSB/UserInterface.tcl	(revision 159)
@@ -16,10 +16,45 @@
     namespace import ::blt::tabnotebook
 
-    proc validate {max value} {
+# -------------------------------------------------------------------------
+
+    variable oscCodes
+    array set oscCodes {
+        1 {Channel 1}
+        2 {Channel 2}
+        3 {Channel 3}
+        4 {Channel 4}
+        5 {Channel 5}
+        6 {Trigger}
+    }
+
+# -------------------------------------------------------------------------
+
+    variable adcCodes
+    array set adcCodes {
+        1 {ADC 1}
+        2 {ADC 2}
+        3 {ADC 3}
+    }
+
+# -------------------------------------------------------------------------
+
+    variable inpCodes
+    array set inpCodes {
+        0 {raw data}
+        1 {filtered}
+        2 {amplitude}
+        3 {amp flag}
+    }
+
+# -------------------------------------------------------------------------
+
+    proc validate {max size value} {
         if {![regexp {^[0-9]*$} $value]} {
+            return 0
+        } elseif {[regexp {^0[0-9]+$} $value]} {
             return 0
         } elseif {$value > $max} {
             return 0
-        } elseif {[string length $value] > 4} {
+        } elseif {[string length $value] > $size} {
             return 0
         } else {
@@ -30,62 +65,161 @@
 # -------------------------------------------------------------------------
 
-    Class Display
-
-# -------------------------------------------------------------------------
-
-    Display instproc usbCmd {command} {
-        global usb_handle
-
-        if {[catch {$usb_handle writeRaw [usb::convert $command]} result]} {
-            puts {Error during write}
-            puts $result
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    Display instproc usbCmdRead {command width size} {
-        global usb_handle
-
+    proc doublevalidate {max value} {
+        if {![regexp {^[0-9]{0,2}\.?[0-9]{0,3}$} $value]} {
+            return 0
+        } elseif {[regexp {^0[0-9]+$} $value]} {
+            return 0
+        } elseif {$value > $max} {
+            return 0
+        } else {
+            return 1
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    proc legendLabel {master row key title} {
+        label ${master}.${key}_label -anchor w -text ${title}
+        label ${master}.${key}_value -width 10 -anchor e -text {}
+
+        grid ${master}.${key}_label -row ${row} -column 1 -sticky w
+        grid ${master}.${key}_value -row ${row} -column 2 -sticky ew
+    }
+
+# -------------------------------------------------------------------------
+
+    proc legendButton {master row key title var bg {fg black}} {
+        checkbutton ${master}.${key}_check -variable $var
+        label ${master}.${key}_label -anchor w -text ${title} -bg ${bg} -fg $fg
+        label ${master}.${key}_value -width 10 -anchor e -text {} -bg ${bg} -fg $fg
+
+        grid ${master}.${key}_check -row ${row} -column 0 -sticky w
+        grid ${master}.${key}_label -row ${row} -column 1 -sticky w
+        grid ${master}.${key}_value -row ${row} -column 2 -sticky ew
+    }
+
+# -------------------------------------------------------------------------
+
+    Class UsbController
+
+# -------------------------------------------------------------------------
+
+    UsbController instproc usbConnect {} {
+        my instvar handle
+
+        puts usbConnect
+
+        if {[my exists handle]} {
+            $handle disconnect
+            unset handle
+        }
+if {1} {
+        while {[catch {usb::connect 0x09FB 0x6001 1 1 0} result]} {
+            set answer [tk_messageBox -icon error -type retrycancel \
+                -message {Cannot access USB device} -detail $result]
+#            puts $result
+            if {[string equal $answer cancel]} exit
+        }
+
+        set handle $result
+
+}
+    }
+
+# -------------------------------------------------------------------------
+
+    UsbController instproc usbHandle {} {
+        my instvar handle
+
+        if {[my exists handle]} {
+            return $handle
+        } else {
+            my usbConnect
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    UsbController instproc usbCmd {command} {
+        set code [catch {[my usbHandle] writeRaw [usb::convert $command]} result]
+        switch -- $code {
+            1 {
+#                puts $result
+                my usbConnect
+            }
+        }
+
+    }
+
+# -------------------------------------------------------------------------
+
+    UsbController instproc usbCmdReadRaw {command size data} {
         my usbCmd $command
 
-        set usb_data {}
-        if {[catch {$usb_handle readHex $width $size} result]} {
-            puts {Error during read}
-            puts $result
-            set result {}
-        }
-
-        my set data $result
-    }
-
-# -------------------------------------------------------------------------
-
-    Display instproc usbCmdReadEpt {command size} {
-        global usb_handle
-
+        set code [catch {[my usbHandle] readRaw $size} result]
+        switch -- $code {
+            0 {
+                set $data $result
+            }
+            1 {
+#                puts $result
+                my usbConnect
+            }
+            5 {
+#                puts Busy
+            }
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    UsbController instproc usbCmdReadRaw {command size data} {
         my usbCmd $command
 
-        set usb_data {}
-        if {[catch {$usb_handle readEpt $size} result]} {
-            puts {Error during read}
-            puts $result
-            set result {}
-        }
-
-        my set data $result
-    }
-
-# -------------------------------------------------------------------------
-
-    Class CfgDisplay -superclass Display -parameter {
+        set code [catch {[my usbHandle] readRaw $size} result]
+        switch -- $code {
+            0 {
+                set $data $result
+            }
+            1 {
+#                puts $result
+                my usbConnect
+            }
+            5 {
+#                puts Busy
+            }
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    UsbController instproc usbCmdReadHex {command width size data} {
+        my usbCmd $command
+
+        set code [catch {[my usbHandle] readHex $width $size} result]
+        switch -- $code {
+            0 {
+                set $data $result
+            }
+            1 {
+#                puts $result
+                my usbConnect
+            }
+            5 {
+#                puts Busy
+            }
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    Class MuxDisplay -parameter {
         {master}
-    }
-
-# -------------------------------------------------------------------------
-
-    CfgDisplay instproc init {} {
-
-        my reset
+        {controller}
+    }
+
+# -------------------------------------------------------------------------
+
+    MuxDisplay instproc init {} {
 
         my setup
@@ -96,5 +230,5 @@
 # -------------------------------------------------------------------------
 
-    CfgDisplay instproc destroy {} {
+    MuxDisplay instproc destroy {} {
         next
     }
@@ -102,111 +236,128 @@
 # -------------------------------------------------------------------------
 
-    CfgDisplay instproc reset {} {
-    }
-
-# -------------------------------------------------------------------------
-
-    CfgDisplay instproc start {} {
+    MuxDisplay instproc start {} {
+        my instvar config chan_val
+
+        set chan_val(1) 0
+        set chan_val(2) 0
+        set chan_val(3) 0
+        set chan_val(4) 0
+        set chan_val(5) 0
+        set chan_val(6) 0
+
+        trace add variable [myvar chan_val] write [myproc chan_val_update]
+        trace add variable [myvar polar] write [myproc polar_update]
+
+        $config(1).chan_1_1 select
+        $config(2).chan_1_2 select
+        $config(3).chan_1_3 select
+        $config(4).chan_1_1 select
+        $config(5).chan_3_1 select
+        $config(6).chan_3_1 select
+
+        for {set i 1} {$i <= 3} {incr i} {
+          $config(7).polar$i select
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    MuxDisplay instproc setup {} {
+        variable oscCodes
+        variable adcCodes
+        variable inpCodes
+        my instvar master
         my instvar config
 
-        trace add variable [myvar dac1] write [myproc dac1_update]
-        trace add variable [myvar dac2] write [myproc dac2_update]
-        trace add variable [myvar polar] write [myproc polar_update]
-
-        ${config(1)}.dac1 set 0
-        ${config(1)}.dac2 set 0
-
-        ${config(2)}.polar1 select
-        ${config(2)}.polar2 select
-        ${config(2)}.polar3 select
-    }
-
-# -------------------------------------------------------------------------
-
-    CfgDisplay instproc setup {} {
-        my instvar number master
-        my instvar config
-
-        set config(1) [labelframe ${master}.cfg1 -borderwidth 1 -relief sunken -text {DAC}]
-        set config(2) [labelframe ${master}.cfg2 -borderwidth 1 -relief sunken -text {polarity inversion}]
-
-        frame ${config(1)}.limits
-        label ${config(1)}.limits.min -text {0.0V}
-        label ${config(1)}.limits.max -text {-3.3V}
-
-        scale ${config(1)}.dac1 -orient vertical -from 0 -to 4095 -tickinterval 500 -variable [myvar dac1]
-        scale ${config(1)}.dac2 -orient vertical -from 0 -to 4095 -tickinterval 0 -variable [myvar dac2]
-
-        checkbutton ${config(2)}.polar1 -text {channel 1} -variable [myvar polar(1)]
-        checkbutton ${config(2)}.polar2 -text {channel 2} -variable [myvar polar(2)]
-        checkbutton ${config(2)}.polar3 -text {channel 3} -variable [myvar polar(3)]
-
-        grid ${config(1)} -sticky ns
-        grid ${config(2)} -sticky ew -pady 7
-
-        pack ${config(1)}.limits.min -anchor n -side top -pady 10
-        pack ${config(1)}.limits.max -anchor s -side bottom -pady 9
-
-        grid ${config(1)}.dac1 ${config(1)}.dac2 ${config(1)}.limits -sticky ns -pady 7
-
-        grid ${config(2)}.polar1
-        grid ${config(2)}.polar2
-        grid ${config(2)}.polar3
+        set size [array size inpCodes]
+        set oscList [array get oscCodes]
+        set adcList [array get adcCodes]
+        set inpList [array get inpCodes]
+
+        foreach {osc title} $oscList {
+            set config($osc) [labelframe ${master}.mux_$osc -borderwidth 1 -relief sunken -text $title]
+
+            foreach {ch dummy} $adcList {
+                label $config($osc).chan_${ch} -text "#$ch "
+                grid $config($osc).chan_${ch} -row 0 -column $ch -sticky w
+            }
+            foreach {code input} $inpList {
+                set row [expr {$code + 1}]
+                set last 0
+                foreach {ch dummy} $adcList {
+                    set value [expr {$size * ($ch - 1) + $code}]
+                    radiobutton $config($osc).chan_${code}_${ch} -variable [myvar chan_val($osc)] -value ${value}
+                    grid $config($osc).chan_${code}_${ch} -row ${row} -column $ch -sticky w
+                    set last $ch
+                }
+                $config($osc).chan_${code}_${last} configure -text $input
+            }
+            set column [expr {($osc - 1) % 3}]
+            set row [expr {($osc - 1) / 3 * 2 + 1}]
+            grid $config($osc) -row $row -column $column -sticky news -padx 10
+        }
+
+        set config(7) [labelframe ${master}.mux_8 -borderwidth 1 -relief sunken -text {polarity inversion}]
+        for {set i 1} {$i <= 3} {incr i} {
+          checkbutton $config(7).polar$i -text "ADC $i" -variable [myvar polar($i)]
+          grid ${config(7)}.polar$i
+        }
+        grid $config(7) -row 2 -column 3 -sticky news -padx 10
+
+        grid columnconfigure ${master} 0 -weight 1
+        grid columnconfigure ${master} 1 -weight 1
+        grid columnconfigure ${master} 2 -weight 1
+        grid columnconfigure ${master} 3 -weight 1
 
         grid rowconfigure ${master} 0 -weight 1
-        grid rowconfigure ${config(1)} 0 -weight 1
-        grid rowconfigure ${config(2)} 0 -weight 1
-    }
-
-# -------------------------------------------------------------------------
-
-    CfgDisplay instproc dac1_update args {
-        my instvar dac1
-
-        set value [format {%03x} $dac1]
-        set command 0005012000050030000500[string range $value 0 1]000502[string index $value 2]0
-
-        my usbCmd $command
-    }
-
-# -------------------------------------------------------------------------
-
-    CfgDisplay instproc dac2_update args {
-        my instvar dac2
-
-        set value [format {%03x} $dac2]
-        set command 0005012400050030000500[string range $value 0 1]000502[string index $value 2]0
-
-        my usbCmd $command
-    }
-
-# -------------------------------------------------------------------------
-
-    CfgDisplay instproc polar_update args {
-        my instvar polar
-
-        set value [format {0%x%x%x} $polar(3) $polar(2) $polar(1)]
-
-        my usbCmd 000A${value}
-    }
-
-# -------------------------------------------------------------------------
-
-    Class OscDisplay -superclass Display -parameter {
+        grid rowconfigure ${master} 1 -weight 0
+        grid rowconfigure ${master} 2 -weight 0
+        grid rowconfigure ${master} 3 -weight 0
+        grid rowconfigure ${master} 4 -weight 1
+
+    }
+
+
+# ------------------------------------------------------------------------
+
+    MuxDisplay instproc chan_val_update args {
+        my instvar controller chan_val
+
+        set byte1 [format {%02x%02x} $chan_val(2) $chan_val(1)]
+        set byte2 [format {%02x%02x} $chan_val(4) $chan_val(3)]
+        set byte3 [format {%02x%02x} $chan_val(6) $chan_val(5)]
+
+        $controller usbCmd 000200020004${byte1}000200030004${byte2}000200040004${byte3}
+    }
+
+# -------------------------------------------------------------------------
+
+    MuxDisplay instproc polar_update args {
+        my instvar controller polar
+
+        set value [format {%x%x%x} $polar(3) $polar(2) $polar(1)]
+
+        $controller usbCmd 0002000100040${value}
+    }
+
+# -------------------------------------------------------------------------
+
+    Class HstDisplay -parameter {
         {number}
         {master}
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc init {} {
-        my instvar data xvec yvec
-
-        set xvec [vector #auto]
-        set yvec [vector #auto]
-        # fill one vector for the x axis with 1025 points
-        $xvec seq 0 1024
-
-        my reset
+        {controller}
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc init {} {
+
+        my set data {}
+
+        vector create [myvar xvec](4096)
+        vector create [myvar yvec](4096)
+
+        # fill one vector for the x axis with 4096 points
+        [myvar xvec] seq -0.5 4095.5
 
         my setup
@@ -217,5 +368,5 @@
 # -------------------------------------------------------------------------
 
-    OscDisplay instproc destroy {} {
+    HstDisplay instproc destroy {} {
         next
     }
@@ -223,429 +374,101 @@
 # -------------------------------------------------------------------------
 
-    OscDisplay instproc reset {} {
-        my instvar data xvec yvec
-
-        set data {}
-
-        $yvec set {}
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc start {} {
-        my instvar config trig_mux disp_mux
-
-        set trig_mux 2
-        set disp_mux 2
+    HstDisplay instproc start {} {
+        my instvar config
 
         trace add variable [myvar data] write [myproc data_update]
-        trace add variable [myvar auto] write [myproc auto_update]
+        trace add variable [myvar cntr_val] write [myproc cntr_val_update]
+        trace add variable [myvar rate_val] write [myproc rate_val_update]
+
+        trace add variable [myvar axis] write [myproc axis_update]
         trace add variable [myvar thrs] write [myproc thrs_update]
-        trace add variable [myvar thrs_val] write [myproc thrs_val_update]
-        trace add variable [myvar disp_val] write [myproc disp_val_update]
-        trace add variable [myvar trig_val] write [myproc trig_val_update]
-
-        ${config}.auto_check select
+        trace add variable [myvar thrs_val] write [myproc thrs_update]
+
+        ${config}.axis_check select
+
         ${config}.thrs_check select
-        ${config}.thrs_field set 1278
-        ${config}.disp_uwt2 select
-        ${config}.trig_uwt2 select
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc setup {} {
+        ${config}.thrs_field set 25
+
+        set cntr_tmp 1200000000
+        my set cntr_val $cntr_tmp
+        my set cntr_bak $cntr_tmp
+        my set cntr_old $cntr_tmp
+        my set yvec_bak 0.0
+        my set yvec_old 0.0
+
+        my set rate_val(inst) 0.0
+        my set rate_val(mean) 0.0
+
+#        my cntr_reset
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc setup {} {
         my instvar number master
-        my instvar data xvec yvec
-        my instvar config auto thrs thrs_val disp_val trig_val
+        my instvar xvec yvec graph
+        my instvar config thrs thrs_val
+        my instvar cntr_h cntr_m cntr_s
 
         # create a graph widget and show a grid
         set graph [graph ${master}.graph -height 250 -leftmargin 80]
-        $graph crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
-        $graph grid configure -hide no
-        $graph legend configure -hide yes
-        $graph axis configure x -min 0 -max 1024
-        $graph axis configure y -min 0 -max 4100
-
-        set config [frame ${master}.config]
-
-        checkbutton ${config}.auto_check -text {auto update} -variable [myvar auto]
-
-        frame ${config}.spc1 -width 10 -height 10
-
-        checkbutton ${config}.thrs_check -text threshold -variable [myvar thrs]
-        spinbox ${config}.thrs_field -from 1 -to 4095 \
-            -increment 5 -width 10 -textvariable [myvar thrs_val] \
-            -validate all -vcmd {::mca::validate 4095 %P}
-
-        frame ${config}.spc2 -width 10 -height 10
-
-        label ${config}.disp -text {display input}
-        radiobutton ${config}.disp_data -text {raw data} -variable [myvar disp_val] -value data
-        radiobutton ${config}.disp_uwt1 -text {filter 1} -variable [myvar disp_val] -value uwt1
-        radiobutton ${config}.disp_uwt2 -text {filter 2} -variable [myvar disp_val] -value uwt2
-        radiobutton ${config}.disp_uwt3 -text {filter 3} -variable [myvar disp_val] -value uwt3
-        radiobutton ${config}.disp_base -text {baseline} -variable [myvar disp_val] -value base
-#        radiobutton ${config}.disp_sum8 -text {sum of 8} -variable [myvar disp_val] -value sum8
-
-        frame ${config}.spc3 -width 10 -height 10
-
-        label ${config}.trig -text {trigger input}
-        radiobutton ${config}.trig_data -text {raw data} -variable [myvar trig_val] -value data
-        radiobutton ${config}.trig_uwt1 -text {filter 1} -variable [myvar trig_val] -value uwt1
-        radiobutton ${config}.trig_uwt2 -text {filter 2} -variable [myvar trig_val] -value uwt2
-        radiobutton ${config}.trig_uwt3 -text {filter 3} -variable [myvar trig_val] -value uwt3
-        radiobutton ${config}.trig_base -text {baseline} -variable [myvar trig_val] -value base
-#        radiobutton ${config}.trig_sum8 -text {sum of 8} -variable [myvar trig_val] -value sum8
-
-        frame ${config}.spc4 -width 10 -height 10
-
-        button ${config}.acquire -text Acquire \
-            -bg green -activebackground green -command [myproc acquire]
-        button ${config}.restart -text Restart \
-            -bg yellow -activebackground yellow -command [myproc restart]
-        button ${config}.register -text Register \
-            -bg lightblue -activebackground lightblue -command [myproc register]
-
-        grid ${config}.auto_check -sticky w
-        grid ${config}.spc1
-        grid ${config}.thrs_check -sticky w
-        grid ${config}.thrs_field -sticky ew -pady 1 -padx 5
-        grid ${config}.spc2
-        grid ${config}.disp -sticky w -pady 1 -padx 3
-        grid ${config}.disp_data -sticky w
-        grid ${config}.disp_uwt1 -sticky w
-        grid ${config}.disp_uwt2 -sticky w
-        grid ${config}.disp_uwt3 -sticky w
-        grid ${config}.disp_base -sticky w
-#        grid ${config}.disp_sum8 -sticky w
-        grid ${config}.spc3
-        grid ${config}.trig -sticky w -pady 1 -padx 3
-        grid ${config}.trig_data -sticky w
-        grid ${config}.trig_uwt1 -sticky w
-        grid ${config}.trig_uwt2 -sticky w
-        grid ${config}.trig_uwt3 -sticky w
-        grid ${config}.trig_base -sticky w
-#        grid ${config}.disp_sum8 -sticky w
-        grid ${config}.spc4
-        grid ${config}.acquire -sticky ew -pady 3 -padx 5
-        grid ${config}.restart -sticky ew -pady 3 -padx 5
-        grid ${config}.register -sticky ew -pady 3 -padx 5
-
-        grid ${graph} -row 0 -column 0 -sticky news
-        grid ${config} -row 0 -column 1
-
-        grid rowconfigure ${master} 0 -weight 1
-        grid columnconfigure ${master} 0 -weight 1
-        grid columnconfigure ${master} 1 -weight 0 -minsize 80
-
-        # enable zooming
-        Blt_ZoomStack $graph
-
-        #bind .graph <Motion> {%W crosshairs configure -position @%x,%y}
-
-        # create one element with data for the x and y axis, no dots
-        $graph element create Spectrum1 -symbol none -xdata $xvec -ydata $yvec
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc data_update args {
-        my instvar data yvec
-        $yvec set $data
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc auto_update args {
-        my instvar config auto after_handle
-
-        if {$auto} {
-            ${config}.acquire configure -state disabled
-            ${config}.restart configure -state disabled
-            ${config}.register configure -state disabled
-
-            my acquire_restart_loop
-        } else {
-            if {[my exists after_handle]} {
-                after cancel $after_handle
-            }
-            ${config}.acquire configure -state active
-            ${config}.restart configure -state active
-            ${config}.register configure -state active
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc thrs_update args {
-        my instvar config number thrs thrs_val
-
-        set val_addr [format %04x [expr {17 + ${number}}]]
-
-        if {$thrs} {
-            ${config}.thrs_field configure -state normal
-            my thrs_val_update
-        } else {
-            ${config}.thrs_field configure -state disabled
-            my usbCmd ${val_addr}0000
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc thrs_val_update args {
-        my instvar config number thrs_val
-
-        if {[string equal $thrs_val {}]} {
-            set thrs_val 0
-        }
-
-        set val_addr [format %04x [expr {17 + ${number}}]]
-        set value [format %04x $thrs_val]
-
-        my usbCmd ${val_addr}${value}
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc mux {} {
-        my instvar trig_mux disp_mux
-
-        format {00%x%x} $trig_mux $disp_mux
-    }
-
-# ------------------------------------------------------------------------
-
-    OscDisplay instproc disp_val_update args {
-        my instvar number disp_val disp_mux
-
-        set mux_addr [format %04x [expr {20 + ${number}}]]
-
-        switch -- $disp_val {
-            data {
-                set disp_mux 0
-                my usbCmd ${mux_addr}[my mux]
-            }
-            uwt1 {
-                set disp_mux 1
-                my usbCmd ${mux_addr}[my mux]
-            }
-            uwt2 {
-                set disp_mux 2
-                my usbCmd ${mux_addr}[my mux]
-            }
-            uwt3 {
-                set disp_mux 3
-                my usbCmd ${mux_addr}[my mux]
-            }
-            base {
-                set disp_mux 4
-                my usbCmd ${mux_addr}[my mux]
-            }
-        }
-    }
-
-# ------------------------------------------------------------------------
-
-    OscDisplay instproc trig_val_update args {
-        my instvar number trig_val trig_mux
-
-        set mux_addr [format %04x [expr {20 + ${number}}]]
-
-        switch -- $trig_val {
-            data {
-                set trig_mux 0
-                my usbCmd ${mux_addr}[my mux]
-            }
-            uwt1 {
-                set trig_mux 1
-                my usbCmd ${mux_addr}[my mux]
-            }
-            uwt2 {
-                set trig_mux 2
-                my usbCmd ${mux_addr}[my mux]
-            }
-            uwt3 {
-                set trig_mux 3
-                my usbCmd ${mux_addr}[my mux]
-            }
-            base {
-                set trig_mux 4
-                my usbCmd ${mux_addr}[my mux]
-            }
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc save_data {data} {
-        set file [tk_getSaveFile]
-        if {[string equal $file {}]} {
-            return
-        }
-
-        set x [catch {set fid [open $file w+]}]
-        set y [catch {puts $fid $data}]
-        set z [catch {close $fid}]
-
-        if { $x || $y || $z || ![file exists $file] || ![file isfile $file] || ![file readable $file] } {
-            tk_messageBox -icon error \
-                -message "An error occurred while writing to \"$file\""
-        } else {
-            tk_messageBox -icon info \
-                -message "File \"$file\" written successfully"
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc acquire {} {
-        my instvar number
-        my usbCmdRead 0002000${number} 2 1024
-   }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc restart {} {
-        my instvar number
-        my usbCmd 0001000${number}
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc register {} {
-        my save_data [my set data]
-    }
-
-# -------------------------------------------------------------------------
-
-    OscDisplay instproc acquire_restart_loop {} {
-        my instvar number after_handle
-
-        my acquire
-        my restart
-
-        set after_handle [after 1000 [myproc acquire_restart_loop]]
-    }
-
-# -------------------------------------------------------------------------
-
-    Class HstDisplay -superclass Display -parameter {
-        {number}
-        {master}
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc init {} {
-        my instvar data xvec yvec
-
-        set xvec [vector #auto]
-        set yvec [vector #auto]
-        # fill one vector for the x axis with 4097 points
-        $xvec seq 0 4096
-
-        my reset
-
-        my setup
-
-        next
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc destroy {} {
-        next
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc reset {} {
-        my instvar data xvec yvec
-
-        set data {}
-
-        $yvec set {}
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc start {} {
-        my instvar config base_mux peak_mux
-
-        set base_mux 0
-        set peak_mux 1
-
-        trace add variable [myvar axis] write [myproc axis_update]
-        trace add variable [myvar data] write [myproc data_update]
-        trace add variable [myvar auto] write [myproc auto_update]
-        trace add variable [myvar peak] write [myproc peak_update]
-        trace add variable [myvar thrs] write [myproc thrs_update]
-        trace add variable [myvar thrs_val] write [myproc thrs_val_update]
-        trace add variable [myvar base] write [myproc base_update]
-        trace add variable [myvar base_typ] write [myproc base_typ_update]
-        trace add variable [myvar base_val] write [myproc base_val_update]
-
-        ${config}.axis_check deselect
-        ${config}.auto_check select
-        ${config}.peak_check select
-
-        ${config}.thrs_check select
-        ${config}.thrs_field set 1278
-
-        ${config}.base_const select
-        ${config}.base_field set 35
-        ${config}.base_check deselect
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc setup {} {
-        my instvar number master
-        my instvar data xvec yvec graph
-        my instvar config auto thrs thrs_val base base_typ base_val
-
-        # create a graph widget and show a grid
-        set graph [graph ${master}.graph -height 250 -leftmargin 80]
-        $graph crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
+        $graph crosshairs configure -hide no -linewidth 1 -color darkblue -dashes {2 2}
         $graph grid configure -hide no
         $graph legend configure -hide yes
         $graph axis configure x -min 0 -max 4096
 
-        set config [frame ${master}.config]
+        set config [frame ${master}.config -width 170]
 
         checkbutton ${config}.axis_check -text {log scale} -variable [myvar axis]
 
-        frame ${config}.spc1 -width 10 -height 10
-
-        checkbutton ${config}.auto_check -text {auto update} -variable [myvar auto]
-
-        frame ${config}.spc2 -width 10 -height 10
-
-        checkbutton ${config}.peak_check -text {peak detect} -variable [myvar peak]
-
-        frame ${config}.spc3 -width 10 -height 10
-
-        checkbutton ${config}.thrs_check -text threshold -variable [myvar thrs]
+        frame ${config}.spc1 -width 170 -height 30
+
+        frame ${config}.rate_frame -borderwidth 0 -width 170
+        legendLabel ${config}.rate_frame 0 inst {Inst. rate, 1/s}
+        legendLabel ${config}.rate_frame 1 mean {Avg. rate, 1/s}
+
+        frame ${config}.spc2 -width 170 -height 30
+
+        frame ${config}.chan_frame -borderwidth 0 -width 170
+        legendLabel ${config}.chan_frame 0 entr  {Total entries}
+        legendLabel ${config}.chan_frame 1 empty {}
+        legendLabel ${config}.chan_frame 2 axisy {Bin entries}
+        legendLabel ${config}.chan_frame 3 axisx {Bin number}
+
+        frame ${config}.spc3 -width 170 -height 30
+
+        checkbutton ${config}.thrs_check -text {amplitude threshold} -variable [myvar thrs]
         spinbox ${config}.thrs_field -from 1 -to 4095 \
             -increment 5 -width 10 -textvariable [myvar thrs_val] \
-            -validate all -vcmd {::mca::validate 4095 %P}
-
-        frame ${config}.spc4 -width 10 -height 10
-
-        checkbutton ${config}.base_check -text baseline -variable [myvar base]
-        radiobutton ${config}.base_auto -text automatic -variable [myvar base_typ] -value auto
-        radiobutton ${config}.base_const -text constant -variable [myvar base_typ] -value const
-        spinbox ${config}.base_field -from 1 -to 4095 \
-            -increment 5 -width 10 -textvariable [myvar base_val] \
-            -validate all -vcmd {::mca::validate 4095 %P}
-
-        frame ${config}.spc5 -width 10 -height 10
-
-        button ${config}.acquire -text Acquire \
-            -bg green -activebackground green -command [myproc acquire]
-        button ${config}.restart -text Restart \
-            -bg yellow -activebackground yellow -command [myproc restart]
+            -validate all -vcmd {::mca::validate 4095 4 %P}
+
+        frame ${config}.spc4 -width 170 -height 30
+
+        label ${config}.cntr -text {time of exposure}
+        frame ${config}.cntr_frame -borderwidth 0 -width 170
+
+        label ${config}.cntr_frame.h -width 3 -anchor w -text {h}
+        entry ${config}.cntr_frame.h_field -width 3 -textvariable [myvar cntr_h] \
+            -validate all -vcmd {::mca::validate 999 3 %P}
+        label ${config}.cntr_frame.m -width 3 -anchor w -text {m}
+        entry ${config}.cntr_frame.m_field -width 3 -textvariable [myvar cntr_m] \
+            -validate all -vcmd {::mca::validate 59 2 %P}
+        label ${config}.cntr_frame.s -width 3 -anchor w -text {s}
+        entry ${config}.cntr_frame.s_field -width 6 -textvariable [myvar cntr_s] \
+            -validate all -vcmd {::mca::doublevalidate 59.999 %P}
+
+        grid ${config}.cntr_frame.h_field ${config}.cntr_frame.h \
+            ${config}.cntr_frame.m_field ${config}.cntr_frame.m ${config}.cntr_frame.s_field ${config}.cntr_frame.s
+
+        frame ${config}.spc5 -width 170 -height 10
+
+        button ${config}.start -text Start \
+            -bg yellow -activebackground yellow -command [myproc cntr_start]
+        button ${config}.reset -text Reset \
+            -bg red -activebackground red -command [myproc cntr_reset]
+
+        frame ${config}.spc6 -width 170 -height 30
+
+
         button ${config}.register -text Register \
             -bg lightblue -activebackground lightblue -command [myproc register]
@@ -653,18 +476,17 @@
         grid ${config}.axis_check -sticky w
         grid ${config}.spc1
-        grid ${config}.auto_check -sticky w
+        grid ${config}.rate_frame -sticky ew -padx 5
         grid ${config}.spc2
-        grid ${config}.peak_check -sticky w
+        grid ${config}.chan_frame -sticky ew -padx 5
         grid ${config}.spc3
         grid ${config}.thrs_check -sticky w
         grid ${config}.thrs_field -sticky ew -pady 1 -padx 5
         grid ${config}.spc4
-        grid ${config}.base_check -sticky w
-        grid ${config}.base_auto -sticky w
-        grid ${config}.base_const -sticky w
-        grid ${config}.base_field -sticky ew -pady 1 -padx 5
+        grid ${config}.cntr -sticky w -pady 1 -padx 3
+        grid ${config}.cntr_frame -sticky ew -padx 5
         grid ${config}.spc5
-        grid ${config}.acquire -sticky ew -pady 3 -padx 5
-        grid ${config}.restart -sticky ew -pady 3 -padx 5
+        grid ${config}.start -sticky ew -pady 3 -padx 5
+        grid ${config}.reset -sticky ew -pady 3 -padx 5
+        grid ${config}.spc6
         grid ${config}.register -sticky ew -pady 3 -padx 5
 
@@ -676,11 +498,43 @@
         grid columnconfigure ${master} 1 -weight 0 -minsize 80
 
+        grid columnconfigure ${config}.rate_frame 1 -weight 1
+        grid columnconfigure ${config}.chan_frame 1 -weight 1
+
         # enable zooming
         Blt_ZoomStack $graph
 
+        my crosshairs $graph
+
         #bind .graph <Motion> {%W crosshairs configure -position @%x,%y}
 
         # create one element with data for the x and y axis, no dots
-        $graph element create Spectrum1 -symbol none -smooth step -xdata $xvec -ydata $yvec
+        $graph element create Spectrum1 -color blue -linewidth 2 -symbol none -smooth step -xdata [myvar xvec] -ydata [myvar yvec]
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc coor_update {W x y} {
+        my instvar config graph
+
+        $W crosshairs configure -position @${x},${y}
+
+        set index [$W axis invtransform x $x]
+        set index [::tcl::mathfunc::round $index]
+        catch {
+            ${config}.chan_frame.axisy_value configure -text [[myvar yvec] index $index]
+            ${config}.chan_frame.axisx_value configure -text ${index}.0
+        }
+    }
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc crosshairs {graph} {
+        set method [myproc coor_update]
+        bind $graph <Motion> [list [self] coor_update %W %x %y]
+        bind $graph <Leave> {
+            %W crosshairs off
+        }
+        bind $graph <Enter> {
+            %W crosshairs on
+        }
     }
 
@@ -698,72 +552,472 @@
 # -------------------------------------------------------------------------
 
-    HstDisplay instproc data_update args {
-        my instvar data yvec
-        $yvec set $data
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc auto_update args {
-        my instvar auto after_handle
-        my instvar config
-        if {$auto} {
-            ${config}.acquire configure -state disabled
-            ${config}.register configure -state disabled
-
-            my acquire_loop
-        } else {
-            if {[my exists after_handle]} {
-                after cancel $after_handle
-            }
-            ${config}.acquire configure -state active
-            ${config}.register configure -state active
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc mux {} {
-        my instvar base_mux peak_mux
-
-        format {00%x%x} $base_mux $peak_mux
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc peak_update args {
-        my instvar number peak peak_mux
-
-        set mux_addr [format %04x [expr {23 + ${number}}]]
-
-        if {$peak} {
-            set peak_mux 1
-            my usbCmd ${mux_addr}[my mux]
-        } else {
-            set peak_mux 0
-            my usbCmd ${mux_addr}[my mux]
-        }
-    }
-
-# -------------------------------------------------------------------------
-
     HstDisplay instproc thrs_update args {
-        my instvar config number thrs thrs_val
-
-        set val_addr [format %04x [expr {14 + ${number}}]]
+        my instvar controller config number thrs thrs_val
+
+        if {[string equal $thrs_val {}]} {
+            set thrs_val 0
+        }
+
+        set val_addr [format %02x [expr {6 + 2 * ${number}}]]
 
         if {$thrs} {
             ${config}.thrs_field configure -state normal
-            my thrs_val_update
+            set value [format %03x $thrs_val]
         } else {
             ${config}.thrs_field configure -state disabled
-            my usbCmd ${val_addr}0000
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc thrs_val_update args {
-        my instvar config number thrs_val
+            set value 000
+        }
+
+        $controller usbCmd 000200${val_addr}00040${value}
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc rate_val_update {name key op} {
+        my instvar config rate_val
+
+        ${config}.rate_frame.${key}_value configure -text [format {%.2e} $rate_val(${key})]
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_val_update args {
+        my instvar cntr_val cntr_h cntr_m cntr_s
+
+        set cntr_tmp [expr {${cntr_val}/20000}]
+        set cntr_h [expr {${cntr_tmp}/3600000}]
+        set cntr_m [expr {${cntr_tmp}%3600000/60000}]
+        set cntr_s [expr {${cntr_tmp}%3600000%60000/1000.0}]
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_setup {} {
+        my instvar controller number cntr_val
+
+        set word0 [format %08x [expr {${cntr_val} & 0xFFFFFFFF}]]
+        set word1 [format %08x [expr {${cntr_val} >> 32}]]
+
+        set prefix [format %x [expr {5 + ${number}}]]
+
+        set command {}
+        append command 0001${prefix}000000200000004[string range $word0 4 7]
+        append command 0001${prefix}000000200010004[string range $word0 0 3]
+        append command 0001${prefix}000000200020004[string range $word1 4 7]
+        append command 0001${prefix}000000200030004[string range $word1 0 3]
+
+        # send counter value
+        $controller usbCmd $command
+
+        # load counter value
+#        set val_addr [format %02x [expr {12 + ${number}}]]
+#        $controller usbCmd 000200${val_addr}00040001000200${val_addr}00040000
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_reset {} {
+        my instvar controller number after_handle
+        my instvar cntr_val cntr_bak cntr_old yvec_bak yvec_old
+
+        my cntr_stop
+
+        set value [format %04x [expr {1 << (5 + ${number})}]]
+        $controller usbCmd 000200000004${value}0002000000040000
+
+        set cntr_val $cntr_bak
+        my cntr_setup
+
+        set cntr_old $cntr_bak
+        set yvec_bak 0.0
+        set yvec_old 0.0
+        
+        my acquire
+
+        my cntr_ready
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_ready {} {
+        my instvar config cntr_val cntr_bak
+
+        set cntr_val $cntr_bak
+
+        ${config}.start configure -text Start -command [myproc cntr_start]
+        ${config}.reset configure -state active
+
+        ${config}.cntr_frame.h_field configure -state normal
+        ${config}.cntr_frame.m_field configure -state normal
+        ${config}.cntr_frame.s_field configure -state normal
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_start {} {
+        my instvar config
+        my instvar cntr_h cntr_m cntr_s
+        my instvar cntr_val cntr_bak cntr_old yvec_bak yvec_old
+
+        set h $cntr_h
+        set m $cntr_m
+        set s $cntr_s
+
+        if {[string equal $h {}]} {
+            set h 0
+        }
+        if {[string equal $m {}]} {
+            set m 0
+        }
+        if {[string equal $s {}]} {
+            set s 0
+        }
+
+        set cntr_tmp [expr {${h}*3600000 + ${m}*60000 + ${s}*1000}]
+        set cntr_tmp [expr {entier(20000 * ${cntr_tmp})}]
+
+        if {$cntr_tmp > 0} {
+            ${config}.cntr_frame.h_field configure -state disabled
+            ${config}.cntr_frame.m_field configure -state disabled
+            ${config}.cntr_frame.s_field configure -state disabled
+
+            set cntr_val $cntr_tmp
+            set cntr_bak $cntr_tmp
+            set cntr_old $cntr_tmp
+            set yvec_bak [usb::integrateBlt [myvar yvec] 0]
+            set yvec_old $yvec_bak
+
+            my cntr_setup
+
+            my cntr_resume
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_pause {} {
+        my instvar config
+
+        my cntr_stop
+
+        ${config}.start configure -text Resume -command [myproc cntr_resume]
+#        ${config}.reset configure -state active
+
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_resume {} {
+        my instvar controller config number auto
+
+        set val_addr [format %02x [expr {13 + ${number}}]]
+
+        ${config}.start configure -text Pause -command [myproc cntr_pause]
+#        ${config}.reset configure -state disabled
+
+        $controller usbCmd 000200${val_addr}00040002
+
+        set auto 1
+
+        after 100 [myproc acquire_loop]
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc cntr_stop {} {
+        my instvar controller config number auto
+
+        set val_addr [format %02x [expr {13 + ${number}}]]
+
+        $controller usbCmd 000200${val_addr}00040000
+
+        set auto 0
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc data_update args {
+        my instvar data
+        usb::convertBlt $data 4 [myvar yvec]
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc acquire_loop {} {
+        my instvar cntr_val auto
+
+        my acquire
+
+        if {$cntr_val == 0} {
+            my cntr_stop
+            my cntr_ready
+        } elseif {$auto} {
+            after 1000 [myproc acquire_loop]
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc acquire {} {
+        my instvar controller config number
+        my instvar cntr_val cntr_bak cntr_old yvec_bak yvec_old rate_val
+
+        set size 4096
+
+        set prefix [format {%x} [expr {$number + 2}]]
+
+        set value [format {%08x} [expr {$size * 2}]]
+
+        set command 0001${prefix}000000200000001[string range $value 0 3]0003[string range $value 4 7]00050000
+
+        $controller usbCmdReadRaw $command [expr {$size * 4}] [myvar data]
+        set yvec_new [usb::integrateBlt [myvar yvec] 0]
+
+        set prefix [format {%x} [expr {$number + 5}]]
+        set command 0001${prefix}000000200000003000400050000
+
+        $controller usbCmdReadHex $command 8 1 [myvar cntr_val]
+        set cntr_new $cntr_val
+
+        if {$cntr_new < $cntr_old} {
+            set rate_val(inst) [expr {($yvec_new - $yvec_old)*20000000/($cntr_old - $cntr_new)}]
+            set rate_val(mean) [expr {($yvec_new - $yvec_bak)*20000000/($cntr_bak - $cntr_new)}]
+            ${config}.chan_frame.entr_value configure -text $yvec_new
+
+            set yvec_old $yvec_new
+            set cntr_old $cntr_new
+        }
+   }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc save_data {data} {
+        my instvar number
+
+        set types {
+            {{Data Files}       {.dat}        }
+            {{All Files}        *             }
+        }
+
+        set stamp [clock format [clock seconds] -format %Y%m%d_%H%M%S]
+        set fname spectrum_[expr {$number + 1}]_${stamp}.dat
+
+        set fname [tk_getSaveFile -filetypes $types -initialfile $fname]
+        if {[string equal $fname {}]} {
+            return
+        }
+
+        set x [catch {
+            set fid [open $fname w+]
+            puts $fid $data
+            close $fid
+        }]
+
+        if { $x || ![file exists $fname] || ![file isfile $fname] || ![file readable $fname] } {
+            tk_messageBox -icon error \
+                -message "An error occurred while writing to \"$fname\""
+        } else {
+            tk_messageBox -icon info \
+                -message "File \"$fname\" written successfully"
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    HstDisplay instproc register {} {
+        my save_data [join [[myvar yvec] range 0 4095] \n]
+    }
+
+# -------------------------------------------------------------------------
+
+    Class CntDisplay -parameter {
+        {master}
+        {controller}
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc init {} {
+
+        my set data {}
+        my set cntr 0
+        my set recs 0
+
+        vector create [myvar xvec](16384)
+        vector create [myvar yvec](16384)
+
+        # fill one vector for the x axis with 16384 points
+        [myvar xvec] seq -0.5 16384.5
+
+        my setup
+
+        next
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc destroy {} {
+        next
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc start {} {
+        my instvar config
+
+        trace add variable [myvar data] write [myproc data_update]
+
+        trace add variable [myvar thrs] write [myproc thrs_update]
+        trace add variable [myvar thrs_val] write [myproc thrs_update]
+
+        trace add variable [myvar cntr] write [myproc cntr_update]
+        trace add variable [myvar recs] write [myproc recs_update]
+
+        trace add variable [myvar axis] write [myproc axis_update]
+
+        ${config}.axis_check select
+
+        ${config}.thrs_check select
+        ${config}.thrs_field set 25
+
+        my set cntr_val 100
+        my set cntr_bak 100
+        my set recs_val 100
+        my set recs_bak 100
+
+#        my cntr_reset
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc setup {} {
+        my instvar master
+        my instvar xvec yvec graph
+        my instvar config
+        my instvar cntr_ms
+
+        # create a graph widget and show a grid
+        set graph [graph ${master}.graph -height 250 -leftmargin 80]
+        $graph crosshairs configure -hide no -linewidth 1 -color darkblue -dashes {2 2}
+        $graph grid configure -hide no
+        $graph legend configure -hide yes
+        $graph axis configure x -min 0 -max 16384
+
+        set config [frame ${master}.config -width 170]
+
+        checkbutton ${config}.axis_check -text {log scale} -variable [myvar axis]
+
+        frame ${config}.spc1 -width 170 -height 30
+
+        frame ${config}.chan_frame -borderwidth 0 -width 170
+        legendLabel ${config}.chan_frame 0 mean  {Mean value}
+        legendLabel ${config}.chan_frame 1 entr  {Total entries}
+        legendLabel ${config}.chan_frame 2 empty {}
+        legendLabel ${config}.chan_frame 3 axisy {Bin entries}
+        legendLabel ${config}.chan_frame 4 axisx {Bin number}
+
+        frame ${config}.spc3 -width 170 -height 30
+
+        checkbutton ${config}.thrs_check -text {amplitude threshold} -variable [myvar thrs]
+        spinbox ${config}.thrs_field -from 1 -to 4095 \
+            -increment 5 -width 10 -textvariable [myvar thrs_val] \
+            -validate all -vcmd {::mca::validate 4095 4 %P}
+
+        frame ${config}.spc4 -width 170 -height 30
+
+        label ${config}.cntr -text {time of exposure (ms)}
+        spinbox ${config}.cntr_field -from 0 -to 9999 \
+            -increment 10 -width 10 -textvariable [myvar cntr_val] \
+            -validate all -vcmd {::mca::validate 9999 4 %P}
+
+        frame ${config}.spc5 -width 170 -height 10
+
+        label ${config}.recs -text {number of exposures}
+        spinbox ${config}.recs_field -from 0 -to 99999 \
+            -increment 10 -width 10 -textvariable [myvar recs_val] \
+            -validate all -vcmd {::mca::validate 99999 5 %P}
+
+        frame ${config}.spc6 -width 170 -height 10
+
+        button ${config}.start -text {Start}  \
+            -bg yellow -activebackground yellow -command [myproc recs_start]
+
+        button ${config}.reset -text Reset \
+            -bg red -activebackground red -command [myproc cntr_reset]
+
+        frame ${config}.spc7 -width 170 -height 30
+
+        button ${config}.register -text Register \
+            -bg lightblue -activebackground lightblue -command [myproc register]
+
+        grid ${config}.axis_check -sticky w
+        grid ${config}.spc1
+        grid ${config}.chan_frame -sticky ew -padx 5
+        grid ${config}.spc3
+        grid ${config}.thrs_check -sticky w
+        grid ${config}.thrs_field -sticky ew -pady 1 -padx 5
+        grid ${config}.spc4
+        grid ${config}.cntr -sticky w -pady 1 -padx 3
+        grid ${config}.cntr_field -sticky ew -pady 1 -padx 5
+        grid ${config}.spc5
+        grid ${config}.recs -sticky w -pady 1 -padx 3
+        grid ${config}.recs_field -sticky ew -pady 1 -padx 5
+        grid ${config}.spc6
+        grid ${config}.start -sticky ew -pady 3 -padx 5
+        grid ${config}.reset -sticky ew -pady 3 -padx 5
+        grid ${config}.spc7
+        grid ${config}.register -sticky ew -pady 3 -padx 5
+
+        grid ${graph} -row 0 -column 0 -sticky news
+        grid ${config} -row 0 -column 1
+
+        grid rowconfigure ${master} 0 -weight 1
+        grid columnconfigure ${master} 0 -weight 1
+        grid columnconfigure ${master} 1 -weight 0 -minsize 80
+
+        grid columnconfigure ${config}.chan_frame 1 -weight 1
+
+        # enable zooming
+        Blt_ZoomStack $graph
+
+        my crosshairs $graph
+
+        #bind .graph <Motion> {%W crosshairs configure -position @%x,%y}
+
+        # create one element with data for the x and y axis, no dots
+        $graph element create Spectrum1 -color blue -linewidth 2 -symbol none -smooth step -xdata [myvar xvec] -ydata [myvar yvec]
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc coor_update {W x y} {
+        my instvar config graph
+
+        $W crosshairs configure -position @${x},${y}
+
+        set index [$W axis invtransform x $x]
+        set index [::tcl::mathfunc::round $index]
+        catch {
+            ${config}.chan_frame.axisy_value configure -text [[myvar yvec] index $index]
+            ${config}.chan_frame.axisx_value configure -text ${index}.0
+        }
+    }
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc crosshairs {graph} {
+        set method [myproc coor_update]
+        bind $graph <Motion> [list [self] coor_update %W %x %y]
+        bind $graph <Leave> {
+            %W crosshairs off
+        }
+        bind $graph <Enter> {
+            %W crosshairs on
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc thrs_update args {
+        my instvar controller config thrs thrs_val
 
         if {[string equal $thrs_val {}]} {
@@ -771,143 +1025,293 @@
         }
 
-        set val_addr [format %04x [expr {14 + ${number}}]]
-        set value [format %04x $thrs_val]
-
-        my usbCmd ${val_addr}${value}
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc base_update args {
-        my instvar config number base base_val base_mux
-
-        set mux_addr [format %04x [expr {23 + ${number}}]]
-        set val_addr [format %04x [expr {11 + ${number}}]]
-
-        if {$base} {
-            ${config}.base_auto configure -state normal
-            ${config}.base_const configure -state normal
-            my base_typ_update
+        set number 0
+        set val_addr [format %02x [expr {7 + 2 * ${number}}]]
+
+        if {$thrs} {
+            ${config}.thrs_field configure -state normal
+            set value [format %03x $thrs_val]
         } else {
-            ${config}.base_auto configure -state disabled
-            ${config}.base_const configure -state disabled
-            ${config}.base_field configure -state disabled
-            set base_mux 0
-            my usbCmd ${mux_addr}[my mux]${val_addr}0000
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc base_typ_update args {
-        my instvar config number base_typ base_val base_mux
-
-        set mux_addr [format %04x [expr {23 + ${number}}]]
-        set val_addr [format %04x [expr {11 + ${number}}]]
-        set value [format %04x $base_val]
-
-        switch -- $base_typ {
-            auto {
-                ${config}.base_field configure -state disabled
-                set base_mux 1
-                my usbCmd ${mux_addr}[my mux]
-            }
-            const {
-                ${config}.base_field configure -state normal
-                set base_mux 0
-                my usbCmd ${mux_addr}[my mux]${val_addr}${value}
-            }
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc base_val_update args {
-        my instvar number base_val
-
-        if {[string equal $base_val {}]} {
-            set base_val 0
-        }
-
-        set val_addr [format %04x [expr {11 + ${number}}]]
-        set value [format %04x $base_val]
-
-        my usbCmd ${val_addr}${value}
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc acquire {} {
-        my instvar number
-        my usbCmdRead 0002001${number} 4 4096
+            ${config}.thrs_field configure -state disabled
+            set value 000
+        }
+
+        $controller usbCmd 000200${val_addr}00040${value}
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc cntr_update args {
+        my instvar cntr cntr_val
+        set cntr_val [expr {${cntr}/20000}]
+
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc recs_update args {
+        my instvar recs recs_val
+        set recs_val [expr {${recs}*1}]
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc cntr_setup {} {
+        my instvar controller cntr_val
+
+        set cntr_tmp [expr {${cntr_val} * 20000}]
+        set word0 [format {%08x} [expr {${cntr_tmp} & 0xFFFFFFFF}]]
+        set word1 [format {%08x} [expr {${cntr_tmp} >> 32}]]
+
+        set prefix [format {%x} 9]
+
+        set command {}
+        append command 0001${prefix}000000200000004[string range $word0 4 7]
+        append command 0001${prefix}000000200010004[string range $word0 0 3]
+        append command 0001${prefix}000000200020004[string range $word1 4 7]
+        append command 0001${prefix}000000200030004[string range $word1 0 3]
+
+        # send counter value
+        $controller usbCmd $command
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc recs_setup {} {
+        my instvar controller recs_val
+
+        set word0 [format {%08x} [expr {${recs_val} & 0xFFFFFFFF}]]
+        set word1 [format {%08x} [expr {${recs_val} >> 32}]]
+
+        set prefix [format {%x} 10]
+
+        set command {}
+        append command 0001${prefix}000000200000004[string range $word0 4 7]
+        append command 0001${prefix}000000200010004[string range $word0 0 3]
+        append command 0001${prefix}000000200020004[string range $word1 4 7]
+        append command 0001${prefix}000000200030004[string range $word1 0 3]
+
+        # send counter value
+        $controller usbCmd $command
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc cntr_reset {} {
+        my instvar controller after_handle
+        my instvar cntr_val cntr_bak recs_val recs_bak
+
+        my cntr_stop
+
+        set value [format {%04x} [expr {1 << 11}]]
+        $controller usbCmd 000200000004${value}0002000000040000
+
+        my recs_stop
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc cntr_ready {} {
+        my instvar config cntr_val cntr_bak recs_val recs_bak
+
+        set cntr_val $cntr_bak
+        set recs_val $recs_bak
+
+        ${config}.start configure -text Start -command [myproc recs_start]
+        ${config}.reset configure -state active
+
+        ${config}.start configure -state active
+        ${config}.cntr_field configure -state normal
+        ${config}.recs_field configure -state normal
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc recs_start {} {
+        my instvar controller config auto
+        my instvar cntr_val cntr_bak recs_val recs_bak
+
+        if {$cntr_val > 0 && $recs_val > 0} {
+            ${config}.start configure -text {Stop} -command [myproc recs_stop]
+            ${config}.cntr_field configure -state disabled
+            ${config}.recs_field configure -state disabled
+
+            set cntr_bak $cntr_val
+            set recs_bak $recs_val
+
+            my cntr_setup
+            my recs_setup
+
+            set val_addr [format {%02x} 16]
+
+            $controller usbCmd 000200${val_addr}00040002
+
+            set auto 1
+
+            after 100 [myproc acquire_loop]
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc recs_stop {} {
+        my instvar cntr_val cntr_bak recs_val recs_bak
+
+        my cntr_stop
+
+        set cntr_val $cntr_bak
+        my cntr_setup
+
+        set recs_val $recs_bak
+        my recs_setup
+
+        my acquire
+
+        my cntr_ready
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc cntr_stop {} {
+        my instvar controller config auto
+
+        set val_addr [format {%02x} 16]
+
+        $controller usbCmd 000200${val_addr}00040000
+
+        set auto 0
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc acquire_loop {} {
+        my instvar recs_val auto
+
+        my acquire
+
+        if {$recs_val == 0} {
+            my cntr_stop
+            my cntr_ready
+        } elseif {$auto} {
+            after 1000 [myproc acquire_loop]
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc data_update args {
+        my instvar config data
+        usb::convertBlt $data 2 [myvar yvec]
+
+        ${config}.chan_frame.mean_value configure \
+            -text [format {%.2e} [usb::integrateBlt [myvar yvec] 1]]
+        ${config}.chan_frame.entr_value configure \
+            -text [usb::integrateBlt [myvar yvec] 0]
+
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc axis_update args {
+        my instvar axis graph
+        if {$axis} {
+            $graph axis configure y -min 1 -max 1E5 -logscale yes
+        } else {
+            $graph axis configure y -min {} -max {} -logscale no
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc acquire {} {
+        my instvar controller config
+        my instvar cntr cntr_val recs recs_val
+
+        set size 16384
+
+        set prefix [format {%x} 8]
+
+        set value [format {%08x} $size]
+
+        set command 0001${prefix}000000200000001[string range $value 0 3]0003[string range $value 4 7]00050000
+
+        $controller usbCmdReadRaw $command [expr {$size * 2}] [myvar data]
+
+        set prefix [format {%x} 9]
+        set command 0001${prefix}000000200000003000400050000
+
+        $controller usbCmdReadHex $command 8 1 [myvar cntr]
+
+        set prefix [format {%x} 10]
+        set command 0001${prefix}000000200000003000400050000
+
+        $controller usbCmdReadHex $command 8 1 [myvar recs]
    }
 
 # -------------------------------------------------------------------------
 
-    HstDisplay instproc restart {} {
-        my instvar number
-        my usbCmd 0001001${number}
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc save_data {data} {
-        set file [tk_getSaveFile]
-        if {[string equal $file {}]} {
+    CntDisplay instproc save_data {data} {
+
+        set types {
+            {{Data Files}       {.dat}        }
+            {{All Files}        *             }
+        }
+
+        set stamp [clock format [clock seconds] -format %Y%m%d_%H%M%S]
+        set fname counts_${stamp}.dat
+
+        set fname [tk_getSaveFile -filetypes $types -initialfile $fname]
+        if {[string equal $fname {}]} {
             return
         }
 
-        set x [catch {set fid [open $file w+]}]
-        set y [catch {puts $fid $data}]
-        set z [catch {close $fid}]
-
-        if { $x || $y || $z || ![file exists $file] || ![file isfile $file] || ![file readable $file] } {
+        set x [catch {
+            set fid [open $fname w+]
+            puts $fid $data
+            close $fid
+        }]
+
+        if { $x || ![file exists $fname] || ![file isfile $fname] || ![file readable $fname] } {
             tk_messageBox -icon error \
-                -message "An error occurred while writing to \"$file\""
+                -message "An error occurred while writing to \"$fname\""
         } else {
             tk_messageBox -icon info \
-                -message "File \"$file\" written successfully"
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc register {} {
-        my save_data [my set data]
-    }
-
-# -------------------------------------------------------------------------
-
-    HstDisplay instproc acquire_loop {} {
-        my instvar number after_handle
-
-        my acquire
-
-        set after_handle [after 1000 [myproc acquire_loop]]
-    }
-
-# -------------------------------------------------------------------------
-
-    Class EptDisplay -superclass Display -parameter {
-        {number}
+                -message "File \"$fname\" written successfully"
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    CntDisplay instproc register {} {
+        my save_data [join [[myvar yvec] range 0 16383] \n]
+    }
+
+# -------------------------------------------------------------------------
+
+    Class OscDisplay -parameter {
         {master}
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc init {} {
-        my instvar data xvec yvec
-
-        set xvec [vector #auto]
-
-        for {set i 0} {$i < 11} {incr i} {
-          set yvec($i) [vector #auto]
+        {controller}
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc init {} {
+        my instvar sequence data xvec yvec
+
+        set data {}
+        
+        set sequence 0
+
+#        set xvec [vector create #auto(262144)]
+        set xvec [vector create #auto(10000)]
+
+        for {set i 1} {$i <= 9} {incr i} {
+#          dict set yvec $i [vector create #auto(262144)]
+          dict set yvec $i [vector create #auto(10000)]
         }
 
         # fill one vector for the x axis
+#        $xvec seq 0 262143
         $xvec seq 0 10000
 
-        my reset
-
         my setup
 
@@ -917,5 +1321,5 @@
 # -------------------------------------------------------------------------
 
-    EptDisplay instproc destroy {} {
+    OscDisplay instproc destroy {} {
         next
     }
@@ -923,112 +1327,119 @@
 # -------------------------------------------------------------------------
 
-    EptDisplay instproc reset {} {
-        my instvar data xvec yvec
-        my instvar number_val directory
-
-        set data {}
+    OscDisplay instproc start {} {
+        my instvar config
+        my instvar recs_val directory
 
         set directory $::env(HOMEPATH)
-        set number_val 10
-
-        for {set i 0} {$i < 11} {incr i} {
-          $yvec($i) set {}
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc start {} {
+        set recs_val 100
+
+        trace add variable [myvar chan] write [myproc chan_update]
+
+        trace add variable [myvar data] write [myproc data_update]
+
+        trace add variable [myvar auto] write [myproc auto_update]
+
+        trace add variable [myvar thrs] write [myproc thrs_update 0]
+        trace add variable [myvar thrs_val] write [myproc thrs_update 0]
+
+        trace add variable [myvar recs_val] write [myproc recs_val_update]
+
+        trace add variable [myvar last] write [myproc last_update]
+
+        ${config}.chan_frame.chan1_check select
+        ${config}.chan_frame.chan2_check select
+        ${config}.chan_frame.chan3_check select
+        ${config}.chan_frame.chan4_check select
+        ${config}.chan_frame.chan5_check select
+        ${config}.chan_frame.chan6_check select
+
+        ${config}.thrs_check select
+        ${config}.thrs_field set 100
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc setup {} {
+        my instvar master
+        my instvar xvec yvec graph
         my instvar config
 
-        trace add variable [myvar recs_val] write [myproc recs_val_update]
-        trace add variable [myvar data] write [myproc data_update]
-        trace add variable [myvar last] write [myproc data_update]
-
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc setup {} {
-        my instvar master
-        my instvar data xvec yvec graph
-        my instvar config number_val
-
         # create a graph widget and show a grid
-        set display [frame ${master}.display]
-
-        set graph(0) [graph ${display}.graph0 -height 200 -leftmargin 80]
-        $graph(0) crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
-        $graph(0) grid configure -hide no
-        $graph(0) legend configure -hide yes
-        $graph(0) axis configure x -min 0 -max 10000
-        $graph(0) axis configure y -min 0 -max 4100
-
-        set graph(1) [graph ${display}.graph1 -height 200 -leftmargin 80]
-        $graph(1) crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
-        $graph(1) grid configure -hide no
-        $graph(1) legend configure -hide yes
-        $graph(1) axis configure x -min 0 -max 10000 -hide yes
-        $graph(1) axis configure y -min 0 -max 4100
-
-        set graph(2) [graph ${display}.graph2 -height 200 -leftmargin 80]
-        $graph(2) crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
-        $graph(2) grid configure -hide no
-        $graph(2) legend configure -hide yes
-        $graph(2) axis configure x -min 0 -max 10000 -hide yes
-        $graph(2) axis configure y -min 0 -max 4100
-
-        set graph(3) [graph ${display}.graph3 -height 100 -leftmargin 80]
-        $graph(3) crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
-        $graph(3) grid configure -hide no
-        $graph(3) legend configure -hide yes
-        $graph(3) axis configure x -min 0 -max 10000 -hide yes
-        $graph(3) axis configure y -min 0 -max 25
-
-        scale ${master}.last -orient horizontal -from 1 -to 35 -tickinterval 0 -showvalue no -variable [myvar last]
-
-        set config [frame ${master}.config -width 120]
-
-        label ${config}.recs -text {number of records}
-        spinbox ${config}.recs_field -from 5 -to 100 \
-            -increment 5 -width 10 -textvariable [myvar recs_val] \
-            -validate all -vcmd {::mca::validate 100 %P}
-
-        frame ${config}.spc1 -width 10 -height 10
-
-        button ${config}.sequence -text {Start Recording}  \
-            -bg red -activebackground red -command [myproc sequence]
-
-        frame ${config}.spc2 -width 10 -height 10
-
-        label ${config}.stat -text {}
-
-        frame ${config}.spc3 -width 10 -height 20
+        set graph [graph ${master}.graph -height 250 -leftmargin 80]
+        $graph crosshairs configure -hide no -linewidth 1 -color darkblue -dashes {2 2}
+        $graph grid configure -hide no
+        $graph legend configure -hide yes
+        $graph axis configure x -min 0 -max 10000
+        $graph axis configure y -min 0 -max 4100
+
+#        scale ${master}.last -orient horizontal -from 1 -to 27 -tickinterval 0 -showvalue no -variable [myvar last]
+
+        set config [frame ${master}.config -width 170]
+
+        frame ${config}.chan_frame -width 170
+        legendButton ${config}.chan_frame 0 chan1 {Channel 1} [myvar chan(1)] turquoise2
+        legendButton ${config}.chan_frame 1 chan2 {Channel 2} [myvar chan(2)] SpringGreen2
+        legendButton ${config}.chan_frame 2 chan3 {Channel 3} [myvar chan(3)] orchid2
+        legendButton ${config}.chan_frame 3 chan4 {Channel 4} [myvar chan(4)] orange2
+        legendButton ${config}.chan_frame 4 chan5 {Channel 5} [myvar chan(5)] blue1 white
+        legendButton ${config}.chan_frame 5 chan6 {Channel 6} [myvar chan(6)] gray65 white
+        legendLabel  ${config}.chan_frame 6 axisx {Time axis}
+
+        frame ${config}.spc1 -width 170 -height 30
+
+        checkbutton ${config}.auto_check -text {auto update} -variable [myvar auto]
+
+        frame ${config}.spc2 -width 170 -height 30
+
+        checkbutton ${config}.thrs_check -text threshold -variable [myvar thrs]
+        spinbox ${config}.thrs_field -from 1 -to 4095 \
+            -increment 5 -width 10 -textvariable [myvar thrs_val] \
+            -validate all -vcmd {::mca::validate 4095 4 %P}
+
+        frame ${config}.spc3 -width 170 -height 30
 
         button ${config}.acquire -text Acquire \
-            -bg green -activebackground green -command [myproc acquire]
+            -bg green -activebackground green -command [myproc acquire_start]
         button ${config}.register -text Register \
             -bg lightblue -activebackground lightblue -command [myproc register]
 
-
-        grid ${config}.recs -sticky w -pady 1 -padx 3
-        grid ${config}.recs_field -sticky ew -pady 1 -padx 5
+        frame ${config}.spc4 -width 170 -height 30
+
+        label ${config}.recs -text {number of records}
+        spinbox ${config}.recs_field -from 0 -to 10000 \
+            -increment 10 -width 10 -textvariable [myvar recs_val] \
+            -validate all -vcmd {::mca::validate 10000 5 %P}
+
+        frame ${config}.spc5 -width 170 -height 10
+
+        button ${config}.sequence -text {Start Recording} -command [myproc sequence_start] \
+            -bg yellow -activebackground yellow
+
+        frame ${config}.spc6 -width 170 -height 10
+
+        button ${config}.recover -text {Read file} \
+            -bg lightblue -activebackground lightblue -command [myproc recover]
+
+        grid ${config}.chan_frame -sticky ew
         grid ${config}.spc1
-        grid ${config}.sequence -sticky ew -pady 3 -padx 5
+        grid ${config}.auto_check -sticky w
         grid ${config}.spc2
-        grid ${config}.stat -sticky w -pady 1 -padx 3
+        grid ${config}.thrs_check -sticky w
+        grid ${config}.thrs_field -sticky ew -pady 1 -padx 5
         grid ${config}.spc3
         grid ${config}.acquire -sticky ew -pady 3 -padx 5
         grid ${config}.register -sticky ew -pady 3 -padx 5
-
-        grid ${graph(3)} -row 0 -column 0 -sticky news
-        grid ${graph(2)} -row 1 -column 0 -sticky news
-        grid ${graph(1)} -row 2 -column 0 -sticky news
-        grid ${graph(0)} -row 3 -column 0 -sticky news
-
-        grid ${display} -row 0 -column 0 -sticky news
+        grid ${config}.spc4
+        grid ${config}.recs -sticky w -pady 1 -padx 3
+        grid ${config}.recs_field -sticky ew -pady 1 -padx 5
+        grid ${config}.spc5
+        grid ${config}.sequence -sticky ew -pady 3 -padx 5
+        grid ${config}.spc6
+        grid ${config}.recover -sticky ew -pady 3 -padx 5
+
+        grid ${graph} -row 0 -column 0 -sticky news
         grid ${config} -row 0 -column 1
 
-        grid ${master}.last -row 1 -column 0 -columnspan 2 -sticky ew
+#        grid ${master}.last -row 1 -column 0 -columnspan 2 -sticky ew
 
         grid rowconfigure ${master} 0 -weight 1
@@ -1036,91 +1447,285 @@
         grid columnconfigure ${master} 1 -weight 0 -minsize 120
 
-        grid columnconfigure ${display} 0 -weight 1
-        grid rowconfigure ${display} 0 -weight 1
-        grid rowconfigure ${display} 1 -weight 1
-        grid rowconfigure ${display} 2 -weight 1
-        grid rowconfigure ${display} 3 -weight 1
+        grid columnconfigure ${config}.chan_frame 2 -weight 1
 
         # enable zooming
-        Blt_ZoomStack $graph(0)
-        Blt_ZoomStack $graph(1)
-        Blt_ZoomStack $graph(2)
-        Blt_ZoomStack $graph(3)
-
-        #bind .graph <Motion> {%W crosshairs configure -position @%x,%y}
+        Blt_ZoomStack $graph
+
+        my crosshairs $graph
 
         # create one element with data for the x and y axis, no dots
-        $graph(0) element create Spectrum0 -symbol none -xdata $xvec -ydata $yvec(0)
-        $graph(1) element create Spectrum1 -symbol none -xdata $xvec -ydata $yvec(1)
-        $graph(2) element create Spectrum2 -symbol none -xdata $xvec -ydata $yvec(2)
-        for {set i 3} {$i < 11} {incr i} {
-          $graph(3) element create Spectrum$i -symbol none -xdata $xvec -ydata $yvec($i)
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc recs_val_update args {
+        $graph pen create pen1 -color turquoise3 -linewidth 2 -symbol none
+        $graph pen create pen2 -color SpringGreen3 -linewidth 2 -symbol none
+        $graph pen create pen3 -color orchid3 -linewidth 2 -symbol none
+        $graph pen create pen4 -color orange3 -linewidth 2 -symbol none
+        $graph pen create pen5 -color blue2 -linewidth 2 -symbol none
+        $graph pen create pen6 -color gray55 -linewidth 2 -symbol none
+
+        $graph element create Spectrum1 -pen pen1 -xdata $xvec -ydata [dict get $yvec 1]
+        $graph element create Spectrum2 -pen pen2 -xdata $xvec -ydata [dict get $yvec 2]
+        $graph element create Spectrum3 -pen pen3 -xdata $xvec -ydata [dict get $yvec 3]
+        $graph element create Spectrum4 -pen pen4 -xdata $xvec -ydata [dict get $yvec 4]
+        $graph element create Spectrum5 -pen pen5 -xdata $xvec -ydata [dict get $yvec 5]
+        $graph element create Spectrum6 -pen pen6 -xdata $xvec -ydata [dict get $yvec 6]
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc coor_update {W x y} {
+        my instvar xvec yvec graph
+        my instvar config
+
+        $W crosshairs configure -position @${x},${y}
+
+        set index [$W axis invtransform x $x]
+        set index [::tcl::mathfunc::round $index]
+        catch {
+            ${config}.chan_frame.chan1_value configure -text [[dict get $yvec 1] index $index]
+            ${config}.chan_frame.chan2_value configure -text [[dict get $yvec 2] index $index]
+            ${config}.chan_frame.chan3_value configure -text [[dict get $yvec 3] index $index]
+            ${config}.chan_frame.chan4_value configure -text [[dict get $yvec 4] index $index]
+            ${config}.chan_frame.chan5_value configure -text [[dict get $yvec 5] index $index]
+            ${config}.chan_frame.chan6_value configure -text [[dict get $yvec 6] index $index]
+            ${config}.chan_frame.axisx_value configure -text ${index}.0
+        }
+    }
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc crosshairs {graph} {
+        set method [myproc coor_update]
+        bind $graph <Motion> [list [self] coor_update %W %x %y]
+        bind $graph <Leave> {
+            %W crosshairs off
+        }
+        bind $graph <Enter> {
+            %W crosshairs on
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc chan_update {name key op} {
+        my instvar config graph chan
+
+        if {$chan(${key})} {
+            $graph pen configure pen${key} -linewidth 2
+        } else {
+            $graph pen configure pen${key} -linewidth 0
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc recs_val_update args {
         my instvar recs_val
         if {[string equal $recs_val {}]} {
-            set number_val 0
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc data_update args {
-        my instvar data xvec yvec graph last
+            set recs_val 0
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc last_update args {
+        my instvar graph last
 
         set first [expr {$last - 1}]
+
+        $graph axis configure x -min ${first}0000 -max ${last}0000
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc thrs_update {reset args} {
+        my instvar controller config thrs thrs_val
+
+        if {[string equal $thrs_val {}]} {
+            set thrs_val 0
+        }
+
+        if {$thrs} {
+            ${config}.thrs_field configure -state normal
+            set value [format %03x $thrs_val]
+        } else {
+            ${config}.thrs_field configure -state disabled
+            set value 000
+        }
+
+        set command {}
+        if {$reset} {
+            append command 0002000500041${value}
+        }
+        append command 0002000500040${value}
+
+        $controller usbCmd $command
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc data_update args {
+        my instvar data yvec
+        my instvar graph chan waiting sequence auto
+
+        usb::convertOsc $data $yvec
+
+        foreach {key value} [array get chan] {
+            $graph pen configure pen${key} -dashes 0
+        }
+
+        set waiting 0
+
+        if {$sequence} {
+            my sequence_register
+        } elseif {$auto} {
+            after 1000 [myproc acquire_start]
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc acquire_start {} {
+        my instvar graph chan controller waiting
+
+        foreach {key value} [array get chan] {
+            $graph pen configure pen${key} -dashes dot
+        }
+
+        # restart
+        my thrs_update 1
+
+        set waiting 1
+
+        after 200 [myproc acquire_loop]
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc acquire_loop {} {
+        my instvar controller waiting
+
+#        set size 262144
+        set size 10000
+
+        set value [format {%08x} [expr {$size * 4}]]
+
+        set command 00011000000200000001[string range $value 0 3]0003[string range $value 4 7]00050000
         
-        $xvec seq ${first}0000 ${last}0000
-        for {set i 0} {$i < 4} {incr i} {
-            $graph($i) axis configure x -min ${first}0000 -max ${last}0000
-        }
-
-        for {set i 0} {$i < 11} {incr i} {
-            $yvec($i) set [lrange [lindex $data $i] ${first}0000 ${last}0000]
-        }
-    }
-
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc save_data {data} {
-        set file [tk_getSaveFile]
-        if {[string equal $file {}]} {
+        $controller usbCmdReadRaw $command [expr {$size * 8}] [myvar data]
+
+        if {$waiting} {
+            after 200 [myproc acquire_loop]
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc auto_update args {
+        my instvar config auto
+
+        if {$auto} {
+            ${config}.recs_field configure -state disabled
+            ${config}.sequence configure -state disabled
+            ${config}.acquire configure -state disabled
+            ${config}.register configure -state disabled
+            ${config}.recover configure -state disabled
+
+            my acquire_start
+        } else {
+            ${config}.recs_field configure -state normal
+            ${config}.sequence configure -state active
+            ${config}.acquire configure -state active
+            ${config}.register configure -state active
+            ${config}.recover configure -state active
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc save_data {fname} {
+        my instvar data
+
+        set fid [open $fname w+]
+        fconfigure $fid -translation binary -encoding binary
+
+#        puts -nonewline $fid [binary format "H*iH*" "1f8b0800" [clock seconds] "0003"]
+#        puts -nonewline $fid [zlib deflate $data]
+        puts -nonewline $fid $data
+#        puts -nonewline $fid [binary format i [zlib crc32 $data]]
+#        puts -nonewline $fid [binary format i [string length $data]]
+
+        close $fid
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc open_data {} {
+        set types {
+            {{Data Files}       {.dat}     }
+            {{All Files}        *             }
+        }
+
+        set fname [tk_getOpenFile -filetypes $types]
+        if {[string equal $fname {}]} {
             return
         }
 
-        set x [catch {set fid [open $file w+]}]
-        set y [catch {puts $fid $data}]
-        set z [catch {close $fid}]
-
-        if { $x || $y || $z || ![file exists $file] || ![file isfile $file] || ![file readable $file] } {
+        set x [catch {
+            set fid [open $fname r+]
+            fconfigure $fid -translation binary -encoding binary
+#            set size [file size $fname]
+#            seek $fid 10
+#            my set data [zlib inflate [read $fid [expr {$size - 18}]]]
+            my set data [read $fid]
+            close $fid
+        }]
+
+        if { $x || ![file exists $fname] || ![file isfile $fname] || ![file readable $fname] } {
             tk_messageBox -icon error \
-                -message "An error occurred while writing to \"$file\""
+                -message "An error occurred while reading \"$fname\""
         } else {
             tk_messageBox -icon info \
-                -message "File \"$file\" written successfully"
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc acquire {} {
-        my usbCmdReadEpt 00060000 2097152
-   }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc register {} {
-        my save_data [my set data]
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc sequence {} {
-        my instvar config recs_val directory counter
+                -message "File \"$fname\" read successfully"
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc register {} {
+        set types {
+            {{Data Files}       {.dat}     }
+            {{All Files}        *             }
+        }
+
+        set stamp [clock format [clock seconds] -format %Y%m%d_%H%M%S]
+        set fname oscillogram_${stamp}.dat
+
+        set fname [tk_getSaveFile -filetypes $types -initialfile $fname]
+        if {[string equal $fname {}]} {
+            return
+        }
+    
+        if {[catch {my save_data $fname} result]} {
+            tk_messageBox -icon error \
+                -message "An error occurred while writing to \"$fname\""
+        } else {
+            tk_messageBox -icon info \
+                -message "File \"$fname\" written successfully"
+        }
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc recover {} {
+        my open_data
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc sequence_start {} {
+        my instvar config recs_val recs_bak directory counter sequence
+
+        set counter 1
+        if {$counter > $recs_val} {
+            return
+        }
 
         set directory [tk_chooseDirectory -initialdir $directory -title {Choose a directory}]
@@ -1131,258 +1736,95 @@
 
         ${config}.recs_field configure -state disabled
-        ${config}.sequence configure -state disabled
+        ${config}.sequence configure -text {Stop Recording} -command [myproc sequence_stop]
         ${config}.acquire configure -state disabled
         ${config}.register configure -state disabled
+        ${config}.recover configure -state disabled
         
-        set counter 1
+        set recs_bak $recs_val
+
+        set sequence 1
+
+        my acquire_start
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc sequence_register {} {
+        my instvar config recs_val recs_bak directory counter
+
+        set fname [file join $directory oscillogram_$counter.dat]
+
+        my incr counter
+
+        if {[catch {my save_data $fname} result]} {
+            tk_messageBox -icon error \
+                -message "An error occurred while writing to \"$fname\""
+        } elseif {$counter <= $recs_bak} {
+            set recs_val [expr {$recs_bak - $counter}]
+            my acquire_start
+            return
+        }
         
-        if {$counter <= $recs_val} {
-            ${config}.stat configure -text "record $counter of $recs_val"
-            set after_handle [after 100 [myproc acquire_register_loop]]
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    EptDisplay instproc acquire_register_loop {} {
-        my instvar after_handle
-        my instvar config data recs_val directory counter
-
-        my acquire
-
-        set file [file join $directory ept_$counter.dat.gz]
-
-        set x [catch {set fid [open $file w+]}]
-        fconfigure $fid -translation binary -encoding binary
-
-        set y [catch {
-            puts -nonewline $fid [binary format "H*iH*" "1f8b0800" [clock seconds] "0003"]
-            puts -nonewline $fid [zlib deflate $data]
-            puts -nonewline $fid [binary format i [zlib crc32 $data]]
-            puts -nonewline $fid [binary format i [string length $data]]
-        }]
-
-        set z [catch {close $fid}]
-
-        my incr counter
-
-        if { $x || $y || $z || ![file exists $file] || ![file isfile $file] || ![file readable $file] } {
-            tk_messageBox -icon error -message "An error occurred while writing to \"$file\""
-        } elseif {$counter <= $recs_val} {
-            ${config}.stat configure -text "record $counter of $recs_val"
-            set after_handle [after 100 [myproc acquire_register_loop]]
-            return
-        }
+        my sequence_stop
+    }
+
+# -------------------------------------------------------------------------
+
+    OscDisplay instproc sequence_stop {} {
+        my instvar config recs_val recs_bak sequence
+
+        set sequence 0
         
-        ${config}.stat configure -text {}
+        set recs_val $recs_bak
+
         ${config}.recs_field configure -state normal
-        ${config}.sequence configure -state active
+        ${config}.sequence configure -text {Start Recording} -command [myproc sequence_start]
         ${config}.acquire configure -state active
         ${config}.register configure -state active
-
-    }
-
-# -------------------------------------------------------------------------
-
-    Class MemDisplay -superclass Display -parameter {
-        {number}
-        {master}
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc init {} {
-        my instvar data xvec yvec
-
-        set xvec [vector #auto]
-        set yvec [vector #auto]
-
-        # fill one vector for the x axis
-        $xvec seq 0 10000
-
-        my reset
-
-        my setup
-
-        next
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc destroy {} {
-        next
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc reset {} {
-        my instvar data xvec yvec
-
-        set data {}
-
-        $yvec set {}
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc start {} {
-        my instvar config
-
-        trace add variable [myvar data] write [myproc data_update]
-        trace add variable [myvar last] write [myproc data_update]
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc setup {} {
-        my instvar master
-        my instvar data xvec yvec
-        my instvar config auto thrs thrs_val disp_val trig_val
-
-        # create a graph widget and show a grid
-        set graph [graph ${master}.graph -height 250 -leftmargin 80]
-        $graph crosshairs configure -hide no -linewidth 2 -dashes { 1 1 }
-        $graph grid configure -hide no
-        $graph legend configure -hide yes
-        $graph axis configure x -min 0 -max 10000
-#        $graph axis configure y -min 0 -max 4100
-
-        scale ${master}.last -orient horizontal -from 1 -to 105 -tickinterval 0 -variable [myvar last]
-
-        set config [frame ${master}.config]
-
-        button ${config}.acquire -text Acquire \
-            -bg green -activebackground green -command [myproc acquire]
-        button ${config}.register -text Register \
-            -bg lightblue -activebackground lightblue -command [myproc register]
-
-        grid ${config}.acquire -sticky ew -pady 3 -padx 5
-        grid ${config}.register -sticky ew -pady 3 -padx 5
-
-        grid ${graph} -row 0 -column 0 -sticky news
-        grid ${config} -row 0 -column 1
-
-        grid ${master}.last -row 1 -column 0 -columnspan 2 -sticky ew
-
-        grid rowconfigure ${master} 0 -weight 1
-        grid columnconfigure ${master} 0 -weight 1
-        grid columnconfigure ${master} 1 -weight 0 -minsize 80
-
-        # enable zooming
-        Blt_ZoomStack $graph
-
-        #bind .graph <Motion> {%W crosshairs configure -position @%x,%y}
-
-        # create one element with data for the x and y axis, no dots
-        $graph element create Spectrum -symbol none -xdata $xvec -ydata $yvec
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc data_update args {
-        my instvar data yvec last
-
-        set first [expr {$last - 1}]
-        $yvec set [lrange $data ${first}0000 ${last}0000]
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc save_data {data} {
-        set file [tk_getSaveFile]
-        if {[string equal $file {}]} {
-            return
-        }
-
-        set x [catch {set fid [open $file w+]}]
-        set y [catch {puts $fid $data}]
-        set z [catch {close $fid}]
-
-        if { $x || $y || $z || ![file exists $file] || ![file isfile $file] || ![file readable $file] } {
-            tk_messageBox -icon error \
-                -message "An error occurred while writing to \"$file\""
-        } else {
-            tk_messageBox -icon info \
-                -message "File \"$file\" written successfully"
-        }
-    }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc acquire {} {
-        my usbCmdRead 00040000 1 524288
-#        my usbCmdRead 00060000 1 1048576
-   }
-
-# -------------------------------------------------------------------------
-
-    MemDisplay instproc register {} {
-        my save_data [my set data]
-    }
-
-# -------------------------------------------------------------------------
-
-    namespace export MemDisplay
-    namespace export EptDisplay
+        ${config}.recover configure -state active
+    }
+
+# -------------------------------------------------------------------------
+
+    namespace export MuxDisplay
     namespace export HstDisplay
+    namespace export CntDisplay
     namespace export OscDisplay
-    namespace export CfgDisplay
 }
 
-set config [frame .config]
 set notebook [::blt::tabnotebook .notebook -borderwidth 1 -selectforeground black -side bottom]
 
-grid ${config} -row 0 -column 0 -sticky ns -padx 3
-grid ${notebook} -row 0 -column 1  -sticky news -pady 5
+grid ${notebook} -row 0 -column 0  -sticky news -pady 5
 
 grid rowconfigure . 0 -weight 1
-grid columnconfigure . 0 -weight 0  -minsize 50
-grid columnconfigure . 1 -weight 1
-
-foreach i {0 1 2} {
-    set channel [expr $i + 1]
-
-    set window [frame ${notebook}.hst_$i]
-    $notebook insert end -text "Histogram $channel" -window $window -fill both
-    ::mca::HstDisplay hst_$i -number $i -master $window
-
-    set window [frame ${notebook}.osc_$i]
-    $notebook insert end -text "Pulse shape $channel" -window $window -fill both
-    ::mca::OscDisplay osc_$i -number $i -master $window
-}
-
-#set window [frame ${notebook}.cfg]
-#$notebook insert end -text "Configuration" -window $window -fill both
-::mca::CfgDisplay cfg -master $config
+grid columnconfigure . 0 -weight 1
+
+::mca::UsbController usb
+
+set window [frame ${notebook}.hst_0]
+$notebook insert end -text "Spectrum histogram" -window $window -fill both
+::mca::HstDisplay hst_0 -number 0 -master $window -controller usb
+
+set window [frame ${notebook}.cnt_0]
+$notebook insert end -text "Rate histogram" -window $window -fill both
+::mca::CntDisplay cnt_0 -master $window -controller usb
+
+set window [frame ${notebook}.mux]
+$notebook insert end -text "Interconnect" -window $window -fill both
+::mca::MuxDisplay mux -master $window -controller usb
 
 set window [frame ${notebook}.ept]
-$notebook insert end -text "EPT" -window $window -fill both
-::mca::EptDisplay ept -master $window
-
-#set window [frame ${notebook}.mem]
-#$notebook insert end -text "Memory test" -window $window -fill both
-#::mca::MemDisplay mem -master $window
-
-set usb_handle {}
-
-while {[catch {usb::connect 0x09FB 0x6001 1 1 0} usb_handle]} {
-    set answer [tk_messageBox -icon error -type retrycancel \
-        -message {Cannot access USB device} -detail $usb_handle]
-    if {[string equal $answer cancel]} break
-}
-
-# cfg reset
-cfg reset
-
-cfg start
-
-foreach i {0 1 2} {
-    hst_$i start
-    osc_$i start
-
-    hst_$i restart
-    osc_$i restart
-}
-
-ept start
-#mem start
+$notebook insert end -text "Oscilloscope" -window $window -fill both
+::mca::OscDisplay osc -master $window -controller usb
+
+update
+
+usb usbCmd 00000000
+
+hst_0 start
+
+cnt_0 start
+
+mux start
+
+osc start
Index: trunk/MultiChannelUSB/adc_fifo.v
===================================================================
--- trunk/MultiChannelUSB/adc_fifo.v	(revision 104)
+++ 	(revision )
@@ -1,73 +1,0 @@
-module adc_fifo
-	#(
-		parameter	W	=	48 // fifo width
-	)
-	(
-		input	wire			adc_clock,
-		input	wire	[W-1:0]	adc_data,
-
-		input	wire			sys_clock,
-		output	wire			sys_frame,
-		output	wire	[W-1:0]	sys_data
-	);
-
-	wire	[W-1:0]	int_q;
-	reg		[W-1:0]	int_data;
-	
-	reg				state, int_rdreq, int_frame;
-	wire			int_wrfull, int_rdempty;
-
-	dcfifo #(
-		.intended_device_family("Cyclone III"),
-		.lpm_numwords(16),
-		.lpm_showahead("ON"),
-		.lpm_type("dcfifo"),
-		.lpm_width(W),
-		.lpm_widthu(4),
-		.rdsync_delaypipe(4),
-		.wrsync_delaypipe(4),
-		.overflow_checking("ON"),
-		.underflow_checking("ON"),
-		.use_eab("ON"),
-		.write_aclr_synch("OFF")) fifo_unit (
-		.aclr(1'b0),
-		.data(adc_data),
-		.rdclk(sys_clock),
-		.rdreq((~int_rdempty) & int_rdreq),
-		.wrclk(adc_clock),
-		.wrreq(~int_wrfull),
-		.q(int_q),
-		.rdempty(int_rdempty),
-		.wrfull(int_wrfull),
-		.rdfull(),
-		.rdusedw(),
-		.wrempty(),
-		.wrusedw());
-
-	always @(posedge sys_clock)
-	begin
-		case (state)
-			1'b0:
-			begin
-				int_rdreq <= 1'b1;
-				int_frame <= 1'b0;
-				state <= 1'b1;
-			end
-
-			1'b1: 
-			begin
-				if (~int_rdempty)
-				begin
-					int_data <= int_q;
-					int_rdreq <= 1'b0;
-					int_frame <= 1'b1;
-					state <= 1'b0;
-				end
-			end
-		endcase
-	end
-	
-	assign	sys_frame = int_frame;
-	assign	sys_data = int_data;
-
-endmodule
Index: trunk/MultiChannelUSB/adc_lvds.v
===================================================================
--- trunk/MultiChannelUSB/adc_lvds.v	(revision 104)
+++ trunk/MultiChannelUSB/adc_lvds.v	(revision 159)
@@ -1,2 +1,5 @@
+
+(* ALTERA_ATTRIBUTE = {"{-to int_data_p} DDIO_INPUT_REGISTER=HIGH; {-to int_data_n} DDIO_INPUT_REGISTER=LOW"} *)
+
 module adc_lvds
 	#(
@@ -5,70 +8,123 @@
 	)
 	(
+		input	wire						clock,
+
 		input	wire						lvds_dco,
 		input	wire						lvds_fco,
  		input	wire	[size-1:0]			lvds_d,
 
-		output	wire	[size*width-1:0]	adc_data
+ 		input	wire	[1:0]				trig,
+
+		output	wire						adc_frame,
+		output	wire	[size*width-1+2:0]	adc_data
+
 	);
+	localparam	width2	=	width + 2;
+		
 
-	wire 	[size-1:0]	int_data_h, int_data_l;
-	reg 	[width-1:0]	int_data_next [size-1:0];
-//	reg 	[2*width:0]	int_data_next [size-1:0];
-	reg 	[width-1:0]	int_data_reg [size-1:0];
-//	reg 	[2*width:0]	int_data_reg [size-1:0];
+	reg							state, int_rdreq, adc_frame_reg;
+	wire						int_wrfull, int_rdempty;
 
-	reg 	[width-1:0]	int_adc_data [size-1:0];
+	reg		[size-1:0]			int_data_p, int_data_n;
 
-	integer i;
+	reg 	[2:0]				int_edge_reg;
+
+	reg 	[size*width-1:0]	int_fifo_reg;
+	wire	[size*width-1:0]	int_fifo_wire;
+
+	reg 	[size*width2-1:0]	int_data_reg;
+	wire	[size*width2-1:0]	int_data_wire;
+
+	wire	[size*width-1+2:0]	int_q_wire;
+	reg		[size*width-1+2:0]	adc_data_reg;
+	
+
+
 	genvar j;
 
-	altddio_in #(
+	generate
+		for (j = 0; j < size; j = j + 1)
+		begin : INT_DATA
+// MSB first
+//			assign int_data_wire[j*width+width-1:j*width] = {int_data_reg[j*width+width-3:j*width], int_data_p[j], int_data_n[j]};
+// LSB first
+//			assign int_data_wire[j*width+width-1:j*width] = {int_data_n[j], int_data_p[j], int_data_reg[j*width+width-1:j*width+2]};
+
+			assign int_data_wire[j*width2+width2-1:j*width2] = {int_data_reg[j*width2+width2-3:j*width2], int_data_p[j], int_data_n[j]};
+			assign int_fifo_wire[j*width+width-1:j*width] = int_data_reg[j*width2+width2-1:j*width2+2];
+//			assign int_data_wire[j*width2+width2-1:j*width2] = {int_data_n[j], int_data_p[j], int_data_reg[j*width2+width2-1:j*width2+2]};
+//			assign int_fifo_wire[j*width+width-1:j*width] = int_data_reg[j*width2+width2-3:j*width2];
+		end
+	endgenerate
+
+
+	dcfifo #(
 		.intended_device_family("Cyclone III"),
-		.invert_input_clocks("ON"),
-//		.invert_input_clocks("OFF"),
-		.lpm_type("altddio_in"),
-		.width(size)) altddio_in_unit (
-		.datain(lvds_d),
-		.inclock(lvds_dco),
-		.aclr(1'b0),
-		.dataout_h(int_data_h),
-		.dataout_l(int_data_l),
-		.aset(1'b0),
-		.inclocken(1'b1),
-		.sclr(1'b0),
-		.sset(1'b0));
+		.lpm_numwords(16),
+		.lpm_showahead("ON"),
+		.lpm_type("dcfifo"),
+		.lpm_width(size*width+2),
+		.lpm_widthu(4),
+		.rdsync_delaypipe(4),
+		.wrsync_delaypipe(4),
+		.overflow_checking("ON"),
+		.underflow_checking("ON"),
+		.use_eab("ON")) fifo_unit (
+//		.data(int_data_wire),
+		.data({trig, int_fifo_reg}),
+		.rdclk(clock),
+		.rdreq((~int_rdempty) & int_rdreq),
+		.wrclk(lvds_fco),
+		.wrreq(~int_wrfull),
+		.q(int_q_wire),
+		.rdempty(int_rdempty),
+		.wrfull(int_wrfull),
+		.aclr(),
+		.rdfull(),
+		.rdusedw(),
+		.wrempty(),
+		.wrusedw());
+
+	always @ (posedge clock)
+	begin
+		case (state)
+			1'b0:
+			begin
+				int_rdreq <= 1'b1;
+				adc_frame_reg <= 1'b0;
+				state <= 1'b1;
+			end
+
+			1'b1: 
+			begin
+				if (~int_rdempty)
+				begin
+					int_rdreq <= 1'b0;
+					adc_frame_reg <= 1'b1;
+					adc_data_reg <= int_q_wire;
+					state <= 1'b0;
+				end
+			end
+		endcase
+	end
+	
+	always @ (negedge lvds_dco)
+	begin
+		int_data_n <= lvds_d;
+	end
 
 	always @ (posedge lvds_dco)
 	begin
-		for (i = 0; i < size; i = i + 1)
+		int_data_p <= lvds_d;
+		int_data_reg <= int_data_wire;
+		int_edge_reg <= {(~int_edge_reg[1]), int_edge_reg[0], lvds_fco};
+		if (int_edge_reg[1] & int_edge_reg[2])
 		begin
-			int_data_reg[i] <= int_data_next[i];
+			int_fifo_reg <= int_fifo_wire;
 		end
 	end
 
-	always @ (posedge lvds_fco)
-	begin
-		for (i = 0; i < size; i = i + 1)
-		begin
-			int_adc_data[i] <= int_data_next[i];
-//			int_data_next[i] = {int_data_reg[i][2*width-2:0], int_data_l[i], int_data_h[i]};
-		end
-	end
-
-	always @*
-	begin
-		for (i = 0; i < size; i = i + 1)
-		begin
-			int_data_next[i] = {int_data_reg[i][width-3:0], int_data_l[i], int_data_h[i]};
-//			int_data_next[i] = {int_data_reg[i][2*width-2:0], int_data_l[i], int_data_h[i]};
-		end
-	end
-
-	generate
-		for (j = 0; j < size; j = j + 1)
-		begin : ADC_LVDS_OUTPUT
-			assign adc_data[j*width+width-1:j*width] = int_adc_data[j];
-		end
-	endgenerate
+	assign	adc_frame = adc_frame_reg;
+	assign	adc_data = adc_data_reg;
 
 endmodule
Index: trunk/MultiChannelUSB/adc_para.v
===================================================================
--- trunk/MultiChannelUSB/adc_para.v	(revision 104)
+++ 	(revision )
@@ -1,31 +1,0 @@
-module adc_para
-	(
-		input	wire			lvds_dco,
-		input	wire			lvds_fco,
-		input	wire			para_data_ready,
- 		input	wire	[11:0]	para_data,
-
-		output	wire	[11:0]	adc_data
-	);
-
-	reg 	[1:0]	int_data_ready;
-	reg 	[11:0]	int_data, int_adc_data;
-
-	always @ (posedge lvds_dco)
-	begin
-		int_data_ready[1] <= int_data_ready[0];
-		int_data_ready[0] <= para_data_ready;
-		if ((int_data_ready[0]) & (~int_data_ready[1]))
-		begin
-			int_data <= para_data;
-		end
-	end
-
-	always @ (posedge lvds_fco)
-	begin
-		int_adc_data <= int_data;
-	end
-	
-	assign	adc_data = int_adc_data;
-
-endmodule
Index: trunk/MultiChannelUSB/adc_pll.v
===================================================================
--- trunk/MultiChannelUSB/adc_pll.v	(revision 104)
+++ 	(revision )
@@ -1,146 +1,0 @@
-// megafunction wizard: %ALTPLL%
-// GENERATION: STANDARD
-// VERSION: WM1.0
-// MODULE: altpll 
-
-// ============================================================
-// File Name: adc_pll.v
-// Megafunction Name(s):
-// 			altpll
-//
-// Simulation Library Files(s):
-// 			altera_mf
-// ============================================================
-// ************************************************************
-// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE!
-//
-// 9.0 Build 132 02/25/2009 SJ Web Edition
-// ************************************************************
-
-
-//Copyright (C) 1991-2009 Altera Corporation
-//Your use of Altera Corporation's design tools, logic functions 
-//and other software and tools, and its AMPP partner logic 
-//functions, and any output files from any of the foregoing 
-//(including device programming or simulation files), and any 
-//associated documentation or information are expressly subject 
-//to the terms and conditions of the Altera Program License 
-//Subscription Agreement, Altera MegaCore Function License 
-//Agreement, or other applicable license agreement, including, 
-//without limitation, that your use is for the sole purpose of 
-//programming logic devices manufactured by Altera and sold by 
-//Altera or its authorized distributors.  Please refer to the 
-//applicable agreement for further details.
-
-
-// synopsys translate_off
-`timescale 1 ps / 1 ps
-// synopsys translate_on
-module adc_pll (
-	inclk0,
-	c0);
-
-	input	  inclk0;
-	output	  c0;
-
-	wire [4:0] sub_wire0;
-	wire [0:0] sub_wire4 = 1'h0;
-	wire [0:0] sub_wire1 = sub_wire0[0:0];
-	wire  c0 = sub_wire1;
-	wire  sub_wire2 = inclk0;
-	wire [1:0] sub_wire3 = {sub_wire4, sub_wire2};
-
-	altpll	altpll_component (
-				.inclk (sub_wire3),
-				.clk (sub_wire0),
-				.activeclock (),
-				.areset (1'b0),
-				.clkbad (),
-				.clkena ({6{1'b1}}),
-				.clkloss (),
-				.clkswitch (1'b0),
-				.configupdate (1'b0),
-				.enable0 (),
-				.enable1 (),
-				.extclk (),
-				.extclkena ({4{1'b1}}),
-				.fbin (1'b1),
-				.fbmimicbidir (),
-				.fbout (),
-				.locked (),
-				.pfdena (1'b1),
-				.phasecounterselect ({4{1'b1}}),
-				.phasedone (),
-				.phasestep (1'b1),
-				.phaseupdown (1'b1),
-				.pllena (1'b1),
-				.scanaclr (1'b0),
-				.scanclk (1'b0),
-				.scanclkena (1'b1),
-				.scandata (1'b0),
-				.scandataout (),
-				.scandone (),
-				.scanread (1'b0),
-				.scanwrite (1'b0),
-				.sclkout0 (),
-				.sclkout1 (),
-				.vcooverrange (),
-				.vcounderrange ());
-	defparam
-		altpll_component.bandwidth_type = "AUTO",
-		altpll_component.clk0_divide_by = 1,
-		altpll_component.clk0_duty_cycle = 50,
-		altpll_component.clk0_multiply_by = 6,
-		altpll_component.clk0_phase_shift = "0",
-		altpll_component.compensate_clock = "CLK0",
-		altpll_component.inclk0_input_frequency = 50000,
-		altpll_component.intended_device_family = "Cyclone III",
-		altpll_component.lpm_hint = "CBX_MODULE_PREFIX=adc_pll",
-		altpll_component.lpm_type = "altpll",
-		altpll_component.operation_mode = "NORMAL",
-		altpll_component.pll_type = "AUTO",
-		altpll_component.port_activeclock = "PORT_UNUSED",
-		altpll_component.port_areset = "PORT_UNUSED",
-		altpll_component.port_clkbad0 = "PORT_UNUSED",
-		altpll_component.port_clkbad1 = "PORT_UNUSED",
-		altpll_component.port_clkloss = "PORT_UNUSED",
-		altpll_component.port_clkswitch = "PORT_UNUSED",
-		altpll_component.port_configupdate = "PORT_UNUSED",
-		altpll_component.port_fbin = "PORT_UNUSED",
-		altpll_component.port_inclk0 = "PORT_USED",
-		altpll_component.port_inclk1 = "PORT_UNUSED",
-		altpll_component.port_locked = "PORT_UNUSED",
-		altpll_component.port_pfdena = "PORT_UNUSED",
-		altpll_component.port_phasecounterselect = "PORT_UNUSED",
-		altpll_component.port_phasedone = "PORT_UNUSED",
-		altpll_component.port_phasestep = "PORT_UNUSED",
-		altpll_component.port_phaseupdown = "PORT_UNUSED",
-		altpll_component.port_pllena = "PORT_UNUSED",
-		altpll_component.port_scanaclr = "PORT_UNUSED",
-		altpll_component.port_scanclk = "PORT_UNUSED",
-		altpll_component.port_scanclkena = "PORT_UNUSED",
-		altpll_component.port_scandata = "PORT_UNUSED",
-		altpll_component.port_scandataout = "PORT_UNUSED",
-		altpll_component.port_scandone = "PORT_UNUSED",
-		altpll_component.port_scanread = "PORT_UNUSED",
-		altpll_component.port_scanwrite = "PORT_UNUSED",
-		altpll_component.port_clk0 = "PORT_USED",
-		altpll_component.port_clk1 = "PORT_UNUSED",
-		altpll_component.port_clk2 = "PORT_UNUSED",
-		altpll_component.port_clk3 = "PORT_UNUSED",
-		altpll_component.port_clk4 = "PORT_UNUSED",
-		altpll_component.port_clk5 = "PORT_UNUSED",
-		altpll_component.port_clkena0 = "PORT_UNUSED",
-		altpll_component.port_clkena1 = "PORT_UNUSED",
-		altpll_component.port_clkena2 = "PORT_UNUSED",
-		altpll_component.port_clkena3 = "PORT_UNUSED",
-		altpll_component.port_clkena4 = "PORT_UNUSED",
-		altpll_component.port_clkena5 = "PORT_UNUSED",
-		altpll_component.port_extclk0 = "PORT_UNUSED",
-		altpll_component.port_extclk1 = "PORT_UNUSED",
-		altpll_component.port_extclk2 = "PORT_UNUSED",
-		altpll_component.port_extclk3 = "PORT_UNUSED",
-		altpll_component.width_clock = 5;
-
-
-endmodule
Index: trunk/MultiChannelUSB/amplitude.v
===================================================================
--- trunk/MultiChannelUSB/amplitude.v	(revision 159)
+++ trunk/MultiChannelUSB/amplitude.v	(revision 159)
@@ -0,0 +1,113 @@
+module amplitude
+	#(
+		parameter	width	=	12 // bit width of the input data
+	)
+	(
+		input	wire				clock, frame, reset,
+		input	wire	[width-1:0]	cfg_data,
+		input	wire	[width-1:0]	inp_data,
+		output	wire	[width-1:0]	out_data,
+		output	wire	[1:0]		out_flag
+	);
+
+	reg					int_case_reg, int_case_next;
+	reg					out_flag_reg, out_flag_next;
+	reg					int_flag_reg, int_flag_next;
+	reg		[width-1:0]	int_mini_reg, int_mini_next;
+	reg		[width-1:0]	out_data_reg, out_data_next;
+	reg		[width-1:0]	inp_data_reg [1:0], inp_data_next [1:0];
+
+	wire				int_comp_wire;
+	reg					int_comp_reg, int_comp_next;
+
+	reg		[5:0]		int_cntr_reg, int_cntr_next;
+
+	assign int_comp_wire = (inp_data_reg[1] < inp_data);
+
+	always @(posedge clock)
+	begin
+		if (reset)
+		begin
+			int_case_reg <= 1'b0;
+			int_mini_reg <= {(width){1'b0}};
+			inp_data_reg[0] <= {(width){1'b0}};
+			inp_data_reg[1] <= {(width){1'b0}};
+			out_data_reg <= {(width){1'b0}};
+			out_flag_reg <= 1'b0;
+			int_flag_reg <= 1'b0;
+			int_comp_reg <= 1'b0;
+			int_cntr_reg <= 6'd0;
+		end
+		else
+		begin
+			int_case_reg <= int_case_next;
+			int_mini_reg <= int_mini_next;
+			inp_data_reg[0] <= inp_data_next[0];
+			inp_data_reg[1] <= inp_data_next[1];
+			out_data_reg <= out_data_next;
+			out_flag_reg <= out_flag_next;
+			int_flag_reg <= int_flag_next;
+			int_comp_reg <= int_comp_next;
+			int_cntr_reg <= int_cntr_next;
+		end
+	end
+	
+	always @*
+	begin
+		int_case_next = int_case_reg;
+		int_mini_next = int_mini_reg;
+		inp_data_next[0] = inp_data_reg[0];
+		inp_data_next[1] = inp_data_reg[1];
+		out_data_next = out_data_reg;
+		out_flag_next = out_flag_reg;
+		int_flag_next = int_flag_reg;
+		int_comp_next = int_comp_reg;
+		int_cntr_next = int_cntr_reg;
+		
+		case (int_case_reg)
+			0:
+			begin
+				if (frame)
+				begin
+					inp_data_next[0] = inp_data;
+					inp_data_next[1] = inp_data_reg[0];
+					int_comp_next = int_comp_wire;
+					out_data_next = {(width){1'b0}};
+					out_flag_next = 1'b0;
+					// minimum
+					if ((~int_comp_reg) & (int_comp_wire) & int_cntr_reg[5])
+					begin
+						int_mini_next = inp_data_reg[0];
+						int_flag_next = 1'b1;
+					end
+					// maximum after minimum
+					else if ((int_comp_reg) & (~int_comp_wire) & (int_flag_reg))
+					begin
+						out_data_next = inp_data_reg[0] - int_mini_reg;
+						int_flag_next = 1'b0;
+						int_case_next = 1'b1;
+					end
+					else if (~int_cntr_reg[5])
+					begin
+						int_cntr_next = int_cntr_reg + 6'd1;
+					end
+                end
+ 			end
+			
+			1:
+			begin
+				if (out_data_reg > cfg_data)
+				begin
+					int_cntr_next = 6'b0;
+					out_flag_next = 1'b1;
+				end
+				int_case_next = 1'b0;
+ 			end
+
+		endcase
+	end
+
+	assign out_data = out_data_reg;
+	assign out_flag = {~int_cntr_reg[5], out_flag_reg};
+
+endmodule
Index: trunk/MultiChannelUSB/analyser.v
===================================================================
--- trunk/MultiChannelUSB/analyser.v	(revision 104)
+++ 	(revision )
@@ -1,187 +1,0 @@
-module analyser
-	(
-		input	wire			clock, frame, reset,
-		input	wire	[24:0]	cfg_data,
-		input	wire	[1:0]	uwt_flag,
-		input	wire	[11:0]	uwt_data,
-		output	wire			ana_dead,
-		output	wire			ana_good,
-		output	wire	[11:0]	ana_data,
-		output	wire	[11:0]	ana_base
-	);
-
-	reg		[2:0]	state_reg, state_next;
-	reg		[4:0]	counter_reg, counter_next;
-	reg				dead_reg, dead_next;
-	reg				good_reg, good_next;
-	reg		[11:0]	data_reg, data_next;
-
-	reg		[19:0]	sample_reg, sample_next;
-
-	reg		[19:0]	buffer_reg [31:0];
-	reg		[19:0]	buffer_next [31:0];
-
-	wire	[11:0]	baseline = buffer_reg[31][16:5];
-	wire			counter_max = (&counter_reg);
-
-	integer i;
-
-	always @(posedge clock)
-	begin
-		if (reset)
-		begin
-			state_reg <= 3'd0;
-			counter_reg <= 5'd0;
-			sample_reg = 20'd0;
-			dead_reg <= 1'b0;
-			good_reg <= 1'b0;
-			data_reg <= 12'd0;
-
-			for (i = 0; i <= 31; i = i + 1)
-			begin
-				buffer_reg[i] <= 20'hfffff;
-			end
-		end
-		else
-		begin
-			state_reg <= state_next;
-			counter_reg <= counter_next;
-			sample_reg <= sample_next;
-			dead_reg <= dead_next;
-			good_reg <= good_next;
-			data_reg <= data_next;
-
-			for (i = 0; i <= 31; i = i + 1)
-			begin
-				buffer_reg[i] <= buffer_next[i];
-			end
-		end
-	end
-	
-	always @*
-	begin
-		state_next = state_reg;
-		counter_next = counter_reg;
-		sample_next = sample_reg;
-		dead_next = dead_reg;
-		good_next = good_reg;
-		data_next = data_reg;
-		
-		for (i = 0; i <= 31; i = i + 1)
-		begin
-			buffer_next[i] = buffer_reg[i];
-		end
-
-		case (state_reg)
-			0: // skip first 32 samples
-			begin
-				if (frame)
-				begin
-					counter_next = counter_reg + 5'd1;
-					if (counter_max)
-					begin
-						state_next = 3'd1;
-					end
-                end
- 			end
-
-			1: // skip first 32 baseline samples
-			begin
-				if (frame)
-				begin
-					for (i = 0; i < 31; i = i + 1)
-					begin
-						buffer_next[i+1] = buffer_reg[i] + {8'd0, uwt_data};
-					end
-					buffer_next[0] = {8'd0, uwt_data};
-
-					counter_next = counter_reg + 5'd1;
-					if (counter_max)
-					begin
-						state_next = 3'd2;
-					end
-                end
- 			end
-
-			2:
-			begin
-				if (frame)
-				begin
-
-					if (cfg_data[24])
-					begin
-						if (uwt_data > baseline)
-						begin
-							data_next = uwt_data - baseline;
-						end
-						else
-						begin
-							data_next = 12'd0;
-						end
-					end
-					else
-					begin
-						if (uwt_data > cfg_data[23:12])
-						begin
-							data_next = uwt_data - cfg_data[23:12];
-						end
-						else
-						begin
-							data_next = 12'd0;
-						end
-					end
-	
-					sample_next = {8'd0, uwt_data};
-
-					dead_next = 1'b1;
-					good_next = 1'b0;
-
-					state_next = 3'd3;
-				end
-			end
-			
-			3:
-			begin
-
-				// if (sample - baseline < threshold)
-				if (data_reg < cfg_data[11:0])
-				begin
-					for (i = 0; i < 31; i = i + 1)
-					begin
-						buffer_next[i+1] = buffer_reg[i] + sample_reg;
-					end
-					buffer_next[0] = sample_reg;
-					dead_next = 1'b0;
-				end
-
-				state_next = 3'd2;
-
-				// skip 32 samples after peak
-				if (counter_max)
-				begin
-					if (uwt_flag[0])
-					begin
-						counter_next = 5'd0;
-						state_next = 3'd4;
-					end
-				end
-				else
-				begin
-					counter_next = counter_reg + 5'd1;
-				end	
-			end
-
-			4:
-			begin
-				good_next = dead_reg;
-				state_next = 2'd2;
- 			end
-		endcase
-	end
-
-	assign ana_dead = dead_reg;
-	assign ana_good = good_reg;
-	assign ana_data = data_reg;
-	assign ana_base = baseline;
-
-endmodule
Index: trunk/MultiChannelUSB/clip.v
===================================================================
--- trunk/MultiChannelUSB/clip.v	(revision 159)
+++ trunk/MultiChannelUSB/clip.v	(revision 159)
@@ -0,0 +1,366 @@
+module clip
+	#(
+		parameter	shift	=	24, // right shift of the result
+		parameter	width	=	27, // bit width of the input data
+		parameter	widthr	=	12 // bit width of the output data
+	)
+	(
+		input	wire					clock, frame, reset,
+		input	wire	[4*6-1:0]		del_data,
+		input	wire	[4*6-1:0]		amp_data,
+		input	wire	[4*16-1:0]		tau_data,
+		input	wire	[4*width-1:0]	inp_data,
+		output	wire	[4*widthr-1:0]	out_data
+	);
+
+	localparam	width1	=	width + 16;
+	localparam	width2	=	width + 6;
+	localparam	width3	=	width1 + 2;
+
+	reg						int_wren_reg, int_wren_next;
+	reg						int_flag_reg, int_flag_next;
+	reg		[1:0]			int_chan_reg, int_chan_next;
+	reg		[2:0]			int_case_reg, int_case_next;
+	reg		[7:0]			int_addr_reg, int_addr_next;
+
+	reg		[5:0]			del_addr_reg, del_addr_next;
+	wire	[5:0]			del_addr_wire;
+	wire	[7:0]			int_addr_wire;
+
+	reg		[widthr-1:0]	out_data_reg [4:0], out_data_next [4:0];
+	wire	[widthr-1:0]	out_data_wire;
+
+	reg		[width3-1:0]	add_data_reg [4:0], add_data_next [4:0];
+	wire	[width3-1:0]	add_data_wire;
+
+	wire	[width1-1:0]	mul_data_wire1;
+	wire	[width2-1:0]	mul_data_wire2;
+
+	reg		[width-1:0]		inp_data_reg [3:0], inp_data_next [3:0];
+	wire	[width-1:0]		inp_data_wire [4:0];
+
+	reg		[5:0]			amp_data_reg, amp_data_next;
+	wire	[5:0]			amp_data_wire [3:0];
+
+	reg		[15:0]			tau_data_reg, tau_data_next;
+	wire	[15:0]			tau_data_wire [3:0];
+
+	integer i;
+	genvar j; 
+
+	generate
+		for (j = 0; j < 4; j = j + 1)
+		begin : INT_DATA 
+			assign inp_data_wire[j] = inp_data[j*width+width-1:j*width];
+			assign amp_data_wire[j] = amp_data[j*6+6-1:j*6];
+			assign tau_data_wire[j] = tau_data[j*16+16-1:j*16];
+		end
+	endgenerate
+																				 
+	lpm_mux #(
+		.lpm_size(4),
+		.lpm_type("LPM_MUX"),
+		.lpm_width(8),
+		.lpm_widths(2)) mux_unit_1 (
+		.sel(int_chan_next),
+		.data({
+			2'd3, del_data[3*6+6-1:3*6],
+			2'd2, del_data[2*6+6-1:2*6],
+			2'd1, del_data[1*6+6-1:1*6],
+			2'd0, del_data[0*6+6-1:0*6]}),
+		.result(int_addr_wire));
+
+	assign del_addr_wire = del_addr_reg - int_addr_wire[5:0];
+
+	lpm_mult #(
+		.lpm_hint("MAXIMIZE_SPEED=9"),
+		.lpm_representation("UNSIGNED"),
+		.lpm_type("LPM_MULT"),
+		.lpm_pipeline(3),
+		.lpm_widtha(width),
+		.lpm_widthb(16),
+		.lpm_widthp(width1)) mult_unit_1 (
+		.clock(clock),
+		.clken(int_wren_reg),
+		.dataa(inp_data_wire[4]),
+		.datab(tau_data_reg),
+		.result(mul_data_wire1));
+
+	lpm_mult #(
+		.lpm_hint("MAXIMIZE_SPEED=9"),
+		.lpm_representation("UNSIGNED"),
+		.lpm_type("LPM_MULT"),
+		.lpm_pipeline(3),
+		.lpm_widtha(width),
+		.lpm_widthb(6),
+		.lpm_widthp(width2)) mult_unit_2 (
+		.clock(clock),
+		.clken(int_wren_reg),
+		.dataa(inp_data_reg[0]),
+		.datab(amp_data_reg),
+		.result(mul_data_wire2));
+
+	assign add_data_wire = 
+		  {2'b0, mul_data_wire2, {(width1-width2){1'b0}}}
+		- {2'b0, mul_data_wire1};
+
+	assign out_data_wire = add_data_reg[0][width3-1] ? {(widthr){1'b0}} :
+		  add_data_reg[0][shift+widthr-1:shift]
+		+ {{(widthr-1){add_data_reg[0][width3-1]}}, add_data_reg[0][shift-1]};
+
+
+	altsyncram #(
+		.address_aclr_b("NONE"),
+		.address_reg_b("CLOCK0"),
+		.clock_enable_input_a("BYPASS"),
+		.clock_enable_input_b("BYPASS"),
+		.clock_enable_output_b("BYPASS"),
+		.intended_device_family("Cyclone III"),
+		.lpm_type("altsyncram"),
+		.numwords_a(256),
+		.numwords_b(256),
+		.operation_mode("DUAL_PORT"),
+		.outdata_aclr_b("NONE"),
+		.outdata_reg_b("CLOCK0"),
+		.power_up_uninitialized("FALSE"),
+		.read_during_write_mode_mixed_ports("DONT_CARE"),
+		.widthad_a(8),
+		.widthad_b(8),
+		.width_a(width),
+		.width_b(width),
+		.width_byteena_a(1)) ram_unit_1 (
+		.wren_a(int_wren_reg),
+		.clock0(clock),
+		.address_a(int_addr_reg),
+		.address_b({int_addr_wire[7:6], del_addr_wire}),
+		.data_a(inp_data_reg[0]),
+		.q_b(inp_data_wire[4]),
+		.aclr0(1'b0),
+		.aclr1(1'b0),
+		.addressstall_a(1'b0),
+		.addressstall_b(1'b0),
+		.byteena_a(1'b1),
+		.byteena_b(1'b1),
+		.clock1(1'b1),
+		.clocken0(1'b1),
+		.clocken1(1'b1),
+		.clocken2(1'b1),
+		.clocken3(1'b1),
+		.data_b({(width){1'b1}}),
+		.eccstatus(),
+		.q_a(),
+		.rden_a(1'b1),
+		.rden_b(1'b1),
+		.wren_b(1'b0));
+
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			int_wren_reg <= 1'b1;
+			int_flag_reg <= 1'b0;
+			int_chan_reg <= 2'd0;
+			int_case_reg <= 3'd0;
+			del_addr_reg <= 6'd0;
+			int_addr_reg <= 8'd0;
+			amp_data_reg <= 6'd0;
+			tau_data_reg <= 16'd0;
+			for(i = 0; i <= 3; i = i + 1)
+			begin
+				inp_data_reg[i] <= {(width){1'b0}};
+			end
+			for(i = 0; i <= 4; i = i + 1)
+			begin
+				out_data_reg[i] <= {(widthr){1'b0}};
+				add_data_reg[i] <= {(width3){1'b0}};
+			end
+		end
+		else
+		begin
+			int_wren_reg <= int_wren_next;
+			int_flag_reg <= int_flag_next;
+			int_chan_reg <= int_chan_next;
+			int_case_reg <= int_case_next;
+			del_addr_reg <= del_addr_next;
+			int_addr_reg <= int_addr_next;
+			amp_data_reg <= amp_data_next;
+			tau_data_reg <= tau_data_next;
+			for(i = 0; i <= 3; i = i + 1)
+			begin
+				inp_data_reg[i] <= inp_data_next[i];
+			end                  
+			for(i = 0; i <= 4; i = i + 1)
+			begin
+				out_data_reg[i] <= out_data_next[i];
+				add_data_reg[i] <= add_data_next[i];
+			end                  
+		end             
+	end
+	
+	always @*
+	begin
+		int_wren_next = int_wren_reg;
+		int_flag_next = int_flag_reg;
+		int_chan_next = int_chan_reg;
+		int_case_next = int_case_reg;
+		del_addr_next = del_addr_reg;
+		int_addr_next = int_addr_reg;
+		amp_data_next = amp_data_reg;
+		tau_data_next = tau_data_reg;
+		for(i = 0; i <= 3; i = i + 1)
+		begin
+			inp_data_next[i] = inp_data_reg[i];
+		end                  
+		for(i = 0; i <= 4; i = i + 1)
+		begin
+			out_data_next[i] = out_data_reg[i];
+			add_data_next[i] = add_data_reg[i];
+		end                  
+
+		case (int_case_reg)		
+			0:
+			begin
+				// write zeros
+				int_wren_next = 1'b1;
+				del_addr_next = 6'd0;
+				int_addr_next = 8'd0;
+				amp_data_next = 6'd0;
+				tau_data_next = 16'd0;
+				for(i = 0; i <= 3; i = i + 1)
+				begin
+					inp_data_next[i] = {(width){1'b0}};
+				end                  
+				for(i = 0; i <= 4; i = i + 1)
+				begin
+					out_data_next[i] = {(widthr){1'b0}};
+					add_data_next[i] = {(width3){1'b0}};
+				end                  
+
+				int_case_next = 3'd1;
+			end	
+			1:
+			begin
+				// write zeros
+				int_addr_next = int_addr_reg + 8'd1;
+				if (&int_addr_reg)
+				begin
+					int_wren_next = 1'b0;
+					int_flag_next = 1'b0;
+					int_chan_next = 2'd0;
+					int_case_next = 3'd2;
+				end
+			end	
+			2: // frame
+			begin
+				int_flag_next = 1'b0;
+				int_wren_next = frame;
+				if (frame)
+				begin
+					int_addr_next[7:6] = 2'd0;
+					
+					// set read addr for 2nd pipeline
+					int_chan_next = 2'd1;
+
+					// register input data for 2nd, 3rd and 4th sums
+					inp_data_next[1] = inp_data_wire[1];
+					inp_data_next[2] = inp_data_wire[2];
+					inp_data_next[3] = inp_data_wire[3];
+
+					// prepare registers for 1st sum					
+					inp_data_next[0] = inp_data_wire[0];
+					// prepare registers for 2nd shift					
+					add_data_next[0] = add_data_reg[2];
+
+					tau_data_next = tau_data_wire[0];
+					amp_data_next = amp_data_wire[0];
+					
+					int_case_next = 3'd3;
+				end
+				if (int_flag_reg) // register 4th sum
+				begin
+					int_addr_next[5:0] = del_addr_reg;
+					// register 1st product
+					add_data_next[1] = add_data_wire;
+					out_data_next[1] = out_data_wire;
+				end
+			end
+			3:  // 1st sum
+			begin				
+				int_addr_next[7:6] = 2'd1;
+
+				// set read addr for 3rd pipeline
+				int_chan_next = 2'd2;
+
+				// prepare registers for 2nd sum
+				inp_data_next[0] = inp_data_reg[1];
+				// prepare registers for 3rd shift
+				add_data_next[0] = add_data_reg[3];
+				
+				tau_data_next = tau_data_wire[1];
+				amp_data_next = amp_data_wire[1];
+
+				// register 2nd product
+				add_data_next[2] = add_data_wire;
+				out_data_next[2] = out_data_wire;
+
+				int_case_next = 3'd4;
+			end
+			4: // 2nd sum
+			begin
+				int_addr_next[7:6] = 2'd2;
+
+				// set read addr for 4th pipeline
+				int_chan_next = 2'd3;
+
+				// prepare registers for 3rd sum	
+				inp_data_next[0] = inp_data_reg[2];
+				// prepare registers for 4th shift	
+				add_data_next[0] = add_data_reg[4];
+
+				tau_data_next = tau_data_wire[2];
+				amp_data_next = amp_data_wire[2];
+				
+				// register 3rd product
+				add_data_next[3] = add_data_wire;
+				out_data_next[3] = out_data_wire;
+				
+				del_addr_next = del_addr_reg + 6'd1;
+
+				int_case_next = 3'd5;
+			end
+			5:  // 3rd sum
+			begin				
+				int_flag_next = 1'b1;
+
+				int_addr_next[7:6] = 2'd3;
+					
+				// set read addr for 1st pipeline
+				int_chan_next = 2'd0;
+
+				// prepare registers for 4th sum	
+				inp_data_next[0] = inp_data_reg[3];
+				// prepare registers for 1st shift	
+				add_data_next[0] = add_data_reg[1];
+
+				tau_data_next = tau_data_wire[3];
+				amp_data_next = amp_data_wire[3];
+				
+				// register 4th product
+				add_data_next[4] = add_data_wire;
+				out_data_next[4] = out_data_wire;
+                                             
+				// register 4th output
+				out_data_next[0] = out_data_reg[1];
+
+				int_case_next = 3'd2;
+			end
+			default:
+			begin
+				int_case_next = 3'd0;
+			end
+		endcase
+	end
+
+	assign out_data = {out_data_reg[4], out_data_reg[3], out_data_reg[2], out_data_reg[0]};
+
+endmodule
Index: trunk/MultiChannelUSB/coincidence.v
===================================================================
--- trunk/MultiChannelUSB/coincidence.v	(revision 159)
+++ trunk/MultiChannelUSB/coincidence.v	(revision 159)
@@ -0,0 +1,79 @@
+module coincidence
+	#(
+		parameter	input_width		=	4,
+		parameter	window_size		=	10,
+		parameter	output_width	=	3
+	)
+	(
+		input	wire						clock, frame, reset,
+		input	wire	[output_width-1:0]	cfg_data,
+		input	wire	[input_width-1:0]	trg_data,
+		output	wire	[output_width-1:0]	coi_data,
+		output	wire						coi_flag
+	);
+	
+	reg		[window_size-1:0]	coi_pipe_reg [input_width-1:0];
+	reg							coi_flag_reg;
+
+	wire	[output_width-1:0]	coi_data_wire;
+	wire	[input_width-1:0]	int_data_wire;
+	
+	integer i;
+	genvar j;
+
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			coi_flag_reg <= 1'b0;
+			for(i = 0; i <= 3; i = i + 1)
+			begin
+				coi_pipe_reg[i] <= 0;
+			end
+        end
+        else if (frame)
+		begin
+			if (coi_data_wire >= cfg_data)
+			begin
+				coi_flag_reg <= 1'b1;
+				for(i = 0; i < input_width; i = i + 1)
+				begin
+					coi_pipe_reg[i] <= 0;
+				end
+			end
+			else
+			begin
+				coi_flag_reg <= 1'b0;
+				for(i = 0; i < input_width; i = i + 1)
+				begin
+					coi_pipe_reg[i] <= {coi_pipe_reg[i][window_size-2:0], trg_data[i]};
+				end
+			end
+		end
+	end
+
+	generate
+		for (j = 0; j < input_width; j = j + 1)
+		begin : INT_DATA
+			assign int_data_wire[j] = (|coi_pipe_reg[j]);
+		end
+	endgenerate
+
+	parallel_add #(
+		.msw_subtract("NO"),
+		.representation("UNSIGNED"),
+		.result_alignment("LSB"),
+		.pipeline(1),
+		.shift(0),
+		.size(input_width),
+		.width(1),
+		.widthr(output_width)) parallel_add_unit (
+		.clock(clock),
+		.data(int_data_wire),
+		.result(coi_data_wire));
+
+
+	assign coi_data = coi_data_wire;
+	assign coi_flag = coi_flag_reg;
+
+endmodule
Index: trunk/MultiChannelUSB/configuration.v
===================================================================
--- trunk/MultiChannelUSB/configuration.v	(revision 104)
+++ trunk/MultiChannelUSB/configuration.v	(revision 159)
@@ -4,5 +4,5 @@
 
 		input	wire			bus_ssel, bus_wren,
-		input	wire	[4:0]	bus_addr,
+		input	wire	[5:0]	bus_addr,
 		input	wire	[15:0]	bus_mosi,
 
@@ -10,12 +10,12 @@
 		output	wire			bus_busy,
 		
-		output  wire	[511:0]	cfg_bits
+		output  wire	[1023:0]	cfg_bits
 	);
 
-	wire 	[31:0]	int_ssel_wire;
+	wire 	[63:0]	int_ssel_wire;
 	wire	[15:0]	int_miso_wire;
 	reg		[15:0]	int_miso_reg;
 
-	wire 	[511:0]	int_bits_wire;
+	wire 	[1023:0]	int_bits_wire;
 
 	integer i;
@@ -23,5 +23,5 @@
 
 	generate
-		for (j = 0; j < 32; j = j + 1)
+		for (j = 0; j < 64; j = j + 1)
 		begin : BUS_OUTPUT
 			lpm_ff #(
@@ -43,8 +43,8 @@
 
 	lpm_mux #(
-		.lpm_size(32),
+		.lpm_size(64),
 		.lpm_type("LPM_MUX"),
 		.lpm_width(16),
-		.lpm_widths(5)) bus_miso_mux_unit (
+		.lpm_widths(6)) bus_miso_mux_unit (
 		.sel(bus_addr),
 		.data(int_bits_wire),
@@ -53,7 +53,7 @@
 
 	lpm_decode #(
-		.lpm_decodes(32),
+		.lpm_decodes(64),
 		.lpm_type("LPM_DECODE"),
-		.lpm_width(5)) lpm_decode_unit (
+		.lpm_width(6)) lpm_decode_unit (
 		.data(bus_addr),
 		.eq(int_ssel_wire),
Index: trunk/MultiChannelUSB/counter.v
===================================================================
--- trunk/MultiChannelUSB/counter.v	(revision 104)
+++ trunk/MultiChannelUSB/counter.v	(revision 159)
@@ -1,7 +1,7 @@
 module counter
 	(
-		input	wire			clock, frame, reset,
+		input	wire			clock, frame,
 
-		input	wire	[15:0]	cfg_data,
+		input	wire			reset, setup, count,
 
 		input	wire			bus_ssel, bus_wren,
@@ -23,4 +23,6 @@
 	wire 	[63:0]	reg_bits_wire;
 	wire 	[63:0]	cnt_bits_wire;
+	
+	reg				int_load_reg;
 
 	integer i;
@@ -32,20 +34,10 @@
 		.lpm_type("LPM_COUNTER"),
 		.lpm_width(64)) lpm_counter_component (
-		.sload(cfg_data[0]),
+		.sload(int_load_reg | setup),
 		.sclr(reset),
 		.clock(clock),
 		.data(reg_bits_wire),
-//		.cnt_en(frame & cfg_data[1]),
-		.cnt_en((frame) & (|cnt_bits_wire) & (cfg_data[1])),
-		.q(cnt_bits_wire),
-		.aclr(1'b0),
-		.aload(1'b0),
-		.aset(1'b0),
-		.cin(1'b1),
-		.clk_en(1'b1),
-		.cout(),
-		.eq(),
-		.sset(1'b0),
-		.updown(1'b1));
+		.cnt_en((frame) & (count) & (|cnt_bits_wire)),
+		.q(cnt_bits_wire));
 
 	generate
@@ -60,10 +52,5 @@
 				.clock(clock),
 				.data(bus_mosi),
-				.q(reg_bits_wire[j*16+15:j*16]),
-				.aclr(),
-				.aload(),
-				.aset(),
-				.sload(),
-				.sset());
+				.q(reg_bits_wire[j*16+15:j*16]));
 				end
 	endgenerate
@@ -84,9 +71,5 @@
 		.lpm_width(2)) lpm_decode_unit (
 		.data(bus_addr),
-		.eq(int_ssel_wire),
-		.aclr(),
-		.clken(),
-		.clock(),
-		.enable());
+		.eq(int_ssel_wire));
 
 	always @(posedge clock)
@@ -96,9 +79,11 @@
 			int_miso_reg <= 16'd0;
 			cnt_good_reg <= 1'b0;
+			int_load_reg <= 1'b0;
 		end
 		else
 		begin
 			int_miso_reg <= int_miso_wire;
-			cnt_good_reg <= (|cnt_bits_wire) & (cfg_data[1]);
+			cnt_good_reg <= |cnt_bits_wire;
+			int_load_reg <= bus_ssel & bus_wren;
 		end
 	end
Index: trunk/MultiChannelUSB/delay.v
===================================================================
--- trunk/MultiChannelUSB/delay.v	(revision 159)
+++ trunk/MultiChannelUSB/delay.v	(revision 159)
@@ -0,0 +1,37 @@
+module delay
+	#(
+		parameter	width	=	12,
+		parameter	length	=	32
+	)
+	(
+		input	wire				clock, frame, reset,
+		input	wire	[width-1:0]	inp_data,
+		output	wire	[width-1:0]	out_data
+	);
+	
+	reg		[width-1:0]	int_pipe_reg [length-1:0];
+	
+	integer i;
+
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			for(i = 0; i < length; i = i + 1)
+			begin
+				int_pipe_reg[i] <= 0;
+			end
+        end
+        else if (frame)
+		begin
+			for(i = 0; i <= 30; i = i + 1)
+			begin
+				int_pipe_reg[i+1] <= int_pipe_reg[i];
+			end
+			int_pipe_reg[0] <= inp_data;
+		end
+	end
+
+	assign out_data = int_pipe_reg[length-1];
+
+endmodule
Index: trunk/MultiChannelUSB/filter.v
===================================================================
--- trunk/MultiChannelUSB/filter.v	(revision 159)
+++ trunk/MultiChannelUSB/filter.v	(revision 159)
@@ -0,0 +1,242 @@
+module filter
+	#(
+		parameter	size	=	3, // number of channels
+		parameter	width	=	12 // bit width of the input data (unsigned)
+	)
+	(
+		input	wire						clock, frame, reset,
+		input	wire	[size*width-1:0]	inp_data,
+		output	wire	[size*widthr-1:0]	out_data
+	);
+	
+	localparam	widthr	=	width + 8;
+	/*
+	5-bit LFSR with additional bits to keep track of previous values
+	*/
+	reg		[31:0]				int_lfsr_reg, int_lfsr_next;
+
+	reg							int_wren_reg, int_wren_next;
+	reg							int_flag_reg, int_flag_next;
+	reg							int_chan_reg, int_chan_next;
+	reg		[1:0]				int_case_reg, int_case_next;
+	reg		[5:0]				int_addr_reg, int_addr_next;
+
+	wire	[5:0]				int_addr_wire;
+
+	reg		[size*widthr-1:0]	acc_data_reg [1:0], acc_data_next [1:0];
+	reg		[size*widthr-1:0]	int_data_reg [2:0], int_data_next [2:0];
+
+	wire	[size*widthr-1:0]	acc_data_wire [1:0], del_data_wire;
+
+	integer i;
+	genvar j;
+
+	generate
+		for (j = 0; j < size; j = j + 1)
+		begin : INT_DATA
+			assign acc_data_wire[0][j*widthr+widthr-1:j*widthr] = {{(widthr-width){1'b0}}, inp_data[j*width+width-1:j*width]};
+
+			assign acc_data_wire[1][j*widthr+widthr-1:j*widthr] =
+				  acc_data_reg[0][j*widthr+widthr-1:j*widthr]
+				- del_data_wire[j*widthr+widthr-1:j*widthr]
+				+ acc_data_reg[1][j*widthr+widthr-1:j*widthr];
+
+		end
+	endgenerate
+
+	altsyncram #(
+		.address_aclr_b("NONE"),
+		.address_reg_b("CLOCK0"),
+		.clock_enable_input_a("BYPASS"),
+		.clock_enable_input_b("BYPASS"),
+		.clock_enable_output_b("BYPASS"),
+		.intended_device_family("Cyclone III"),
+		.lpm_type("altsyncram"),
+		.numwords_a(64),
+		.numwords_b(64),
+		.operation_mode("DUAL_PORT"),
+		.outdata_aclr_b("NONE"),
+		.outdata_reg_b("CLOCK0"),
+		.power_up_uninitialized("FALSE"),
+		.read_during_write_mode_mixed_ports("DONT_CARE"),
+		.widthad_a(6),
+		.widthad_b(6),
+		.width_a(size*widthr),
+		.width_b(size*widthr),
+		.width_byteena_a(1)) ram_unit_1 (
+		.wren_a(int_wren_reg),
+		.clock0(clock),
+		.address_a(int_addr_reg),
+		.address_b(int_addr_wire),
+		.data_a(acc_data_reg[0]),
+		.q_b(del_data_wire),
+		.aclr0(1'b0),
+		.aclr1(1'b0),
+		.addressstall_a(1'b0),
+		.addressstall_b(1'b0),
+		.byteena_a(1'b1),
+		.byteena_b(1'b1),
+		.clock1(1'b1),
+		.clocken0(1'b1),
+		.clocken1(1'b1),
+		.clocken2(1'b1),
+		.clocken3(1'b1),
+		.data_b({(size*widthr){1'b1}}),
+		.eccstatus(),
+		.q_a(),
+		.rden_a(1'b1),
+		.rden_b(1'b1),
+		.wren_b(1'b0));
+
+	lpm_mux #(
+		.lpm_size(2),
+		.lpm_type("LPM_MUX"),
+		.lpm_width(6),
+		.lpm_widths(1)) mux_unit_1 (
+		.sel(int_chan_next),
+		.data({
+			1'b1, int_lfsr_reg[20+4:20],
+			1'b0, int_lfsr_reg[5+4:5]}),
+		.result(int_addr_wire));                            
+
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			int_wren_reg <= 1'b1;
+			int_flag_reg <= 1'b0;
+			int_chan_reg <= 1'b0;
+			int_case_reg <= 2'd0;
+			int_addr_reg <= 6'd0;
+			for(i = 0; i <= 1; i = i + 1)
+			begin
+				acc_data_reg[i] <= {(size*widthr){1'b0}};
+			end
+			for(i = 0; i <= 2; i = i + 1)
+			begin
+				int_data_reg[i] <= {(size*widthr){1'b0}};
+			end
+			int_lfsr_reg <= 32'd0;
+		end
+		else
+		begin
+			int_wren_reg <= int_wren_next;
+			int_flag_reg <= int_flag_next;
+			int_chan_reg <= int_chan_next;
+			int_case_reg <= int_case_next;
+			int_addr_reg <= int_addr_next;
+			for(i = 0; i <= 1; i = i + 1)
+			begin
+				acc_data_reg[i] <= acc_data_next[i];
+			end
+			for(i = 0; i <= 2; i = i + 1)
+			begin
+				int_data_reg[i] <= int_data_next[i];
+			end
+			int_lfsr_reg <= int_lfsr_next;
+		end             
+	end
+	
+	always @*
+	begin
+		int_wren_next = int_wren_reg;
+		int_flag_next = int_flag_reg;
+		int_chan_next = int_chan_reg;
+		int_case_next = int_case_reg;
+		int_addr_next = int_addr_reg;
+		for(i = 0; i <= 1; i = i + 1)
+		begin
+			acc_data_next[i] = acc_data_reg[i];
+		end
+		for(i = 0; i <= 2; i = i + 1)
+		begin
+			int_data_next[i] = int_data_reg[i];
+		end
+		int_lfsr_next = int_lfsr_reg;
+
+		case (int_case_reg)		
+			0:
+			begin
+				// write zeros
+				int_wren_next = 1'b1;
+				int_addr_next = 6'd0;
+				for(i = 0; i <= 1; i = i + 1)
+				begin
+					acc_data_next[i] = {(size*widthr){1'b0}};
+				end
+				for(i = 0; i <= 2; i = i + 1)
+				begin
+					int_data_next[i] = {(size*widthr){1'b0}};
+				end
+				int_case_next = 2'd1;
+			end	
+			1:
+			begin
+				// write zeros
+				int_addr_next = int_addr_reg + 6'd1;
+				if (&int_addr_reg)
+				begin
+					int_wren_next = 1'b0;
+					int_flag_next = 1'b0;
+					int_chan_next = 1'b0;
+					int_lfsr_next = 32'h0722BDA6;
+					int_case_next = 'd2;
+				end
+			end	
+			2: // frame
+			begin
+				int_flag_next = 1'b0;
+				if (frame)
+				begin
+					int_wren_next = 1'b1;
+
+					int_addr_next = {1'b0, int_lfsr_reg[4:0]};
+					
+					// set read addr for 2nd pipeline
+					int_chan_next = 1'b1;
+                    
+					// prepare registers for 1st sum					
+					acc_data_next[0] = acc_data_wire[0];
+					acc_data_next[1] = int_data_reg[0];
+					
+					int_lfsr_next = {int_lfsr_reg[30:0], int_lfsr_reg[2] ~^ int_lfsr_reg[4]};
+
+					int_case_next = 'd3;
+				end
+				if (int_flag_reg) // register 2nd sum
+				begin
+					// register 2nd sum
+					int_data_next[1] = acc_data_wire[1];
+				end
+			end
+			3:  // 2nd sum
+			begin				
+				int_flag_next = 1'b1;
+
+				int_addr_next = {1'b1, int_lfsr_reg[5:1]};
+
+				// set read addr for 1st pipeline
+				int_chan_next = 1'b0;
+
+				// prepare registers for 2nd sum	
+				acc_data_next[0] = int_data_reg[0];
+				acc_data_next[1] = int_data_reg[1];
+
+				// register 1st sum
+				int_data_next[0] = acc_data_wire[1];
+				
+				// register 2nd output
+				int_data_next[2] = int_data_reg[1];
+
+				int_case_next = 2'd2;
+			end
+			default:
+			begin
+				int_case_next = 2'd0;
+			end
+		endcase
+	end
+
+	assign out_data = int_data_reg[2];
+
+endmodule
Index: trunk/MultiChannelUSB/histogram.v
===================================================================
--- trunk/MultiChannelUSB/histogram.v	(revision 104)
+++ 	(revision )
@@ -1,199 +1,0 @@
-module histogram
-	(
-		input	wire			clock, frame, reset,
-		
-		input	wire			hst_good,
-		input	wire	[11:0]  hst_data,
-
-		input	wire			bus_ssel, bus_wren,
-		input	wire	[12:0]	bus_addr,
-		input	wire	[15:0]	bus_mosi,
-
-		output	wire	[15:0]	bus_miso,
-		output	wire			bus_busy
-	);
-	
-	// signal declaration
-	reg		[3:0]	int_case_reg, int_case_next;
-	reg				int_wren_reg, int_wren_next;
-	reg		[11:0]	int_addr_reg, int_addr_next;
-	reg		[31:0]	int_data_reg, int_data_next;
-
-	reg		[12:0]	bus_addr_reg, bus_addr_next;
-	reg		[15:0]	bus_miso_reg, bus_miso_next;
-
-	reg				bus_wren_reg, bus_wren_next;
-	reg		[15:0]	bus_mosi_reg, bus_mosi_next;
-
-	wire	[31:0]	q_a_wire;
-	wire	[15:0]	q_b_wire;
-
-	altsyncram #(
-		.address_reg_b("CLOCK0"),
-		.clock_enable_input_a("BYPASS"),
-		.clock_enable_input_b("BYPASS"),
-		.clock_enable_output_a("BYPASS"),
-		.clock_enable_output_b("BYPASS"),
-		.indata_reg_b("CLOCK0"),
-		.intended_device_family("Cyclone III"),
-		.lpm_type("altsyncram"),
-		.numwords_a(4096),
-		.numwords_b(8192),
-		.operation_mode("BIDIR_DUAL_PORT"),
-		.outdata_aclr_a("NONE"),
-		.outdata_aclr_b("NONE"),
-		.outdata_reg_a("CLOCK0"),
-		.outdata_reg_b("CLOCK0"),
-		.power_up_uninitialized("FALSE"),
-		.read_during_write_mode_mixed_ports("OLD_DATA"),
-		.read_during_write_mode_port_a("NEW_DATA_NO_NBE_READ"),
-		.read_during_write_mode_port_b("NEW_DATA_NO_NBE_READ"),
-		.widthad_a(12),
-		.widthad_b(13),
-		.width_a(32),
-		.width_b(16),
-		.width_byteena_a(1),
-		.width_byteena_b(1),
-		.wrcontrol_wraddress_reg_b("CLOCK0")) hst_ram_unit(
-		.wren_a(int_wren_reg),
-		.clock0(clock),
-		.wren_b(bus_wren_reg),
-		.address_a(int_addr_reg),
-		.address_b(bus_addr_reg),
-		.data_a(int_data_reg),
-		.data_b(bus_mosi_reg),
-		.q_a(q_a_wire),
-		.q_b(q_b_wire),
-		.aclr0(1'b0),
-		.aclr1(1'b0),
-		.addressstall_a(1'b0),
-		.addressstall_b(1'b0),
-		.byteena_a(1'b1),
-		.byteena_b(1'b1),
-		.clock1(1'b1),
-		.clocken0(1'b1),
-		.clocken1(1'b1),
-		.clocken2(1'b1),
-		.clocken3(1'b1),
-		.eccstatus(),
-		.rden_a(1'b1),
-		.rden_b(1'b1));
-
-	// body
-	always @(posedge clock)
-	begin
-		if (reset)
-        begin
-			int_wren_reg <= 1'b1;
-			int_addr_reg <= 12'd0;
-			int_data_reg <= 32'd0;
-			int_case_reg <= 4'b0;
-			bus_addr_reg <= 13'd0;
-			bus_miso_reg <= 16'd0;
-			bus_wren_reg <= 1'b0;
-			bus_mosi_reg <= 16'd0;
-		end
-		else
-		begin
-			int_wren_reg <= int_wren_next;
-			int_addr_reg <= int_addr_next;
-			int_data_reg <= int_data_next;
-			int_case_reg <= int_case_next;
-			bus_addr_reg <= bus_addr_next;
-			bus_miso_reg <= bus_miso_next;
-			bus_wren_reg <= bus_wren_next;
-			bus_mosi_reg <= bus_mosi_next;
-		end             
-	end
-
-	always @*
-	begin
-		bus_addr_next = bus_addr_reg;
-		bus_miso_next = bus_miso_reg;
-
-		bus_wren_next = 1'b0;
-		bus_mosi_next = bus_mosi_reg;
-
-		if (bus_ssel)
-		begin
-			bus_miso_next = q_b_wire;	
-			bus_addr_next = bus_addr;
-			bus_wren_next = bus_wren;	
-			if (bus_wren)
-			begin
-				bus_mosi_next = bus_mosi;
-			end
-		end
-	end
-
-	always @*
-	begin
-		int_wren_next = int_wren_reg;
-		int_addr_next = int_addr_reg;
-		int_data_next = int_data_reg;
-		int_case_next = int_case_reg;
-
-		case (int_case_reg)
-						
-			0:
-			begin
-				// write zeros
-				int_addr_next = int_addr_reg + 12'd1;
-				if (&int_addr_reg)
-				begin
-					int_wren_next = 1'b0;
-					int_case_next = 4'd1;
-				end
-			end	
-
-			1:
-			begin
-				int_wren_next = 1'b0;
-/*
-				if (&int_data_reg)
-				begin
-					int_case_next = 4'd0;
-				end
-				else if (frame & hst_good)
-*/
-				if (frame & hst_good)
-				begin
-					int_addr_next = hst_data;
-					int_case_next = 4'd2;
-				end
-			end
-
-			2:
-			begin
-				int_case_next = 4'd3;
-			end
-
-			3:
-			begin
-				int_case_next = 4'd4;
-			end
-
-			4:
-			begin
-				int_case_next = 4'd1;
-				if (~&q_a_wire)
-				begin
-					int_wren_next = 1'b1;
-					int_data_next = q_a_wire + 32'd1;
-				end
-			end
-
-			default:
-			begin
-				int_wren_next = 1'b0;
-				int_addr_next = 12'd0;
-				int_data_next = 32'd0;
-				int_case_next = 4'd0;
-			end
-		endcase
-	end
-
-	// output logic
-	assign	bus_miso = bus_miso_reg;
-	assign	bus_busy = 1'b0;
-endmodule
Index: trunk/MultiChannelUSB/histogram16.v
===================================================================
--- trunk/MultiChannelUSB/histogram16.v	(revision 159)
+++ trunk/MultiChannelUSB/histogram16.v	(revision 159)
@@ -0,0 +1,199 @@
+module histogram16
+	(
+		input	wire			clock, frame, reset,
+		
+		input	wire			hst_good,
+		input	wire	[13:0]  hst_data,
+
+		input	wire			bus_ssel, bus_wren,
+		input	wire	[13:0]	bus_addr,
+		input	wire	[15:0]	bus_mosi,
+
+		output	wire	[15:0]	bus_miso,
+		output	wire			bus_busy
+	);
+	
+	// signal declaration
+	reg		[3:0]	int_case_reg, int_case_next;
+	reg				int_wren_reg, int_wren_next;
+	reg		[13:0]	int_addr_reg, int_addr_next;
+	reg		[15:0]	int_data_reg, int_data_next;
+
+	reg		[13:0]	bus_addr_reg, bus_addr_next;
+	reg		[15:0]	bus_miso_reg, bus_miso_next;
+
+	reg				bus_wren_reg, bus_wren_next;
+	reg		[15:0]	bus_mosi_reg, bus_mosi_next;
+
+	wire	[15:0]	q_a_wire;
+	wire	[15:0]	q_b_wire;
+
+	altsyncram #(
+		.address_reg_b("CLOCK0"),
+		.clock_enable_input_a("BYPASS"),
+		.clock_enable_input_b("BYPASS"),
+		.clock_enable_output_a("BYPASS"),
+		.clock_enable_output_b("BYPASS"),
+		.indata_reg_b("CLOCK0"),
+		.intended_device_family("Cyclone III"),
+		.lpm_type("altsyncram"),
+		.numwords_a(16384),
+		.numwords_b(16384),
+		.operation_mode("BIDIR_DUAL_PORT"),
+		.outdata_aclr_a("NONE"),
+		.outdata_aclr_b("NONE"),
+		.outdata_reg_a("CLOCK0"),
+		.outdata_reg_b("CLOCK0"),
+		.power_up_uninitialized("FALSE"),
+		.read_during_write_mode_mixed_ports("OLD_DATA"),
+		.read_during_write_mode_port_a("NEW_DATA_NO_NBE_READ"),
+		.read_during_write_mode_port_b("NEW_DATA_NO_NBE_READ"),
+		.widthad_a(14),
+		.widthad_b(14),
+		.width_a(16),
+		.width_b(16),
+		.width_byteena_a(1),
+		.width_byteena_b(1),
+		.wrcontrol_wraddress_reg_b("CLOCK0")) hst_ram_unit(
+		.wren_a(int_wren_reg),
+		.clock0(clock),
+		.wren_b(bus_wren_reg),
+		.address_a(int_addr_reg),
+		.address_b(bus_addr_reg),
+		.data_a(int_data_reg),
+		.data_b(bus_mosi_reg),
+		.q_a(q_a_wire),
+		.q_b(q_b_wire),
+		.aclr0(1'b0),
+		.aclr1(1'b0),
+		.addressstall_a(1'b0),
+		.addressstall_b(1'b0),
+		.byteena_a(1'b1),
+		.byteena_b(1'b1),
+		.clock1(1'b1),
+		.clocken0(1'b1),
+		.clocken1(1'b1),
+		.clocken2(1'b1),
+		.clocken3(1'b1),
+		.eccstatus(),
+		.rden_a(1'b1),
+		.rden_b(1'b1));
+
+	// body
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			int_wren_reg <= 1'b1;
+			int_addr_reg <= 14'd0;
+			int_data_reg <= 16'd0;
+			int_case_reg <= 4'b0;
+			bus_addr_reg <= 14'd0;
+			bus_miso_reg <= 16'd0;
+			bus_wren_reg <= 1'b0;
+			bus_mosi_reg <= 16'd0;
+		end
+		else
+		begin
+			int_wren_reg <= int_wren_next;
+			int_addr_reg <= int_addr_next;
+			int_data_reg <= int_data_next;
+			int_case_reg <= int_case_next;
+			bus_addr_reg <= bus_addr_next;
+			bus_miso_reg <= bus_miso_next;
+			bus_wren_reg <= bus_wren_next;
+			bus_mosi_reg <= bus_mosi_next;
+		end             
+	end
+
+	always @*
+	begin
+		bus_addr_next = bus_addr_reg;
+		bus_miso_next = bus_miso_reg;
+
+		bus_wren_next = 1'b0;
+		bus_mosi_next = bus_mosi_reg;
+
+		if (bus_ssel)
+		begin
+			bus_miso_next = q_b_wire;	
+			bus_addr_next = bus_addr;
+			bus_wren_next = bus_wren;	
+			if (bus_wren)
+			begin
+				bus_mosi_next = bus_mosi;
+			end
+		end
+	end
+
+	always @*
+	begin
+		int_wren_next = int_wren_reg;
+		int_addr_next = int_addr_reg;
+		int_data_next = int_data_reg;
+		int_case_next = int_case_reg;
+
+		case (int_case_reg)
+						
+			0:
+			begin
+				// write zeros
+				int_addr_next = int_addr_reg + 14'd1;
+				if (&int_addr_reg)
+				begin
+					int_wren_next = 1'b0;
+					int_case_next = 4'd1;
+				end
+			end	
+
+			1:
+			begin
+				int_wren_next = 1'b0;
+/*
+				if (&int_data_reg)
+				begin
+					int_case_next = 4'd0;
+				end
+				else if (frame & hst_good)
+*/
+				if (frame & hst_good)
+				begin
+					int_addr_next = hst_data;
+					int_case_next = 4'd2;
+				end
+			end
+
+			2:
+			begin
+				int_case_next = 4'd3;
+			end
+
+			3:
+			begin
+				int_case_next = 4'd4;
+			end
+
+			4:
+			begin
+				int_case_next = 4'd1;
+				if (~&q_a_wire)
+				begin
+					int_wren_next = 1'b1;
+					int_data_next = q_a_wire + 16'd1;
+				end
+			end
+
+			default:
+			begin
+				int_wren_next = 1'b0;
+				int_addr_next = 14'd0;
+				int_data_next = 16'd0;
+				int_case_next = 4'd0;
+			end
+		endcase
+	end
+
+	// output logic
+	assign	bus_miso = bus_miso_reg;
+	assign	bus_busy = 1'b0;
+endmodule
Index: trunk/MultiChannelUSB/histogram32.v
===================================================================
--- trunk/MultiChannelUSB/histogram32.v	(revision 159)
+++ trunk/MultiChannelUSB/histogram32.v	(revision 159)
@@ -0,0 +1,199 @@
+module histogram32
+	(
+		input	wire			clock, frame, reset,
+		
+		input	wire			hst_good,
+		input	wire	[11:0]  hst_data,
+
+		input	wire			bus_ssel, bus_wren,
+		input	wire	[12:0]	bus_addr,
+		input	wire	[15:0]	bus_mosi,
+
+		output	wire	[15:0]	bus_miso,
+		output	wire			bus_busy
+	);
+	
+	// signal declaration
+	reg		[3:0]	int_case_reg, int_case_next;
+	reg				int_wren_reg, int_wren_next;
+	reg		[11:0]	int_addr_reg, int_addr_next;
+	reg		[31:0]	int_data_reg, int_data_next;
+
+	reg		[12:0]	bus_addr_reg, bus_addr_next;
+	reg		[15:0]	bus_miso_reg, bus_miso_next;
+
+	reg				bus_wren_reg, bus_wren_next;
+	reg		[15:0]	bus_mosi_reg, bus_mosi_next;
+
+	wire	[31:0]	q_a_wire;
+	wire	[15:0]	q_b_wire;
+
+	altsyncram #(
+		.address_reg_b("CLOCK0"),
+		.clock_enable_input_a("BYPASS"),
+		.clock_enable_input_b("BYPASS"),
+		.clock_enable_output_a("BYPASS"),
+		.clock_enable_output_b("BYPASS"),
+		.indata_reg_b("CLOCK0"),
+		.intended_device_family("Cyclone III"),
+		.lpm_type("altsyncram"),
+		.numwords_a(4096),
+		.numwords_b(8192),
+		.operation_mode("BIDIR_DUAL_PORT"),
+		.outdata_aclr_a("NONE"),
+		.outdata_aclr_b("NONE"),
+		.outdata_reg_a("CLOCK0"),
+		.outdata_reg_b("CLOCK0"),
+		.power_up_uninitialized("FALSE"),
+		.read_during_write_mode_mixed_ports("OLD_DATA"),
+		.read_during_write_mode_port_a("NEW_DATA_NO_NBE_READ"),
+		.read_during_write_mode_port_b("NEW_DATA_NO_NBE_READ"),
+		.widthad_a(12),
+		.widthad_b(13),
+		.width_a(32),
+		.width_b(16),
+		.width_byteena_a(1),
+		.width_byteena_b(1),
+		.wrcontrol_wraddress_reg_b("CLOCK0")) hst_ram_unit(
+		.wren_a(int_wren_reg),
+		.clock0(clock),
+		.wren_b(bus_wren_reg),
+		.address_a(int_addr_reg),
+		.address_b(bus_addr_reg),
+		.data_a(int_data_reg),
+		.data_b(bus_mosi_reg),
+		.q_a(q_a_wire),
+		.q_b(q_b_wire),
+		.aclr0(1'b0),
+		.aclr1(1'b0),
+		.addressstall_a(1'b0),
+		.addressstall_b(1'b0),
+		.byteena_a(1'b1),
+		.byteena_b(1'b1),
+		.clock1(1'b1),
+		.clocken0(1'b1),
+		.clocken1(1'b1),
+		.clocken2(1'b1),
+		.clocken3(1'b1),
+		.eccstatus(),
+		.rden_a(1'b1),
+		.rden_b(1'b1));
+
+	// body
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			int_wren_reg <= 1'b1;
+			int_addr_reg <= 12'd0;
+			int_data_reg <= 32'd0;
+			int_case_reg <= 4'b0;
+			bus_addr_reg <= 13'd0;
+			bus_miso_reg <= 16'd0;
+			bus_wren_reg <= 1'b0;
+			bus_mosi_reg <= 16'd0;
+		end
+		else
+		begin
+			int_wren_reg <= int_wren_next;
+			int_addr_reg <= int_addr_next;
+			int_data_reg <= int_data_next;
+			int_case_reg <= int_case_next;
+			bus_addr_reg <= bus_addr_next;
+			bus_miso_reg <= bus_miso_next;
+			bus_wren_reg <= bus_wren_next;
+			bus_mosi_reg <= bus_mosi_next;
+		end             
+	end
+
+	always @*
+	begin
+		bus_addr_next = bus_addr_reg;
+		bus_miso_next = bus_miso_reg;
+
+		bus_wren_next = 1'b0;
+		bus_mosi_next = bus_mosi_reg;
+
+		if (bus_ssel)
+		begin
+			bus_miso_next = q_b_wire;	
+			bus_addr_next = bus_addr;
+			bus_wren_next = bus_wren;	
+			if (bus_wren)
+			begin
+				bus_mosi_next = bus_mosi;
+			end
+		end
+	end
+
+	always @*
+	begin
+		int_wren_next = int_wren_reg;
+		int_addr_next = int_addr_reg;
+		int_data_next = int_data_reg;
+		int_case_next = int_case_reg;
+
+		case (int_case_reg)
+						
+			0:
+			begin
+				// write zeros
+				int_addr_next = int_addr_reg + 12'd1;
+				if (&int_addr_reg)
+				begin
+					int_wren_next = 1'b0;
+					int_case_next = 4'd1;
+				end
+			end	
+
+			1:
+			begin
+				int_wren_next = 1'b0;
+/*
+				if (&int_data_reg)
+				begin
+					int_case_next = 4'd0;
+				end
+				else if (frame & hst_good)
+*/
+				if (frame & hst_good)
+				begin
+					int_addr_next = hst_data;
+					int_case_next = 4'd2;
+				end
+			end
+
+			2:
+			begin
+				int_case_next = 4'd3;
+			end
+
+			3:
+			begin
+				int_case_next = 4'd4;
+			end
+
+			4:
+			begin
+				int_case_next = 4'd1;
+				if (~&q_a_wire)
+				begin
+					int_wren_next = 1'b1;
+					int_data_next = q_a_wire + 32'd1;
+				end
+			end
+
+			default:
+			begin
+				int_wren_next = 1'b0;
+				int_addr_next = 12'd0;
+				int_data_next = 32'd0;
+				int_case_next = 4'd0;
+			end
+		endcase
+	end
+
+	// output logic
+	assign	bus_miso = bus_miso_reg;
+	assign	bus_busy = 1'b0;
+endmodule
Index: trunk/MultiChannelUSB/oscilloscope.v
===================================================================
--- trunk/MultiChannelUSB/oscilloscope.v	(revision 104)
+++ trunk/MultiChannelUSB/oscilloscope.v	(revision 159)
@@ -130,10 +130,10 @@
 				if (bus_ssel)
 				begin
-					bus_miso_next = {ram_data[17:10], ram_data[8:1]};
+					bus_miso_next = ram_data[15:0];
 					ram_wren_next[0] = bus_wren;
 					if (bus_wren)
 					begin
 						ram_addr_next = bus_addr;
-						ram_data_next[0] = {bus_mosi[15:8], 1'b0, bus_mosi[7:0], 1'b0};
+						ram_data_next[0] = {2'd0, bus_mosi[15:0]};
 					end
 					else
@@ -183,5 +183,5 @@
 					ram_addr_next = ram_addr_reg + 20'd1;
 					ram_wren_next[0] = 1'b1;
-					ram_data_next[0] = {osc_data[15:8], 1'b0, osc_data[7:0], 1'b0};
+					ram_data_next[0] = {2'd0, osc_data[15:0]};
 		
 					int_case_next = 3'd3;
@@ -211,5 +211,5 @@
 				ram_addr_next = ram_addr_reg + 20'd1;
 				ram_wren_next[0] = 1'b1;
-				ram_data_next[0] = {osc_data_reg[31:24], 1'b0, osc_data_reg[23:16], 1'b0};
+				ram_data_next[0] = {2'd0, osc_data_reg[31:16]};
 				int_case_next = 3'd4;
 			end
@@ -219,5 +219,5 @@
 				ram_addr_next = ram_addr_reg + 20'd1;
 				ram_wren_next[0] = 1'b1;
-				ram_data_next[0] = {osc_data_reg[47:40], 1'b0, osc_data_reg[39:32], 1'b0};
+				ram_data_next[0] = {2'd0, osc_data_reg[47:32]};
 				int_case_next = 3'd5;
 			end
@@ -227,5 +227,5 @@
 				ram_addr_next = ram_addr_reg + 20'd1;
 				ram_wren_next[0] = 1'b1;
-				ram_data_next[0] = {osc_data_reg[63:56], 1'b0, osc_data_reg[55:48], 1'b0};
+				ram_data_next[0] = {2'd0, osc_data_reg[63:48]};
 				if (|int_cntr_reg[0])
 				begin
Index: trunk/MultiChannelUSB/shift.v
===================================================================
--- trunk/MultiChannelUSB/shift.v	(revision 159)
+++ trunk/MultiChannelUSB/shift.v	(revision 159)
@@ -0,0 +1,58 @@
+module shift
+	#(
+		parameter	shift	=	24, // right shift of the result
+		parameter	width	=	27, // bit width of the input data
+		parameter	widthr	=	12 // bit width of the output data
+	)
+	(
+		input	wire					clock, frame, reset,
+		input	wire	[5:0]			amp_data,
+		input	wire	[width-1:0]		inp_data,
+		output	wire	[widthr-1:0]	out_data
+	);
+
+	localparam	widthp	=	width + 6;
+
+	reg		[5:0]			amp_data_reg;
+	reg		[width-1:0]		inp_data_reg;
+	reg		[widthr-1:0]	out_data_reg;
+	wire	[widthr-1:0]	out_data_wire;
+	wire	[widthp-1:0]	mul_data_wire;
+															 
+	assign out_data_wire = mul_data_wire[shift+widthr-1:shift]
+		+ {{(widthr-1){mul_data_wire[widthp-1]}}, mul_data_wire[shift-1]};
+
+	lpm_mult #(
+		.lpm_hint("MAXIMIZE_SPEED=9"),
+		.lpm_representation("UNSIGNED"),
+		.lpm_type("LPM_MULT"),
+		.lpm_pipeline(3),
+		.lpm_widtha(width),
+		.lpm_widthb(6),
+		.lpm_widthp(widthp)) mult_unit (
+		.clock(clock),
+		.clken(1'b1),
+		.dataa(inp_data_reg),
+		.datab(amp_data_reg),
+		.result(mul_data_wire));
+
+	always @(posedge clock)
+	begin
+		if (reset)
+        begin
+			amp_data_reg <= 6'b0;
+			inp_data_reg <= {(width){1'b0}};
+			out_data_reg <= {(widthr){1'b0}};
+		end
+		else if (frame)
+		begin					
+			amp_data_reg <= amp_data;
+			inp_data_reg <= inp_data;
+			out_data_reg <= out_data_wire;             
+		end             
+	end
+	
+
+	assign out_data = out_data_reg;
+
+endmodule
Index: trunk/MultiChannelUSB/test_pll.v
===================================================================
--- trunk/MultiChannelUSB/test_pll.v	(revision 104)
+++ 	(revision )
@@ -1,145 +1,0 @@
-// megafunction wizard: %ALTPLL%
-// GENERATION: STANDARD
-// VERSION: WM1.0
-// MODULE: altpll 
-
-// ============================================================
-// File Name: test_pll.v
-// Megafunction Name(s):
-// 			altpll
-//
-// Simulation Library Files(s):
-// 			altera_mf
-// ============================================================
-// ************************************************************
-// THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE!
-//
-// 9.0 Build 132 02/25/2009 SJ Web Edition
-// ************************************************************
-
-
-//Copyright (C) 1991-2009 Altera Corporation
-//Your use of Altera Corporation's design tools, logic functions 
-//and other software and tools, and its AMPP partner logic 
-//functions, and any output files from any of the foregoing 
-//(including device programming or simulation files), and any 
-//associated documentation or information are expressly subject 
-//to the terms and conditions of the Altera Program License 
-//Subscription Agreement, Altera MegaCore Function License 
-//Agreement, or other applicable license agreement, including, 
-//without limitation, that your use is for the sole purpose of 
-//programming logic devices manufactured by Altera and sold by 
-//Altera or its authorized distributors.  Please refer to the 
-//applicable agreement for further details.
-
-
-// synopsys translate_off
-`timescale 1 ps / 1 ps
-// synopsys translate_on
-module test_pll (
-	inclk0,
-	c0);
-
-	input	  inclk0;
-	output	  c0;
-
-	wire [4:0] sub_wire0;
-	wire [0:0] sub_wire4 = 1'h0;
-	wire [0:0] sub_wire1 = sub_wire0[0:0];
-	wire  c0 = sub_wire1;
-	wire  sub_wire2 = inclk0;
-	wire [1:0] sub_wire3 = {sub_wire4, sub_wire2};
-
-	altpll	altpll_component (
-				.inclk (sub_wire3),
-				.clk (sub_wire0),
-				.activeclock (),
-				.areset (1'b0),
-				.clkbad (),
-				.clkena ({6{1'b1}}),
-				.clkloss (),
-				.clkswitch (1'b0),
-				.configupdate (1'b0),
-				.enable0 (),
-				.enable1 (),
-				.extclk (),
-				.extclkena ({4{1'b1}}),
-				.fbin (1'b1),
-				.fbmimicbidir (),
-				.fbout (),
-				.locked (),
-				.pfdena (1'b1),
-				.phasecounterselect ({4{1'b1}}),
-				.phasedone (),
-				.phasestep (1'b1),
-				.phaseupdown (1'b1),
-				.pllena (1'b1),
-				.scanaclr (1'b0),
-				.scanclk (1'b0),
-				.scanclkena (1'b1),
-				.scandata (1'b0),
-				.scandataout (),
-				.scandone (),
-				.scanread (1'b0),
-				.scanwrite (1'b0),
-				.sclkout0 (),
-				.sclkout1 (),
-				.vcooverrange (),
-				.vcounderrange ());
-	defparam
-		altpll_component.bandwidth_type = "AUTO",
-		altpll_component.clk0_divide_by = 5,
-		altpll_component.clk0_duty_cycle = 50,
-		altpll_component.clk0_multiply_by = 2,
-		altpll_component.clk0_phase_shift = "0",
-		altpll_component.compensate_clock = "CLK0",
-		altpll_component.inclk0_input_frequency = 20000,
-		altpll_component.intended_device_family = "Cyclone III",
-		altpll_component.lpm_hint = "CBX_MODULE_PREFIX=pll",
-		altpll_component.lpm_type = "altpll",
-		altpll_component.operation_mode = "NORMAL",
-		altpll_component.pll_type = "AUTO",
-		altpll_component.port_activeclock = "PORT_UNUSED",
-		altpll_component.port_areset = "PORT_UNUSED",
-		altpll_component.port_clkbad0 = "PORT_UNUSED",
-		altpll_component.port_clkbad1 = "PORT_UNUSED",
-		altpll_component.port_clkloss = "PORT_UNUSED",
-		altpll_component.port_clkswitch = "PORT_UNUSED",
-		altpll_component.port_configupdate = "PORT_UNUSED",
-		altpll_component.port_fbin = "PORT_UNUSED",
-		altpll_component.port_inclk0 = "PORT_USED",
-		altpll_component.port_inclk1 = "PORT_UNUSED",
-		altpll_component.port_locked = "PORT_UNUSED",
-		altpll_component.port_pfdena = "PORT_UNUSED",
-		altpll_component.port_phasecounterselect = "PORT_UNUSED",
-		altpll_component.port_phasedone = "PORT_UNUSED",
-		altpll_component.port_phasestep = "PORT_UNUSED",
-		altpll_component.port_phaseupdown = "PORT_UNUSED",
-		altpll_component.port_pllena = "PORT_UNUSED",
-		altpll_component.port_scanaclr = "PORT_UNUSED",
-		altpll_component.port_scanclk = "PORT_UNUSED",
-		altpll_component.port_scanclkena = "PORT_UNUSED",
-		altpll_component.port_scandata = "PORT_UNUSED",
-		altpll_component.port_scandataout = "PORT_UNUSED",
-		altpll_component.port_scandone = "PORT_UNUSED",
-		altpll_component.port_scanread = "PORT_UNUSED",
-		altpll_component.port_scanwrite = "PORT_UNUSED",
-		altpll_component.port_clk0 = "PORT_USED",
-		altpll_component.port_clk1 = "PORT_UNUSED",
-		altpll_component.port_clk2 = "PORT_UNUSED",
-		altpll_component.port_clk3 = "PORT_UNUSED",
-		altpll_component.port_clk4 = "PORT_UNUSED",
-		altpll_component.port_clk5 = "PORT_UNUSED",
-		altpll_component.port_clkena0 = "PORT_UNUSED",
-		altpll_component.port_clkena1 = "PORT_UNUSED",
-		altpll_component.port_clkena2 = "PORT_UNUSED",
-		altpll_component.port_clkena3 = "PORT_UNUSED",
-		altpll_component.port_clkena4 = "PORT_UNUSED",
-		altpll_component.port_clkena5 = "PORT_UNUSED",
-		altpll_component.port_extclk0 = "PORT_UNUSED",
-		altpll_component.port_extclk1 = "PORT_UNUSED",
-		altpll_component.port_extclk2 = "PORT_UNUSED",
-		altpll_component.port_extclk3 = "PORT_UNUSED",
-		altpll_component.width_clock = 5;
-
-endmodule
Index: trunk/MultiChannelUSB/usb_fifo.v
===================================================================
--- trunk/MultiChannelUSB/usb_fifo.v	(revision 104)
+++ trunk/MultiChannelUSB/usb_fifo.v	(revision 159)
@@ -5,5 +5,5 @@
 		input	wire			usb_full, usb_empty,
 		output	wire			usb_wrreq, usb_rdreq, usb_rden, usb_pktend,
-		output	wire	[1:0]	usb_addr,
+		output	wire			usb_addr,
 		
 		input	wire			clock,
@@ -116,5 +116,5 @@
 	assign	usb_wrreq = int_wrreq;
 	assign	usb_rden = int_rdreq;
-	assign	usb_addr = {1'b1, ~rx_ready};
+	assign	usb_addr = rx_ready;
 	assign	usb_data = int_wrreq ? int_tx_q : 8'bz;
 
Index: trunk/MultiChannelUSB/uwt_bior31.v
===================================================================
--- trunk/MultiChannelUSB/uwt_bior31.v	(revision 104)
+++ 	(revision )
@@ -1,116 +1,0 @@
-module uwt_bior31
-	#(
-		parameter	L	=	1 // transform level
-	)
-	(
-		input	wire			clock, frame, reset,
-		input	wire	[31:0]	x,
-		output	wire	[31:0]	d,
-		output	wire	[31:0]	a,
-		output	wire	[31:0]	peak,
-		output	wire	[1:0]	flag
-	);
-
-	localparam	index1		=	1 << (L - 1);
-	localparam	index2		=	2 << (L - 1);
-	localparam	index3		=	3 << (L - 1);
-	localparam	index4		=	index3 + 1;
-	localparam	peak_index	=	((index3 + 1) >> 1) + 2;
-	localparam	peak_shift	=	((L - 1) << 1) + (L - 1);
-	localparam	zero		=	32'h80000000;
-	
-	// Tapped delay line
-	reg		[31:0]	tap [index4:0];
-	
-	reg		[31:0]	d_reg, d_next;
-	reg		[31:0]	a_reg, a_next;
-	reg		[31:0]	peak_reg, peak_next;
-
-	reg		[31:0]	tmp1_reg, tmp1_next;
-	reg		[31:0]	tmp2_reg, tmp2_next;
-
-	reg				less_reg, less_next;
-	reg				more_reg, more_next;
-
-	reg		[1:0]	flag_reg;
-
-	integer			i;
-	
-	always @(posedge clock)
-	begin
-		if (reset)
-		begin
-			d_reg <= 0;
-			a_reg <= 0;
-			peak_reg <= 0;
-			flag_reg <= 0;
-			tmp1_reg <= 0;
-			tmp2_reg <= 0;
-			less_reg <= 1'b0;
-			more_reg <= 1'b0;
-
-			for(i = 0; i <= index4; i = i + 1)
-			begin
-				tap[i] <= 0;
-			end
-		end
-		else if (frame)
-		begin
-			d_reg <= d_next;
-			a_reg <= a_next;
-			peak_reg <= peak_next;
-			
-			tmp1_reg <= tmp1_next;
-			tmp2_reg <= tmp2_next;
-			less_reg <= less_next;
-			more_reg <= more_next;
-
-			flag_reg[0] <= (more_reg) & (~more_next);
-			flag_reg[1] <= (less_reg) & (~less_next);
-			
-			// Tapped delay line: shift one
-			for(i = 0; i < index4; i = i + 1)
-			begin
-				tap[i+1] <= tap[i];
-			end
-			
-			// Input in register 0
-			tap[0] <= x;
-		end
-	end
-	
-	always @*
-	begin
-		// Compute d and a with the filter coefficients.
-		// The coefficients are [1, 3, -3, -1] and [1, 3, 3, 1]
-
-		tmp1_next = tap[index3] + {tap[index2][30:0], 1'b0} + tap[index2];
-		tmp2_next = {tap[index1][30:0], 1'b0} + tap[index1] + tap[0];
-		
-		d_next = zero - tmp1_reg + tmp2_reg;
-		a_next = tmp1_reg + tmp2_reg;
-		
-		more_next = (d_reg > zero);
-		less_next = (d_reg < zero);
-
-/*		
-		d_next = zero - (tap[index3])
-			   - (tap[index2] << 1) - tap[index2]
-			   + (tap[index1] << 1) + tap[index1]
-			   + (tap[0]);
-		
-		a_next = (tap[index3])
-			   + {tap[index2] << 1} + tap[index2]
-			   + (tap[index1] << 1) + tap[index1]
-			   + (tap[0]);
-*/
-		peak_next = (tap[peak_index] >> peak_shift);
-	end
-
-	// output logic
-	assign	d		=	d_reg;
-	assign	a		=	a_reg;
-	assign	peak	=	peak_reg;
-	assign	flag	=	flag_reg;
-
-endmodule
