## Copyright (C) 2016 Pantxo Diribarne
## 
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*- 
## @deftypefn {Function File} {} impixelinfo (@var{h}) 
## @deftypefnx {Function File} {} impixelinfo (@var{input1}, @var{input2}) 
## @deftypefnx {Function File} {@var{retval} =} impixelinfo (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn

## Author: Pantxo Diribarne <pantxo@gre046552>
## Created: 2016-09-07

function hui = impixelinfo (h = [], h2 = [])
  him = [];
  if (isempty (h2))
    if (isempty (h))
      hf = hp = gcf ();
    elseif (! ishandle (h))
      error ("impixelinfo: H must be a graphics handle")      
    elseif (isfigure (h))
      hf = hp = h;
    elseif (ismember (get (h, "type"), {"axes", "uipanel", "image"}))
      hf = hp = ancestor (h, "figure");
    else
      error ("impixelinfo: H must me a handle to a figure, axes, uipanel or image");
    endif
    
    him = findobj (hf, "type", "image");
    if (isempty (him))
      error ("impixelinfo: no image to track")
    endif
  elseif (isfigure (h))
    hf = hp = h;
  elseif (strcmp (get (h, "type"), "uipanel"))
    hp = h;
    hf = ancestor (h, "figure");
  else
    error ("impixelinfo: H must me a handle to a figure, axes, uipanel or image");
  endif

  if (isempty (him))
    if (ishandle (h2))
      if (all (strcmp (get (h2, "type"), "image")))
        him = h2;
      else
        error ("impixelinfo: HIM must be a graphics handle to an image object");
      endif
    endif
  endif
    
  hui = uipanel (hf, "position", [0 0 1 0.05]);
  hc = impixelinfoval (hui, him);
  set (hc, "units", "normalized", "position", [0 0 1 1]);
  set (hf, "windowbuttonmotionfcn", {@motionfcn, hc});
endfunction

function motionfcn (h,d, hc)
  hasna = 1;
  data = getappdata (h, "__impixelinfodata__");
  for ii = 1:numel (data)
    [str, hasnan] = data(ii).coordfcn (get (h, "currentpoint"));
    if (! hasnan)
      break
    endif
  endfor
  set (hc, "string", ["Pixel info: " str])
endfunction