%
%--------------------------------------------------------------------------
% function [map] = FT_remove_elements_outside_map(map)
%
% A function for Matlab which finds the nan element closest to the centre 
% of mirror map and removes all the points outside this radial position.
% Effectivley zooming in on the valid mirror map data.
%
% map:  mirror map in the standard structure
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    03.05.2011
%--------------------------------------------------------------------------
%

% Description: Removes outer ring of NaN data from a mirror map
% Keywords: map, mirror, remove, data, nan

function [map] = FT_remove_elements_outside_map(map)

  % Find nan elements in map
  [ridx,cidx]=find(map.notnan==0);
  
  % Define x and y coordinates of nan points
  x=cidx-map.x0;
  y=ridx-map.y0;
  
  % Define radial coordinates
  r=sqrt(x.^2+y.^2);
  
  % Find the minimum radius - i.e. closest nan point
  radius=min(r);
  
  % Define x, y and radial coordinates for all the map data
  [rows,cols]=size(map.data);
  [X,Y]=meshgrid((1:cols)-map.x0,(1:rows)-map.y0);
  R=sqrt(X.^2+Y.^2);
  
  % Find all points outside the minimum radius
  outside=find(R>=radius);
  
  % Set these elements to nan 
  map.data(outside)=nan;
  D=2*radius;
  
  % Remove unnecessary points (nan points) outside the valid map grid.
  if D+2<rows && D+2<cols
    gridsize = round((ceil(D)+2)/2);
    x0 = round(map.x0);
    y0 = round(map.y0);
  
    new_data = map.data(y0-gridsize:y0+gridsize,x0-gridsize:x0+gridsize);
    map.data = new_data;
  end
  
  % Reassign nan values in map
  map.nan=isnan(map.data);
  map.notnan=not(map.nan);
  map = FT_recenter_mirror_map(map);

end

