function [best_magnitude, best_angle] = do_magic(image,reference,angles)
% function [ best_magnitude, best_angle] = do_magic(image,reference,angles)
%
% $Id: do_magic.m,v 1.4 2002/06/17 13:41:19 tobin Exp $

image_f = fft2(image);
rotations = length(angles);
disp(sprintf('  There will be %d rotations',rotations));
 
for rotation=1:rotations
    angle = angles(rotation);
    disp(sprintf('    Processing rotation number %d (%03.2f°)',rotation,angle));
    ref_rotated = imrotate(reference,angle,'bicubic','crop');
    ref_rotated_big = pad(ref_rotated,size(image),0);
    ref_rotated_f = fft2(ref_rotated_big);
    result_f = image_f .* ref_rotated_f;
    result = real(fftshift(ifft2(result_f)));
    if rotation == 1
        best_angle = ones(size(result));
        best_magnitude = result;
    else
        best_angle(result > best_magnitude) = angle;
        best_magnitude = max(best_magnitude,result);
    end
%    results(rotation,:,:) = real(fftshift(ifft2(result_f)));
end


    

