function [Y,D] = map(C,X,V)
% MAP Finds maximum a posteriori labels for data
%
% Y = MAP(C,X) where C is the SDMaxEnt classifier object, and X is
% a feature image. Y are the labels.
  
% SDMAXENT.MAP
  
% Jerod Weinman
% jerod@acm.org
% (c) 2008

% $Id: map.m 1 2009-05-07 13:41:00Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2007, 2008, 2011
 
%    This file is part of Matlab SDMaxEnt.
%
%    Matlab SDMaxEnt is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    Matlab SDMaxEnt is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with Matlab SDMaxEnt.  If not, see <http://www.gnu.org/licenses/>.
  
  if nargin<3 || ~V
    V = 'same';
  else
    V = 'valid';
  end;
  
  szW = size(C.params.weights);
  sz = size(X);
  
  L = szW(4);
  H = szW(3);
  
  
  for c=1:L
	
	uu = 0;
	
	if ~(c==L) || anyv(C.params.weights(:,:,:,L))
	  for h=1:H
		uu = uu + conv2(X(:,:,h),C.params.weights(:,:,h,c),V);
	  end;
	end;
	
    if c==0
      B = zeros([size(uu) L]);
    end;
    
	B(:,:,c) = uu+C.params.bias(c);
	
  end;

  Y = argmax(B,3);

  if nargout>1
    D = ceil(get(C,'windowSize')/2);
  end;
  
