%--------------------------------------------------------------------------
% function [map_out,Rc_out] = FT_remove_zernike_curvatures_from_map(map,curvature)
%
% A Matlab function that preforms an inner product between a map surface 
% and particular Zernike polynomials, removing the resulting polynomials
% from the map surface.  The polynomials used here are the Zernike 
% polynomials defining mirror curvature, Z02, residual curvature, and
% Z-22 and Z+22, astigmatism.
%
% map:          The map surface from which the curvatures will be removed.
% curvature:    'all':          Astigmatism and residual curvature
%               'residual':     Just remove residual curvature (i.e. Z_0^2)
%               'astigmatism':  Just remove astigmatism
%
% map_out:      Returned map with curvatures removed
% Rc_out:       Equivalent curvature removed.  Set to 0 if just astigmatism
%               is being removed. 
% A:            Amplitudes of removed polynomials
% 
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    09.02.11
%--------------------------------------------------------------------------
%

function [map_out,Rc_out,A]=FT_remove_zernike_curvatures_from_map(map,curvature)
    
    % New map variables
    temp_map=map;
    map_out=map;
  
    % Map radius
    real_radius=map.xstep*FT_find_map_radius(map);
  
    [y,x]=size(map.data);
  
    % Prepare map for inner product
    temp_map=FT_recenter_mirror_map(temp_map);
  
    % Find the radius of the map (indices)
    r=FT_find_map_radius(temp_map);
   
    % Only perform convolution with elements within the unit disc
    [idx]=temp_map.notnan; 
    [rows,cols]=size(temp_map.data);
   
    % All curvatures have n = 2
    n=2;
  
    % Set values of m for different conditions
    if (strcmp(curvature,'residual'))
        mc=0;
    elseif (strcmp(curvature,'astigmatism'))
        mc=[-2 2];
    elseif (strcmp(curvature,'all'))
        mc=[-2 0 2];
    end
      
    A(1:length(mc))=0;
  
    % Perform convolution and remove polynomial from map surface for each
    % different curvature
    for i=1:length(mc)

        m=mc(i);
      
        % Make zernike function
        Z=FT_zernike_polynomial_for_grid(cols,rows,temp_map.x0,temp_map.y0,r,r,n,m);
  
        %-------------------------Convolution------------------------------
        c=sum(sum(Z(idx).*conj(temp_map.data(idx))));
        cn=sum(sum((Z(idx).*conj(Z(idx)))));
        c=c/cn;    
        %------------------------------------------------------------------
    
        A(i)=c;
    
        % Remove polynomial
        map_out=FT_remove_zernike_polynomial_from_map(map_out,n,m,c);
    
    end
  
    A=A*map.scaling;
  
    % Set radius of curvature that has been removed
    if (length(mc)~=2)
        if (length(mc)==1)
            A_rc=A(1);
        else
            A_rc=A(2);
        end
        R=real_radius;
        Rc_out=(4*(A_rc^2)+R^2)/(4*A_rc);
    else
        Rc_out=0;
    end
    
    
end