% Matlab program to test the simultaneously measuring on 2 channels,

clear all;
close all;
addpath ./bin;
%addpath('MAC');
addpath('WINDOWS');
%addpath('LINUX');
% if the program crashes with message "'g7play' is not recognized as an
% internal or external command" you should put g7play in the same directory
% as this program

NFT=2048; NF=NFT/2+1;
NFT=1024; NF=NFT/2+1;
Fs=48000; Ts=1/Fs;
Fmax=Fs/2; Fmin=Fs/NFT;
f=Fmin*(0:NF-1); t=Ts*(0:NFT-1);
G=0;

global V,G; V=struct( 'Fs',Fs, 'NFT',NFT, 'f',f, 't',t); 

%Basic parameters for g7play
Nmax=2^31-1;
Navg=32; %This must be a power of 2, for ola() to work!

%Generate chirp for left and right channels
fee=(0:NF-1)/(NF-1);
fee=(NFT/2)*pi*fee.*fee;
C=exp(-1i*fee);
%C=exp(i*fee); %Time reversed
c=fsst(C); %clear R fee;
c=0.999*c/max(abs(c)); %normalize to abs-peak less 0.1%
C=fast(c);

L=C; R=C; 
%zero out chirp harmonics by 2:1
%ke=1:2:length(f)-1; ko=2:2:length(f);
%L(ko)=0; %zero Even freqs (0, 2fmin, 4fmin, ....)
%R(ke)=0;   %zero Odd freqs (fmin, 3fmin, 5fmin, ....)
l=fsst(L); r=fsst(R);

%Scale data to int32 2^31-1 range
G=0.1;% set output
Gr=G; %Gr=0; %Overall gain
Gl=G; %Gl=0;
l=round(Gl*l*Nmax);
r=round(Gr*r*Nmax);
sprintf('Gains %d %d',l,r);

%save the data in files stim0 and stim1
fd=fopen('data/stim0','w');
N=fwrite(fd,l,'int32'); %Scale to Nmax (32 bit integer)
fclose(fd);
fd=fopen('data/stim1','w');
N=fwrite(fd,r,'int32'); %Scale to Nmax (32 bit integer)
fclose(fd);
delete('./data/resp*')%delete data/resp0 data/resp1, and any other saved responses

%for k=1:5 %Loop over measurement
k=1;

%Play chirps via the hand-held  (the main act!)
disp('chirp via handheld');
analog=sprintf('g7play -Q 0 -B %d -R0 data/stim0 -R1 data/stim1 -c0 data/resp0 -C1 data/resp1 -S %d ',Navg,NFT); 
% MAC %analog=sprintf('./g7play -Q 0 -B %d -R0 data/stim0 -R1 data/stim1 -c0 data/resp0 -C1 data/resp1 -S %d ',Navg,NFT); 

% each %d refers to the values after the string, Navg (number of blocks to
% be averaged) and NFT (discrete fourier transform length)
disp(analog); 
system(analog);
%/L (loopback options) - none, server, i2s 


rd1; %graphics


