function l = lung (im)
%  Does lung registration.  Returns an image with four labels :
%   2 lungs and two pieces above the shoulders.
%
%  l = lung (im)

first = min(min(im));
last = max(max(im)) / 2;


[m,n] = size(im);
threshold = min(min(im));
imt = ~thresh(im,threshold);
while sum(sum(imt)) < ((m*n) / 5)
  threshold = threshold + 0.01;
  imt = ~thresh(im,threshold);
end

threshold

numlabels=4;

while numlabels==4
  
  threshold = threshold + 0.005;  

  threshold       % print it out so we know whats going on (debug)

  imt = ~thresh(im,threshold);
    
  [imtl,numlabels] = group(imt);

  numlabels
 
%  if numlabels > 4        % later we will use a rating system based on
%     last = threshold;	  % more than just num of labels.
%   else			  % for now, we need this working though.
%     first = threshold;
%  end

end 
  
  threshold = threshold - 0.01;
  imt = ~thresh(im,threshold);
  [imtl,numlabel] = group(imt);

  l = label4(imtl);
  