function [res]=adaptivethresh(img,varargin)
%USAGE: adaptivthresh(img,sub_count=8)
% compute adaptive threshold on image with variable count of subsections.
%EXAMPLE: 
%Adaptive thresh in 4 regions adaptivethresh(img,4);
%Adaptive thresh in 8 regions adaptivethresh(img);

sub_count=8;

if length(varargin) == 1
 sub_count=varargin{1};
end

[height,width,depth]=size(img);
if (depth>1)
  img=rgb2gray(img);
  depth=1;
end

res = logical(zeros([height,width]));
   
for j = [0 : sub_count-1]
    y = height/sub_count*j;
    for i = [0 : sub_count-1];
        x = width/sub_count*i;
            sub = img(y + 1:y + height/sub_count , x + 1:x + width/sub_count);

            windowSize = 3; 
            hist = filter(ones(1,windowSize)/windowSize,1,double(imhist(sub)));
            derivace = abs(diff(diff(hist)));
            level=find(derivace == max(derivace));

            if (length(level)>1)
              level=max(level);
            end

            res(y + 1:y + height/sub_count , x + 1:x + width/sub_count)=im2bw(sub,level/255);
    end
end
