function adapExcite = cradapex( subblockLength, ...
      adapGainIndices, adapVecIndices, adapGainCB, adapInputPast )
% function adapExcite = cradapex( subblockLength, 
%      adapGainIndices, adapVecIndices, adapGainCB, adapInputPast )
%
% Create an adaptive LPC-filter excitation signal
%
% subblockLength:     adapInputBlock is devided in subblocks of size subblockLength
% adapGainIndices:    vector containing adap gain indices (size: number of subblocks in adapInputBlock)		
% adapVecIndices      vector containing adap indices (size: number of subblocks in adapInputBlock)
% adapGainCB:	      codebook for quantization of adaptive gains
% adapInputPast:      old excitation of LPC filter
%  
% Author:  Markus Hauenstein
% Date:    05.01.2002 
% Contact: www.markus-hauenstein.de

if size(adapGainIndices) ~= size(adapVecIndices)
  error( 'cradapex: size of adapGainIndices and size of adapVecIndices do not fit' )
end

numberOfSubblocks = size(adapGainIndices);
blockLength = subblockLength * numberOfSubblocks;
adapExcite = zeros(blockLength,1) ; 
maxDelay = length(adapInputPast);

subblockIndex = 1 : subblockLength;

for j=1:numberOfSubblocks,
  bestAdapGainIndex = adapGainIndices(j); 
  bestAdapVecIndex = adapVecIndices(j);

  if bestAdapVecIndex <= maxDelay - subblockLength + 1;
    index = bestAdapVecIndex : bestAdapVecIndex + subblockLength - 1;
  else
    index1 = bestAdapVecIndex : maxDelay;
    missing = subblockLength - (maxDelay-bestAdapVecIndex+1);
    if missing > subblockLength/2,
      error( 'cradapex: cannot construct adaptive excitation' )
    end
    index2 = bestAdapVecIndex : bestAdapVecIndex+missing-1;
    index = [index1,index2];
  end

  adapExcite(subblockIndex) = adapGainCB(bestAdapGainIndex) * adapInputPast(index);

  subblockIndex = subblockIndex + subblockLength;   
end
