function rs = ispect_sg(instruct, outfile)

% iSPECT_SG Matweb matlab file for computing the spectrogram of a
% speech signal and sending it to the matlab web server.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
global siglen fixedfftlen;
fixedfftlen = 2048;
Fs = 10000; 
samplen = 1024;  % Length of the vowel samples being examined

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STAGE 1	Initialize the return string
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

rs = char('');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STAGE 2	Set directory for storage of graphic files
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Change working dir to temp dir on ACS machine
% NOTE: We won't make use of the Matweb variable MLDIR
tempdir = '/var/local/httpd/htdocs/matweb/tmp';

% Uncomment below when running script from a stand-alone test file
% tempdir = '/afs/athena.mit.edu/course/6/6.555/matweb/tmp';
cd(tempdir);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STAGE 3	Get HTML form input variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Get unique identifier (to form file name)
mlid = getfield(instruct, 'mlid');

% Show time signal? Field non-existent if box unchecked
try
   showtime = getfield(instruct, 'showtime');
catch
   showtime = '';
end

% Display magnitude in dB?
try
   showdB = getfield(instruct, 'showdB');
catch
   showdB = '';
end

try
  clrmap = getfield(instruct, 'colormap');
catch
  clrmap = '';
end

% Get upper frequency limit for display
upperflim = str2double(getfield(instruct, 'upperflim'));

% Display Spectrogram?
try
  showspecgram = getfield(instruct, 'showspecgram');
catch
  showspecgram = '';
end

% Get current plot's color
% $$$ ccolor = lower(getfield(instruct, 'ccolor'));

% Get saved plot's color
% $$$ scolor = lower(getfield(instruct, 'scolor'));

% Get standard parameters
[speechdir,speechdat,speechsamp,winlen,wintype,fftlen,overlap] = ...
    getParams(instruct);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STAGE 4	Perform MATLAB computations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[B,F,T] = compspecgram(speechdir, speechdat, winlen, ...
    wintype, fftlen, winlen/2, Fs);

B = 20*log10(B); % Always show spectrogram in dB


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generate graphics
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% axis for frequency windows

% frequency vectors
fixedincr = 1./(fixedfftlen-1);
fixedf = Fs*[0:fixedincr:1];

incr = 1./(fftlen-1);
f = Fs*[0:incr:1];


% Cleanup old jpegs
wscleanup('ml*spect_speech.jpeg',1); 
% Delete jpegs older than 1 hour
				     
fhandle_sg = figure('visible','off');

nrows = 2;
ncolumns = 1;
winindex = 1;

subplot(nrows,ncolumns,winindex);
%plot time signal
Ts = 1/Fs;
time = Ts*[0:1:siglen-1]; 
%load signal
eval(sprintf('sig = load(''%s/%s'');', speechdir, speechdat));
% Assign the signal to x
x = sig.source;
siglen = length(x);
Ts = 1/Fs;
time = Ts*[0:1:siglen-1]; 
plot(time,x);

% mark section that was analized in time and freq window
try
  eval(sprintf('sampbegin = sig.%s;', speechsamp));
catch
  sampbegin = sig.start;
end
sampend = sampbegin + samplen - 1;


ylabel('Speech signal (mV)');
xlabel('Time (sec)');
axis([time(1) time(end) 1.2*min(x) 1.2*max(x)]);

hold on;
% highlight and put bounds on the sample that is selected
plot(time(sampbegin:sampend), x(sampbegin:sampend), 'r');
taxis = axis;
plot([time(sampbegin) time(sampbegin)], [taxis(3) taxis(4)], 'r');
plot([time(sampend) time(sampend)], [taxis(3) taxis(4)], 'r');
%legend('Speech Signal', 'Selected Vowel', 0); %Removed because of bug

winindex = winindex + 1;

subplot(nrows,ncolumns,winindex);
% Plot spectrogram
imagesc(T,F,B);
axis xy;
if (strcmp(clrmap,'grey'))
  colormap(1-gray)
end
v = axis;
%axis([v(1:2) 0 upperflim]);
set(gca,'XAxisLocation', 'top');
ylabel('Frequency (Hz)');
%xlabel('Time (sec)');
cba = colorbar('horiz');
subplot(cba);
xlabel('dB');

%subplotmx(nrows, ncolumns);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STAGE 5	Put output variables in an output structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Render jpeg and write to file.
drawnow;
s.GraphFileName = sprintf('%sspect_speechsg.jpeg', mlid);
wsprintjpeg(fhandle_sg, s.GraphFileName);

close all;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STAGE 6	Call HTMLREP with output struct and output HTML
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Put name of graphic file into HTML template file.

templatefile = ...
      '/afs/athena/course/6/6.555/matweb/samp/ispect2_speechsg.html';

if (nargin == 1)
   rs = htmlrep(s, templatefile);
elseif (nargin == 2)
   rs = htmlrep(s, templatefile, outfile);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Subfunctions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% getParams(instruct) gets the values of standard variables from 
% the input structure
function [speechdir,speechdat,speechsamp,winlen,wintype,fftlen,overlap] ...
= getParams(instruct)

   % Get name of SPEECH file
   speechdir = getfield(instruct, 'speechdir');
   speechdat = getfield(instruct, 'speechdat');
   speechsamp = getfield(instruct, 'speechsamp');
   % Get window length
   winlen = str2double(getfield(instruct, 'winlen'));
   % Get window type
   wintype = lower(getfield(instruct, 'wintype'));

   % Get FFT length
   fftlen = str2double(getfield(instruct, 'fftlen'));
   overlap = str2double(getfield(instruct, 'overlap'));



