function [caYreg,caYclass] = ToyotaFeature_ApplyManyModelsToImage(InImage,caModel,resolution,ImgRange,N);
%function [caYreg,caYclass] = ToyotaFeature_ApplyModelToImage(InImage,caModel,resolution,ImgRange,N);
%
%objects are found that are 4 * the size of resolution

if(length(resolution) == 1), resolution = [resolution,resolution];, end
if(nargin < 4)
  ImgRange = 1;
end

nModels = length(caModel);

VERBOSE = 1;
if(VERBOSE),tic,end;

if(size(InImage,3) == 3)
  InImage = rgb2gray(InImage);
end

if(VERBOSE),fprintf('Sobel filtering...\n');,end
SIm = ApplySobelFilts(InImage);
if(VERBOSE),fprintf('Max filtering...\n');,end
SIm = maxfilter(SIm,5);
if(VERBOSE),fprintf('Resizing...\n');,end
SIm = imresize(SIm,size(InImage)/4,'bilinear');
for i = 1:nModels
  caYreg{i} = [];
  caYclass{i} = [];
end
%SIm = SIm * ImgRange;
for rowidx = 1:(size(SIm,1) - resolution(1) + 1)
  if(mod(rowidx,10) == 1),
    if(VERBOSE),fprintf('row %d of %d\n',rowidx,(size(SIm,1) - resolution(1) + 1));,end
  end
  X = Windowing_ImageStripToMatrix(SIm,resolution,rowidx);
  %if(exist('N'))
    %X = Normalize_Mtx_Apply(X,N);
    %X = outnormalizeDataX(X,N);
  %end
  for iModel = 1:nModels
    if(isSVMModel(caModel{iModel}))
      [yempl,yemp] = CLSosusvmC(X,caModel{iModel});
    end
    if(isBOOSTModel(caModel{iModel}))
      [yempl,yemp] = CLSgentleBoostC(X,caModel{iModel});
      yemp = yemp';
      yempl = yempl';
    end
    caYreg{iModel} = [caYreg{iModel};yemp'];
    caYclass{iModel} = [caYclass{iModel};yempl'];
  end
end

if(VERBOSE),fprintf('\nPadding output\n');,end
l = floor(resolution(2)/2);
t = floor(resolution(1)/2);
r = ceil(resolution(2)/2);
b = ceil(resolution(1)/2);
for i = 1:nModels
  caYreg{i} = padimage(caYreg{i},[l t b r],'replicate');
  caYclass{i} = padimage(caYclass{i},[l t b r],'replicate');
end
if(VERBOSE),fprintf('\nDone, total time is \n');,toc,end

function im_layers = ApplySobelFilts(crop)
filts{1} = [1,1,1;0,0,0;-1,-1,-1];
filts{2} = [-1,0,1;-1,0,1;-1,0,1];
filts{3} = [0,1,1;-1,0,1;-1,-1,0];
filts{4} = [1,1,0;1,0,-1;0,-1,-1];
filts{5} = [-1,-1,-1;-1,8,-1;-1,-1,-1];
filts{6} = [0,0,0;0,1,0;0,0,0];
s = size(crop);
im_layers = zeros(s(1),s(2),length(filts));
crop = im2double(crop);
for i = 1:length(filts)
  im_layers(:,:,i) = imfilter(crop,filts{i},'symmetric');
  if(i ~= 6)
    im_layers(:,:,i) = abs(im_layers(:,:,i));
  end
end

function b = isBOOSTModel(Model)
b = 1;
if(~isfield(Model,'Nrounds'))
  b= 0;
end
if(~isfield(Model,'featuresused'))
  b= 0;
end
if(~isfield(Model,'R'))
  b= 0;
end
if(~isfield(Model,'classifier'))
  b= 0;
end

function b = isSVMModel(Model)
b = 1;
if(~isfield(Model,'AlphaY'))
  b= 0;
end
if(~isfield(Model,'SVs'))
  b= 0;
end
if(~isfield(Model,'nSV'))
  b= 0;
end
if(~isfield(Model,'Parameters'))
  b= 0;
end

