function [xhat, a, b] = DFT(x, M)
% Calculate the discrete fourier transform of x.
% Arguments: x is the vector of samples; 
%            M is how many points should be in the transform. 
% Results:   xhat is the there-and-back-again version of x
%            a is the list of cos coefficients
%            b is the list of sin coefficients
% Author: Jonathan Newnham
    if (exist('M')==0 || M <= 0)
        M = length(x)/2;
    end
    N=length(x); 
    n = 0:(N-1);
    m = 0:(M-1);
    w0 = 2 * pi / N;
    nm = n' * m * w0; % N by M matrix of n * m
    
    % perform discrete fourier transform
    a = 2 / N * x * cos( nm );
    b = 2 / N * x * sin( nm );
    % perform an inverse transform and return that as well
    xhat = -a(1)/2 + a * cos(nm') + b * sin(nm');
end