function cHStanArray = HStan(img, options)
%function cHStanArray = HStan(img, options)
%
%img is a grayscale image (one layer)
%cHStanArray is a cell array of hough-line-like features at increasing scales.

%Default Options
D.Verbose = 1;
D.ShowFigures = 1;
D.MaxIterations = 5;
D.CellSupportSize = 7;

if(nargin < 2), options = [];, end;
options = ResolveMissingOptions(options,D);

img = padimage(img,2);
imgxy{1}(:,:,1) = abs(imfilter(img,[-1 0 1]));
imgxy{1}(:,:,2) = abs(imfilter(img,[-1;0;1]));
imgxy{1} = unpadimage(imgxy{1},2);
cHStanArray{1} = HStanIteration(imgxy{1},options);
for i = 1:options.MaxIterations
  if(options.Verbose), fprintf('Iteration %d\n',i), end;
  cHStanArray{i} = HStanIteration(imgxy{i});
  mf{i}(:,:,1) = maxfilter(cHStanArray{i}(:,:,1),[1 3 1 3]);
  mf{i}(:,:,2) = maxfilter(cHStanArray{i}(:,:,2),[3 1 3 1]);
  imgxy{i+1} = mf{i}(1:2:end,1:2:end,:);
  if(options.ShowFigures)
    figure(i);
    imshow(FourLayerColor(cHStanArray{i},[]));
  end
end

function [output] = HStanIteration(input,options)
%function [output] = HStanModel(input,options)
%
%strengthens the continuous edges using a histogram and max strategy
%vertical edges are strengthened in layer 1, and horizontal in layer 2
d.CellSupportSize = 7;
if(nargin < 2), options = [];, end
options = ResolveMissingOptions(options,d);
input = NormalizeInput(input);
mask = ones(options.CellSupportSize,1);
l = floor(options.CellSupportSize / 2);  
r = ceil(options.CellSupportSize / 2);  
output(:,:,1) = -maxfilter(-input(:,:,1),[0 l 0 r]);
output(:,:,2) = -maxfilter(-input(:,:,2),[l 0 r 0]);

function x = NormalizeInput(x);
x = x - min(x(:)) + 10^-6;
x = x/max(x(:));
