%Program to read in the data written by g7client

global G,V;

% Data to plot: stim0,1,resp0,1
fd=fopen('data/resp0'); c0=fread(fd,'int32'); fclose(fd);
fd=fopen('data/resp1'); c1=fread(fd,'int32'); fclose(fd);


Nmax=2^31-1;

c0=ola(c0,V.NFT); %overlap-add scaled data
c1=ola(c1,V.NFT); %overlap-add scaled data

C0=fast(c0);
C1=fast(c1);

h= figure(1);
h1 = subplot(221);
h2 = subplot(223);
h3 = subplot(222);
h4 = subplot(224);

rect = get(h,'Position'); rect(1) = rect(1) - rect(3)/2; rect(3) = 2*rect(3); set(h,'Position',rect);

%% Plot time and frequency responses from both channels
figure(1)
%subplot(221)
plot(h1,(0:V.NFT-1)*(1/V.Fs)*1000,c0/Nmax,'k','linewidth',1); %hold(gca,'off')
ylabel(h1,'Volts'); title(h1,'Voltage Waveform (Response Channel 0)'); xlabel(h1,'Time [ms]')
%subplot(223)
plot(h2,(0:V.NFT-1)*(1/V.Fs)*1000,c1/Nmax,'k','linewidth',1); %hold(gca,'off')
ylabel(h2,'Volts'); title(h2,'Voltage Waveform (Response Channel 1)'); xlabel(h2,'Time [ms]')
%subplot(222)
loglog(h3,f/10^3,abs(C0)/Nmax,'k') ;
title(h3,'Voltage Spectrum (Response Channel 0)'); ylabel(h3,'Volts')
xlabel(h3,'Frequency [kHz]'); set(h3,'ylim',[10^-4 10^2]);
%subplot(224)
loglog(h4,f/10^3,abs(C1)/Nmax,'k') ;
title(h4,'Voltage Spectrum (Response Channel 1)'); ylabel(h4,'Volts')
xlabel(h4,'Frequency [kHz]'); set(h4,'ylim',[10^-4 10^2]);

%% Plot the impedance
% Voltage divider - Z? + Rref in series. Z? is a unknown impedance - resistor, capacitor,
% loudspeaker, etc. 
% For the code below (C0=V1, C1 = V2), where we are assuming V1 and V2 are
% measuring across Z? (V2 is between Z? and Rref). You need to make sure
% your answer makes sense - the channels may easily be swapped by accident!

Rref=1e3; % voltage divider resistor

figure(2)
Zx=Rref*(C0./C1 -1); %% difference in channels?

subplot(211)
loglog(f/1000,abs(Zx),'b', 'linewidth',2);
title('Impedance Magnitude [Z = Rref*(V1/V2-1)]'); 
xlabel('Frequency [kHz]'); ylabel('|Z| [Ohm]')
grid on
subplot(212)
semilogx(f/1000,unwrap(angle(Zx))/pi,'b', 'linewidth',2);
title('Impedance Phase [Z = Rref*(V1/V2-1)]'); ylabel('\angle Z [Rad/\pi]')
xlabel('Frequency [kHz]'); 
grid on


