function [seg,seg_val,c_lab]=region_split1(im,criterion,c_lab,seg_val)

% This function performs basic region splitting on an image.
%
% The input arguments are the following:
% im: The image to be segmented
% criterion: The value of the similarity criterion that is used to decide
% between splitting of segments or not.
% c_lab: Set this to the value of the FIRST label to be used (typically
% 1). It is primarily included because it is needed in the recursion
% seg_val: This is used in the recursions, set it to an empty matrix initially.
% 
% The output arguments are the following:
%
% seg: The final segmented image
% seg_val:  An image containing the values of the criterion for the
% different segments.  Also important for the recursions.
% c_lab: Used by the recursions.
%
% Copyright Lars Aurdal, The Norwegian Computing Centre
  
% Get size of input image

rows=size(im,1);
cols=size(im,2);

% Calculate homogeneity criterion to see if we should split

% tmp=var(im(1:(rows*cols))); % This is a varaiance criterion
 tmp=abs(max(max(im))-min(min(im))); % This is a homogeneity criterion

if ((tmp>criterion) & (rows>1) & (cols>1))
    
    % We want to split, calculate the split borders
    
    rows;
    cols;
    row_split=fix(rows/2);
    col_split=fix(cols/2);
    
    % Recurse
    
    [seg1,seg_val1,c_lab]=region_split1(im(1:row_split,1:col_split),criterion,c_lab,seg_val);
    [seg2,seg_val2,c_lab]=region_split1(im(1:row_split,(col_split+1):cols),criterion,c_lab,seg_val);
    [seg3,seg_val3,c_lab]=region_split1(im((row_split+1):rows,1:col_split),criterion,c_lab,seg_val);
    [seg4,seg_val4,c_lab]=region_split1(im((row_split+1):rows,(col_split+1):cols),criterion,c_lab,seg_val);
    
    % Accumulate result
    
    seg=[seg1 seg2;seg3 seg4];
    seg_val=[seg_val1 seg_val2;seg_val3 seg_val4];
    
else
    
    % No splitting is necessary, give this part of the segmented result
    % a unique label
    
    seg(1:rows,1:cols)=c_lab;
    seg_val(1:rows,1:cols)=tmp;
    c_lab=c_lab+1;
    
end