function p = getWaves(data, start, waves)

wavSize = 211; %Check for wavelengths up to 211 samples

sz = size(data,1); %Size of data



if start==1  %if at beginning of wave

   if waves==1 %if you're asking for only 1 wave

      p = firstZero(data); %return first zero

   else %Recurse correctly

      p = getWaves(data, firstZero(data), waves-1);

   end;

elseif (sz-start+1<2*wavSize-1) 

   %if you are too close to the end of the wave

   %return 1 more than size of array

   p = sz+1;

else

   z=zeros(0,0); %the indicies of the zeros of the wave

   valz=zeros(0,0); %the values of the dot-product at each zero

   sizez=0; %current number of zeros

   for k=35:wavSize,

      if ((data(start+k-1)<0) * (data(start+k)>=0)) %if positive slope zero

         sizez=sizez+1;

         z(sizez)=k; %store the zero

         valz(sizez)=sum(data(start:start+k-1) .* data(start+k:start+2*k-1))/k;

         %^store the dot-product

      end;

   end;

   [val,index] = max(valz); %determine the best match

   if waves==1 %if last recursive step

      p = z(index)+start;

   else %recurse another level

      p = getWaves(data, z(index)+start, waves-1);

   end;

end;



% This function simply locates the first positive slope zero crossing

% in the given array

function z = firstZero(signal)

for z=2:size(signal,1);

   if ((signal(z-1)<0) * (signal(z)>=0))

      break;

   end;

end;

