import numpy

''' user input parameters '''
file_name = 'Reference_5MHz_Sine_Ch1.bin'
newCSVfilename = 'generated_csv_file.csv'
num_channels = 32
adc_resolution = 12

''' Open file '''
f = open(file_name, "r")
data = numpy.fromfile(f, dtype=numpy.uint16)
f.close()

''' manipulate data '''
shifted_data=[]
for sample in data: # convert to 2s complement by subtracting the midcode (adc_resolution-1):
    shifted_data.append(sample-2**(adc_resolution-1))
num_samples = int(len(shifted_data)/num_channels)
shifted_data = numpy.array(shifted_data) # convert list to numpy array for reshape

samples = shifted_data.reshape(num_samples,num_channels) # Change single column of samples into matrix where each row is a new channel
# Transposing to match CSV format is not needed with this python script as shown in the matlab script for saving. To read data, transposing is needed as shown in line 28 of this script

''' Save matrix as csv '''
numpy.savetxt(newCSVfilename,samples,delimiter=',',fmt='%i')

''' Plotting first 100 pts of channel 1 '''
samples=samples.T

import matplotlib.pyplot as plt

plt.plot(samples[0])
plt.xlim([1,100])
plt.title('Time-domain Signal')
plt.xlabel('Sample #')
plt.ylabel('Codes')
plt.show()