function [gainBestIndex, shapeBestIndex] = gsvecq( target, gainCodeBook, shapeCodeBook )
% function [gainBestIndex, shapeBestIndex] = gsvecq( target, gainCodeBook, shapeCodeBook )
%
% gain-shape vector quantization
%  
% target:        vector of size M to be quantized
% gainCodeBook:  vector of gain values
% shapeCodeBook: MxN Matrix of N shape vectors of size M

% Author:  Markus Hauenstein
% Date:    03.01.2002 
% Contact: www.markus-hauenstein.de

target = target(:);
targetSize = length(target);
if targetSize ~= size(shapeCodeBook,1),
  error( 'gsvecq: size of target vector does not correspond to size of shape code book' )
end

shapeCodeBookSize = size(shapeCodeBook,2);
gainCodeBookSize = length(gainCodeBook);
quality = zeros(shapeCodeBookSize,1);
mse = zeros(gainCodeBookSize,1);
 
for l=1:shapeCodeBookSize,
  energy = shapeCodeBook(:,l)' * shapeCodeBook(:,l);
  corr = target' * shapeCodeBook(:,l);
  if energy > 0,
     quality(l) = (corr * corr) / energy;  
  else
     quality(l) = 0.0;
  end
end
shapeBestIndices = find( quality == max(quality) );
shapeBestIndex = shapeBestIndices(1);

for l=1:gainCodeBookSize,
  tmp = target - gainCodeBook(l) * shapeCodeBook(:,shapeBestIndex);
  mse(l) = tmp' * tmp;
end;
gainBestIndices = find( mse == min(mse) );
gainBestIndex = gainBestIndices(1);
