function [dt, flops] = cofactor(A)

% Computes the determinant of A using the cofactor expansion. This version
% always expands along the first row. The veriable Flops returns the number 
% of flops in the computation.  First, it checks if A is square.

flops = 0;
[n,m]=size(A);
if n ~= m
    return
elseif n == 1
    dt = A(1,1);
else
    sign = 1;   % this is the (-1)^r part
    dt = 0;
    for j = 1:n
        % Form the minor matrix be removing the first row & jth column of A
        % (ie: this is the A1j matrix)
        if j == 1
            M = A(2:n,2:n);
        elseif j == n 
            M = A(2:n,1:n-1);
        else
            M = A(2:n,[1:j-1,j+1:n]);
        end
        % Make the recursive call to the determinant of the minor matrix
        [dt1,newflops]=cofactor(M);
        % Build the expansion along the first row
        dt = dt + sign*A(1,j)*dt1;
        % alternate the sign
        sign = -sign;
        % update flops by counting the adds & multiplications (not sign)
        flops = flops + newflops + 2;
    end
end