clear bitstream; % erase previous bitstream values;
WformOut = WformIn1 - mean(WformIn1); % offset the waveform to place the mean value at zero;
h = actxserver('LeCroy.WaveMasterApplication'); % establish ActiveX control between the scope and Matlab;
xincr = h.Math.F1.Out.Result.HorizontalPerStep; % sample resolution;
basefreq = double(get(h.Measure.P1.Operator.BaseFrequency,'Value')); % TIE frequency determination;
baseper = 1/basefreq;
samplesperbit = ceil(baseper/xincr);

n = find(diff(WformOut>0)); % locate position of edges on the NRZ data;
numberofedges = length(n);

bitcounter = 0; % initialize a bit counter;
virtualclockposition = n(1); 
numones = 0; % keep track of total number of ones identified;
numzeros = 0; % keep track of total number of zeros identified;
for i=1:(numberofedges-1)
	virtualclockposition = n(i); % set virtual clock to coincide with NRZ edge transitions;
	bitswide = round((n(i+1)-n(i))/samplesperbit); % determine how many bits occur between edges;

	for j=1:bitswide % for example if there are two zeros in a row between edges,execute this loop twice to check both bits;
		bitcounter = bitcounter + 1; % keep track of how many bits have been checked so far;

		if (WformOut(virtualclockposition + ceil(samplesperbit/2)) > 0) % the amplitude is high, this bit is a One;
			bitstream(bitcounter) = 1; % log the value of this bit as a zero or one for future reference;
			numones = numones + 1; % increment the total number of identified One values
		else
			bitstream(bitcounter) = 0; % the amplitude low, this bit is a Zero;
			numzeros = numzeros + 1; % increment the total number of identified Zero values;
		end
	end
end

%% SAVE BITSTREAM TO A FILE
disp('')
bitstream = char(bitstream+48) % convert values to ascii
outputfile = 'bitstream.txt';
fid = fopen(outputfile, 'w');
fwrite(fid,bitstream,'char');
fclose(fid);
fprintf('Stats: %d Bits, %d Ones, %d Zeros, output saved to %s\n', length(bitstream), numones, numzeros, outputfile);