function ltpdv_calc_btn(varargin)
% LTPDV_CALC_BTN called when one of the calculator buttons is pushed.
% 
% M Hewitson 22-04-08
% 
% $Id: ltpdv_calc_btn.m,v 1.1 2008/05/11 10:38:43 hewitson Exp $
% 

% Handles
myh     = varargin{1};
mainfig = varargin{end-1};
nins    = varargin{end};

% Get operation
op = get(myh, 'String');

% Get selected objects
objs = ltpdv_get_selected_objs(mainfig);
Nobjs = length(objs);

if Nobjs < nins
   error('### Please select two objects');
end

% check objects are all AOs
for j=1:Nobjs
   if ~isa(objs{j}, 'ao')
      error('### Please select only AOs for math calculations');
   end
end

% Loop over AOs
n   = 1;
res = {};
while n <= length(objs)   
   % operate on two objects
   switch nins
      case 1
         res = [res {feval(op, objs{n})}];
      case 2
         if isempty(res)
            res = feval(op, objs{n}, objs{n+1});
            n = n + 1;
         else
            res = feval(op, res, objs{n});            
         end
   end
   n = n + 1;
end

if nins == 2
   res = {res};
end

% Add this result to the object list
objs = getappdata(mainfig, 'LTPDAobjects');
if ~isempty(res)
   setappdata(mainfig, 'LTPDAobjects', [objs res]);
   % Refresh object list
   ltpdv_refresh_object_list(mainfig);
end


% END