% Newchorus.m .. make a chorus

global N Fs;
global DEL_ABS DEL_E DEL_HZ DEL_MIN DEL_MAX DEL_PH DEL_AMP;
global PIT_E PIT_HZ PIT_SWAMP PIT_PH PIT_AMP;
global VIB_HZ VIB_SWAMP VIB_PH VIB_AMP;
global DELAYS PITCHES VIBS;

Newinit;

%wav = make_input;

[wav,Fs,nbits] = getsound();
finwav = wav;  % solo
N = size(wav,1);
delwav = zeros(size(wav));
pitwav = zeros(size(wav));
vibwav = zeros(size(wav));
dbgsamp = zeros(N,1);

% let's divorce feedback flanging from chorus

chorusp = input('chorus (1) or flanger (0): ');


if chorusp
    
% delayS
for v = [1 2]  % here a set of voices
    for i = 1:N  % generating ith NEW sample
       sampind = NewDelay(i,v); % this is its adjusted 'index'
       if ((sampind < 1) | (sampind > N))
           break
       end
%        dbgsamp(i) = sampind; % just to check
        delwav(i,:) = interpolnd(wav, sampind);
    end
%    delwav = normwav(delwav,1); % they'll be in -1 1
    delwav= delwav * DELAYS(v, DEL_AMP); % final strength
    finwav = finwav + delwav;
    fprintf('\nDelay voice %d. Hit any key to listen:\n',v);
    pause
    wavplay(delwav,Fs);
    
end

% pitches
for v = [1]    
    for i = 1:N  % generating ith NEW sample
        sampind = Pitch(i,v); % this is its adjusted 'index'
       if ((sampind < 1) | (sampind > N))
           break
       end
%        dbgsamp(i) = sampind; % just to check
        pitwav(i,:) = interpolnd(wav, sampind);
    end
        pitwav = pitwav*PITCHES(v,PIT_AMP); % how loud?
        finwav = finwav + pitwav;        
 fprintf('\nPitch voice %d. Hit any key to listen:\n',v);
    pause
    wavplay(pitwav,Fs);
end

% vibs
for v = [2]    
    hz = VIBS(v,VIB_HZ);
     amp = VIBS(v,VIB_SWAMP);
     ph = VIBS(v,VIB_PH);
    for i = 1:N  % here we just modulate wav
         vibwav(i,:) = wav(i,:) * (1+ sin(ind2ang(i,hz, ph))*amp);
    end
     vibwav = vibwav * VIBS(v,VIB_AMP); % how loud?
      finwav = finwav + vibwav;        
 fprintf('\nVib voice %d. Hit any key to listen:\n',v);
    pause
    wavplay(vibwav,Fs);
end

% ugh.  always cascading here. really need to
% turn all this into function calls... sorry!
% if I get time...

pitwav = cascade(2,1,wav);   % pitch 2, vib 1
finwav = finwav+pitwav;  


disp('Chorus Done');
else
    
% a multi-stage flanger with feedback
% difference is we re-treat the output, not create
%new output each time and add it to the developing wave

delwav = wav;
newdelwav = wav;
for v = [4 5]    
    for i = 1:N  % generating ith NEW sample
       sampind = NewDelay(i,v); % this is its adjusted 'index'
       if ((sampind < 1) | (sampind > N))
           break
       end
%        dbgsamp(i) = sampind; % just to check
        newdelwav(i,:) = interpolnd(delwav, sampind);
    end
finwav = finwav + newdelwav;
delwav = finwav;   % ready for feedback or next stage
end

finwav = delwav;

disp('Flanger Done');

end

finwav = normwav(finwav,1.0);
putsound(finwav);



%clf
%plot(wav);
%hold on
%plot(finalwav);
%hold off
