%
%--------------------------------------------------------------------------
% function [radius] = FT_find_map_radius(map,varargin)
% 
% A function for Matlab which finds the maximum radius from a defined
% optical centre of a set of data from a mirror map.  The data defined as
% inside the map surface (i.e. not nan) should be roughly circular.  This
% function is designed to find the radius of the rough circular
% surface.  The default of the function is to find the maximum radius
% defined by the points inside the map surface, but there is the option to
% find the minimum map radius as defined by the nearest nan data point to
% the optical centre.
%
% map:      map containing the surface height data of the optical component
%           we want to find the radius of.
% varargin: optional input.
%           'max':  returns maximum radius defined by points inside the 
%                   mirror.
%           'min':  returns minimum radius defined by closest point to the
%                   centre defined as outside the mirror map.
%
% radius:   the returned radius of the map.
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    03.01.10
%--------------------------------------------------------------------------
%

% Description: estimates the radius of a mirror given a mirror map
% Keywords: radius, mirror, map

function [radius] = FT_find_map_radius(map,varargin)
  
    baseid='find_map_radius';

    % Check minimum or maximum radius.  Default is maximum
    if nargin==1
      rad = 'max';
    else
      if strcmp(lower(varargin{1}),'max')
          rad = 'max';
      elseif strcmp(lower(varargin{1}),'min')
          rad = 'min';
      else
          % Error message
          msgid=[baseid,':checkinarg'];
          result=sprintf(['Unknown option: ', varargin{1}, '.\n']);
          error(msgid,result);
      end
    end

    % find the row and column indices which are on the component surface
    if strcmp(rad,'max')
        [ridx,cidx]=find(map.notnan==1);
    else
        [ridx,cidx]=find(map.notnan==0);
    end

    % define x and y coordinates to start at the optical centre of the map
    X=cidx-map.x0;
    Y=ridx-map.y0;
  
    % define the radius of any point on the map
    R = sqrt(X.^2+ Y.^2);

    % find the radius
    if strcmp(rad,'max')
        radius=max(R);
    else
        radius=min(R);
    end
            
end

