% EQUALZ.M - Equalizer script (EE 262 semester project)
%
%   Eddie Brown
%   Randy Dimmett
%   Almir Mutapcic
% 
%   Linear Systems II - EE 262
%   December 07, 1998
%
%   This script designs an equalizer for given room specs. 
%   The sound file is processed through the equalizer filter 
%   to counter and correct distortions produced in the sound 
%   wave due to the room's filering effects

% prepare workspace
close all; clear all;
format compact; clc;
disp(' Semester Project - Building an Equalizer');
disp('=----------------------------------------=');
disp(' ');

% input room filter filename
roomfile=input('Enter room file: ','s');
[cdout, fs]=wavread('CDOUT.WAV');

% impulse signal
t=[1:length(cdout)]/fs;
x=t*0;x(1)=1;
x=x/max(abs(x));
wavwrite(x,fs,16,'AMPIN.WAV');

run(roomfile)
roomf=abs(fft(y));

% Defining and adjusting frequency scale
N=length(roomf);
freq=[-N/2:(N/2)-1];
freq=freq*fs/N;

% defining equalizer
equalf=1./(roomf+0.003);

% passing cdout through equalizer filter
cdoutf=fft(cdout);
ampinf=cdoutf.*equalf;

ampin=real(ifft(ampinf));
ampin=ampin-mean(ampin);
ampin=ampin./max(abs(ampin));
wavwrite(ampin,fs,16,'AMPIN.WAV');

% presenting results (plots and sounds)
pick=0;
while(pick < 7)
   pick=menu('Pick a Plot',...
      'Frequency Response of Room',...
      'Frequency Response of Equalizer',...
      'DB Plot of Room and Equalizer',...
      'Spectagram Plot of CD ouput',...
      'Spectagram Plot of Equal output',...
      'Process the room fiter',... 
      'Quit');
   switch pick
   case 1
      figure
      plot(freq, fftshift(abs(roomf))); 
      title('Frequency response of the room')
      ylabel('Magnitude'); xlabel('Frequency (Hz)');
      zoom on; grid on;
   case 2
      figure
      plot(freq, fftshift(abs(equalf))); 
      title('Frequency response of the equalizer')
      ylabel('Magnitude'); xlabel('Frequency (Hz)');
      zoom on; grid on;
   case 3
      figure
      plot(freq, fftshift(20*log10(abs(equalf))),'r--'); hold on;
      plot(freq, fftshift(20*log10(abs(roomf)))); hold off;
      title('dB plot of the room and the equalizer')
      ylabel('Magnitude (dB)'); xlabel('Frequency (Hz)');
      legend('Equalizer','Room');
      zoom on; grid on;    
   case 4
      figure; specgram(cdout)
      title('Spectrogram of cdout signal')
   case 5
      figure; specgram(ampin)
      title('Spectrogram of ampin signal')
   case 6
      run(roomfile)
      spick=0;
      while(spick < 4)
      spick=menu('Room filter controls',...
      'Volume optimization',...
      'Sound CD output',...
      'Sound optimized speaker output (earin)',...
      'Back to the main menu');     	  
       switch spick
        case 1
           volume; 
           disp(' '); disp('Optimized volume is '), V
        case 2
          sound(cdout)
        case 3
          volume;
          sound(V*y)
        end
      end      
   end
end