function liveFFT2()
% Little demo for live Fourier decomposition of a webcam image.
% Top left: input webcam image
% Bottom left: Fourier decomposition magnitude image
% Bottom right: Fourier decomposition phase image
% Top right: Inverse Fourier decomposition image reconstructed from bottom left, bottom right.
%
% Any questions, email james_tompkin@brown.edu
%

cam = webcam(1);
%cam.ColorEnable = 'off';
cam.Resolution = '320x240';
fftSize = 256;
offset = (320-fftSize)/2;

h = imshow( zeros(fftSize*2,fftSize*2) );

while true
    im = snapshot(cam);
    im = im2double( rgb2gray(im) );
    im = im(:, offset:offset+fftSize-1); % Crop image columns to 256
    im = imresize(im,[fftSize fftSize]); % Make it 256 by 256
        
    imFFT = fft2( im, fftSize, fftSize );
    
    % Deconstruct
    amplitude = sqrt( real(imFFT).^2 + imag(imFFT).^2 );
    phase = atan2( imag(imFFT), real(imFFT) );
    
    % Investigate how changes to the phase/amplitude affect the
    % reconstruction in here.
    %testIm = zeros(fftSize, fftSize) + 0.5; % Constant image
    %testIm = rand(fftSize, fftSize); % Random image
    %testFFT = fft2( testIm, fftSize, fftSize );
    %amplitude = sqrt( real(testFFT).^2 + imag(testFFT).^2 );
    %phase = atan2( imag(testFFT), real(testFFT) );
    
    % Reconstruct
    recReal = cos( phase ) .* amplitude;
    recImag = sin( phase ) .* amplitude;
    recC = recReal + 1j*recImag;
    rec = real( ifft2( recC ) );
    
    % Place different image parts together
    compositeTop = cat( 2, im, rec );
    compositeBottom = cat( 2, log(abs(fftshift(amplitude))) / 10, fftshift(phase) );
    composite = cat( 1, compositeTop, compositeBottom );
    
    % Update visual display
    set( h, 'CData', composite );
end

clear cam;

end