% delay.m
%
% An implementation of a digital delay line in Matlab.
%
% by Gary Scavone, McGill University, 2015.

clear;

% Define the desired delay (in samples)
M = 5;

% Define the number of time steps to compute.
N = 30;

% Define our input signal.
x = [1, zeros(1, N-1)];  % unit impulse
%x = 1:N;                % or a ramp

% Allocate the delay-line and output buffers.  The delayline buffer
% itself can be longer than our delay value.
dLength = M + 50;
delayline = zeros(1, dLength);
y = zeros(1, N);        % output buffer

% Set the read and write pointer locations.
wptr = 1;               % write pointer
rptr = wptr - M;        % read pointer chases write
if rptr <= 0
  rptr = rptr + dLength;
end

for n = 1:N
  % Write the delay line input.
  delayline(wptr) = x(n);

  % Read the delay line output.
  y(n) = delayline(rptr);

  % Increment the pointer and check end conditions.
  rptr = rptr + 1;
  wptr = wptr + 1;
  if wptr > dLength, wptr = 1; end
  if rptr > dLength, rptr = 1; end
end

t = 0:N-1;
subplot(2,1,1)
stem( t, x )
grid
xlabel('Time (samples)');
title('Input Signal');
subplot(2,1,2)
stem( t, y )
grid
xlabel('Time (samples)');
title('Output Signal');
