## Copyright (C) 2023 Pantxo DIRIBARNE PD218333
##
## 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 <https://www.gnu.org/licenses/>.

## -*- texinfo -*-
## @deftypefn {} {@var{pos} =} tightPosition (@var{hax})
## @deftypefn {} {@var{pos} =} tightPosition (@var{hax}, @var{include_labels})
## Return the actual position of an axes object specified by its hand @var{hax}.
##
## The second facultative argument @var{include_labels} specifies whether the
## position rectangle, [x0, y0, widht, height], should include the axes labels. 
## @seealso{}
## @end deftypefn

function pos = tightPosition (hax, incl_labels = false)

  if (! isaxes (hax))
    error ("tightPosition: HAX must be an axes object handle")
  endif

  if (! (isscalar (incl_labels))
      || (! any (incl_labels == [0 1]) && ! islogical (incl_labels)))
    error ("tightPosition: expect 0, 1 or scalar logical value for INCL_LABELS")
  endif

  [pbam, pba, dam] = get (hax, {"plotboxaspectratiomode", ...
                                "plotboxaspectratio", ...
                                "dataaspectratiomode"}){:};

  ## Use absolute pixel coordinates
  pos = __get_position__ (hax, "pixels");

  if (strcmp (pbam, "auto") && strcmp (dam, "auto"))
    ## do nothing
  else    
    pbratio = pba(1)/pba(2);
    posratio = pos(3)/pos(4);

    if (pbratio != posratio)
      if (posratio < pbratio)
        tmp = pos(4);
        pos(4) = pos(3) / pbratio;
        pos(2) += (tmp - pos(4)) / 2;
      else
        tmp = pos(3);
        pos(3) = pos(4) * pbratio;
        pos(1) += (tmp - pos(3)) / 2;
      endif
    endif
  endif

  ## Translate pixels coordinates to correct units
  units = get (hax, "units");

  if (! strcmp (units, "pixels"))
    ## Need to make sure the actual position matches the position property
    ## otherwise tightinset may be wrong.
    outpos = get (gca, "position");
    set (gca, "units", "pixels", "position", pos, "units", units, ...
         "plotboxaspectratiomode", "auto");
    pos = get (gca, "position");
    ti = get (gca, "tightinset");
    set (gca, "position", outpos, "plotboxaspectratio", pba, ...
         "plotboxaspectratiomode", pbam);
  endif
  
  if (incl_labels)
    pos(1) -= ti(1);
    pos(2) -= ti(2);
    pos(3) += (ti(1) + ti(3));
    pos(4) += (ti(2) + ti(4));
  endif
  
endfunction

