function [cellbw,wat,minima,info] = segmctgrad(varargin)
% SEGMCTGRAD Segmentation of cytoplasmatically stained cells using gradient
% information and thereafter watershed segmentation
% 
% [CELLBW,WAT,MINIMA,INFO] = SEGMCTGRAD(II,DIAMLOW,DIAMHIGH) computes the 
% segmentation of IM and
% removing small cells below diameter DIAMLOW and DIAMHIGH


im = varargin{1};
% imini = im;
diamlow = varargin{2};
diamhigh = varargin{3};
% cprm = [];
% mprm = [];
% th = [];
% mprm.adaptfiltth = 0.01;
% th.intincell = 4;
for i = 4 : 2 : nargin
    
    namehere = varargin{i};
    varhere = varargin{i+1};
    switch(namehere)
        case('prmfile')
            prmfile = varhere;
        otherwise
            error('Wrong option')
    end;            
%     cmd = [namehere '=mergestruct(' namehere ',' varhere ')'];
%     evalc(cmd);
end;

dim = size(im);
ndim = numel(dim);
if numel(dim) == 2
    dim = [dim 1];
end;

im = imfilter(im,fspecial('gaussian',5,3));

if ndim == 2
    im = medfilt2(im,[3 3]);
else
    im = medfilt3(im,3,3,1);
end;

if dim(3) == 1
    [fx,fy] = gradient(im);
    fz = zeros(dim);
else
    [fx,fy,fz] = gradient(im);
end;

% absolute gradient
absgrad = sqrt(fx.^2 + fy.^2 + fz.^2);

% showall(imini,im,absgrad)
% no classification of cells in here!
cprm.classifyprm = 0;
[cellbw,wat,minkappa,minima,info] = segmsurfwat(absgrad,diamlow,diamhigh,'prmfile',prmfile,'cprm',cprm);


% classify cells using CT channel to know what is cell and what is
% background
cmd = prmfile;
[prmin,mprmin,cprmin,wprmin] = eval(cmd);
cprm = mergestruct(cprm,cprmin);
[cprm.th.numpixlow cprm.th.numpixhigh] = cellsize(diamlow,diamhigh,1,1,0.9,dim(3));
[cellbw,info.classifycells] = classifycells(wat,im,cprm.th);

% showall(im,wat,cellbw)
