function hpanel = getimscrollpanel(varargin)
%GETIMSCROLLPANEL Get image scrollpanel.
%   HPANEL = GETIMSCROLLPANEL(HIMAGE,FUNCTION_NAME,VARIABLE_NAME) returns the
%   imscrollpanel associated with HIMAGE. If no imscrollpanel is found,
%   GETIMSCROLLPANEL errors.
  
%   Copyright 1993-2004 The MathWorks, Inc.
%   $Revision: 1.1.8.1 $  $Date: 2004/08/10 01:50:10 $

iptchecknargin(3, 3, nargin, mfilename);
himage = varargin{1};
iptcheckhandle(himage,{'image'},mfilename,'HIMAGE',1)

function_name = varargin{2};
variable_name = varargin{3};

hScrollable = ancestor(himage,'uipanel');

% Not using ancestor here because of a possible HG bug.
% hpanel = ancestor(hScrollable,'uipanel') is returning hScrollable
hpanel = get(hScrollable,'Parent');  

% validate hpanel is a scrollpanel by checking hierarchy
if ~isempty(hpanel)

  kids = get(hpanel,'children');

  if numel(kids)~=4 
    hpanel = [];
    return
  end

  types = get(kids,'Type');
  if ~isequal(types,{'uipanel','uicontrol','uicontrol','uicontrol'}')
    hpanel = [];
    return
  end
  
  styles = get(kids(2:4),'Style');
  if ~isequal(styles,{'frame','slider','slider'}')
    hpanel = [];
    return
  end
  
  grandkid = get(kids(1),'children');
  if numel(grandkid)~=1 || ~strcmp('axes',get(grandkid,'Type'))
    hpanel = [];
    return
  end
  
  greatgrandkids = get(grandkid,'children');
  greatgrandkid_image = findobj(greatgrandkids,'Type','image');
  if numel(greatgrandkid_image)~=1 || greatgrandkid_image~=himage
    hpanel = [];
    return
  end

end

if isempty(hpanel)
    eid =  sprintf('Images:%s:invalidScrollpanel',function_name);
    error(eid,'Function %s expected %s to be in an IMSCROLLPANEL.',...
          upper(function_name),variable_name)
end