#!   /usr/bin/env	python
#    coding: utf8

import sys
import rr
import random
import time
import spi
import csr
import i2c
import gn4124
import fmc_adc

from pylab import *

if __name__ == '__main__':


    GN4124_CSR = 0x0
    
    addr_type = int(raw_input("decimal address -1 , hex addr - 2   : ")) & 0x3
    if addr_type == 2:
    	hex_input_start = raw_input("Enter a start address in hex : ")
    	dma_start = int(hex_input_start, 16) & 0b1111111111111111111111111
	hex_input_end = raw_input("Enter the end address in hex : ")
	dma_end = int(hex_input_end, 16) & 0b1111111111111111111111111
    else:
    	dma_start = int(raw_input("input start position : "))
	dma_end = int(raw_input("input end position : "))
 
    integer_plot = 1

    print "dma start address selected", dma_start
 
    # Objects declaration

    spec = rr.Gennum() # bind to the SPEC board
    gn4124 = gn4124.CGN4124(spec, GN4124_CSR)
    fmc = fmc_adc.CFmcAdc100ks(spec)
   
    fmc.stop_acq()    	        
    
    # Function in fmc_adc.py   
    pages_returned = fmc.dma_access(dma_start,dma_end)
    
    channels = []
    for j in range(len(pages_returned)):
    	for i in range(len(pages_returned[j])):
		channels.append(pages_returned[j][i] & 0xFFFFFFFF)

    #CONVERT FROM 2s COMPLIMENT
    if integer_plot==1:
   	    for i in range(len(channels)):
   		if(channels[i] & 0x8000):
   			channels[i] = -0x10000 + channels[i]
	    

    # Channels data kept in 32 bits so addr        
    channel1 = channels[0::8]
    channel2 = channels[1::8]
    channel3 = channels[2::8]
    channel4 = channels[3::8]
    channel5 = channels[4::8]
    channel6 = channels[5::8]
    channel7 = channels[6::8]
    channel8 = channels[7::8]
    time_base = arange(0,len(channel1),1 )	
	    
    # WRITE TO FILE
    file = open("adc_100k_acq.txt", 'w')
    for i in range(len(channel1)):
    	if integer_plot==1:        
		file.write("%5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d, %5d\n" % (time_base[i], channel1[i], channel2[i], channel3[i], channel4[i], channel5[i], channel6[i], channel7[i], channel8[i]))
	else:
		file.write("%5d, %5X, %5X, %5X, %5X, %5X, %5X, %5X, %5X\n" % (time_base[i], channel1[i], channel2[i], channel3[i], channel4[i], channel5[i], channel6[i], channel7[i], channel8[i]))
	        
    
    print '\nBye bye ...'
    sys.exit()
