%Tester for the sample MEX function fancy_func().
%
%Arash Kamangir, arash@kamangir.net
%
%Revision History
%
%  19 February 2010  - Initial Creation.
%
%  24 February 2010  - Minor revision of the documentation.

%Initialization of the Workspace
close all
clc
clear

disp('Code started...');

%Build the mex file.
try
    temp=fancy_func(0,0);
catch
    disp('Building the MEX file.');
    mex fancy_func.c
end

disp('Initialization...');
%Parameters
%Dimension of the matrices
H=1000;
W=1000;
%Precision used in the sanity check
PRECISION=10^-6;

%Input variables
A=rand(H,W);
B=rand(H,W);

%Do the operation
disp('Processing...');
t_MEX=cputime;
C=fancy_func(A,B);
t_MEX=cputime-t_MEX;

%Check
disp('Sanity Check...');
C_check=(A+B).*(A>B)+(B-A).*(A<B)+A*(A==B);
if ~isempty(find(abs(C-C_check)>PRECISION))
    disp(sprintf('\tError! Something went wrong. Call Arash.'));
else
    disp(sprintf('\tPassed.'));
end

%Stupid check
t_STUPID=cputime;
H=size(A,1);
W=size(A,2);
C_stupid=zeros(H,W);
for x=1:W
    for y=1:H
        %Get the elements
        a=A(y,x);
        b=B(y,x);
        %Do the fancy operation
        if (a>b)
            c=a+b;
        elseif (a<b)
            c=b-a;
        else
            c=a;
        end
        %Set the element
        C_stupid(y,x)=c;
    end
end
t_STUPID=cputime-t_STUPID;

%Report
disp(sprintf('Elapsed Time: Matlab - %dms, MEX - %dms',round(t_STUPID*1000),round(t_MEX*1000)));

%Done
disp('Done.');