import struct
import numpy 


import matplotlib.pyplot as plt
 
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( filepath ):
        
    try:
    
        with open( filepath, "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
            
            # 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) );
            
            return [transmission, positive_samples, negative_samples ]

    except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
        print 'File containing acquired data not found'
        return [ -1, -1, -1]
    
    
def show(data):
    plt.plot(data)
    plt.show()
    

def show2(data, data2):
    if len(data) != len(data2):
        print "Data sets differ in length"
        return -1
    
    t = range( len( data ) )
    plt.plot(t, data , label = 'data1')
    plt.plot(t, data2, label ='data2' )
    plt.legend()
#     plt.legend(bbox_to_anchor=(0., 1.02, 1., .102))
#     , loc=3,ncol=2, mode="expand", borderaxespad=0.
    plt.show()
