function [EigVal, vect, D] = im2evec(imgFile, nvec)
% syntax:
%   [EigVal, vect] = im2evec(imgFile, outFile, nvec)
%
% description:
%   compute Eigenvectors and Eigenvalues using Intervening Contour on multiscalePb.
%
% REQUIRES Berkeley Segmentation Resources :
%
% http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/resources.html
%
% Pablo Arbelaez <arbelaez@eecs.berkeley.edu>
% March 2011
if nargin<2, nvec = 17; end
if nargin<3, outFile = ''; end


im = double(imread(imgFile)) / 255;
[tx, ty, nchan] = size(im);
orig_sz = [tx, ty];

%% mPb
[mPb] = multiscalePb(im);

%% eigenvectors and eigenvalues

[tx, ty] = size(mPb);

l{1} = zeros(size(mPb, 1) + 1, size(mPb, 2));
l{1}(2:end, :) = mPb;
l{2} = zeros(size(mPb, 1), size(mPb, 2) + 1);
l{2}(:, 2:end) = mPb;

% build the pairwise affinity matrix
[val,I,J] = buildW(l{1},l{2});
W = sparse(val,I,J);

[wx, wy] = size(W);
x = 1 : wx;
S = full(sum(W, 1));
D = sparse(x, x, S, wx, wy);
clear S x;

opts.issym=1;
opts.isreal = 1;
opts.disp=2;
[EigVect, EVal] = eigs(D - W, D, nvec, 'sm',opts);
clear W opts;

EigVal = diag(EVal);

EigVal(1:end) = EigVal(end:-1:1);
EigVect(:, 1:end) = EigVect(:, end:-1:1);

txo=orig_sz(1); tyo=orig_sz(2); 
vect = zeros(txo*tyo, nvec);
for v = 1 : nvec,
    rszEigVect = imresize(reshape(EigVect(:, v), [ty tx])',[txo,tyo]);
    vect(:,v)  = rszEigVect(:);
end

if ~strcmp(outFile,''), save(outFile,'EigVal', 'EVect'); end

