% segscript.m

%% This matlab script runs "segment" and reads the file dumps made by it
%%  IMAGE	-the original image
%%  start	-matrix of starting points 
%%		 (x-by-2, x = number of points)
%%
%% Written by Justin Romberg, Waqas Akram, & Charles Gamiz, May 1997.

function [R,E] = segscript(IMAGE, start, masklev)

[m, n] = size(start);
if (n ~= 2)
	disp('Starting-point matrix format is incorrect.');
	return;
end;

tic
disp('Please wait while we median filter ......');
filtIMAGE = medfilt2(IMAGE, [7 7]);
disp('Done with median filter.');
toc

% take the gradient of the median filtered image
[gx, gy] = gradient(filtIMAGE);
gradIMAGE = sqrt(gx.^2 + gy.^2);

% histogram equalize the gradient
gradIMAGE = gradIMAGE./(max(gradIMAGE(:)));
gradeqIM = histeq(gradIMAGE, 100);

% threshold and index then compute the mean and std intensity value
ind = find(gradeqIM >= .95);
IntThresh = mean(IMAGE(ind))
IntStd = std(IMAGE(ind))

file_out(start, 'start.ajw');
file_out(IMAGE, 'image.ajw');
file_out(gradeqIM, 'grad.ajw');

[x, y] = unix(['segment image.ajw grad.ajw start.ajw ',num2str(IntThresh,7),' ',num2str(IntStd,7),' ',num2str(masklev)]);

%unix('rm start.ajw');
%unix('rm image.ajw');
%unix('rm grad.ajw');
E = file_in('edge.ajw');
R = file_in('cell.ajw');
