import struct
import numpy 


import matplotlib.pyplot as plt
 

SAMPLING_FREQ_ADDR_IN_BINARY_DATA = 72

def u2int16(val):
    if val & 0x8000:
        val = numpy.int16( numpy.uint16( val ) ^ numpy.uint16( 0xfffff ) + 1 )
    return val

def u2int16arr(arr):
    for i in xrange( len( arr ) ):
        arr[i]=u2int16(arr[i])
    return arr
 

def read_adc_samples( file ):
    
    try:
    
        with open( file, "rb") as fin:
            

            # header
            header=fin.read(512) 
            # get number of samples
            nsamples = struct.unpack("I",header[8:12])
            # unpack gives structure
            # integer (that is interesting) is stored in address 0
            # number of samples must be divided by number of channels
            nsamples = nsamples[0]/4

            # in order to know timescale i had to add information about sampling frequency to binary file
            # it is stred in uint32_t reserverd on byte 76
            sampling_freq = struct.unpack("I",header[ SAMPLING_FREQ_ADDR_IN_BINARY_DATA : SAMPLING_FREQ_ADDR_IN_BINARY_DATA+4 ] )
            if ( sampling_freq[0] == 0):
                print "Sampling frequency is not stored in given file."
                sampling_period = 1    
            else:
                sampling_period = 1e6 / sampling_freq[0];

            # read data from file
            d=numpy.fromfile(file=fin,dtype=numpy.uint16).reshape(nsamples,4)
            
            # helper vector
            samples_range=range(0,nsamples-1)
        
            # positive line is connected to ADC channel 0
            positive_samples = numpy.int16( u2int16arr( numpy.uint16( d[samples_range, 0] ) ) )

            # negative line is connected to ADC channel 1
            negative_samples = numpy.int16( u2int16arr( numpy.uint16( d[samples_range, 1] ) ) )
            
            transmission = numpy.int32( numpy.int32(positive_samples) - numpy.int32(negative_samples) );
            
            time = numpy.linspace(0, sampling_period*len(transmission),len(transmission))

            return [transmission, positive_samples, negative_samples, time ]

    except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
        print 'File containing ADC samples not found'
        return [ -1, -1, -1, -1]
    
    
def show(time, data):
    plt.plot( time, 1000.0*data/ 2.0**16)
        
    plt.ylabel("Signal [mV]")
    plt.xlabel("Time [us]")
    plt.show()
    
def show2(time, data, data2):
    if len(data) != len(data2):
        print "Data sets differ in length"
        return -1
    

    plt.plot( time, 1000.0*data/ 2.0**16, label = 'data1')
    plt.plot( time, 1000.0*data2/ 2.0**16, label = 'data2')
    plt.ylabel("Signal [mV]")
    plt.xlabel("Time [us]")
    plt.legend()
    plt.show()

