%--------------------------------------------------------------------------
% function [U_map,res_map,Rc] =
% FT_mirror_map_from_thermal_distortion(beam,mirror,r,option,num_terms)
%
% A function for Matlab which calculates the mirror surface map resulting
% from a mirror distorted thermally.  The function returns the map of the
% distortion, the radius of curvature of a Gaussian weighted approximation
% of the distortion and the difference (residual) between the distortion 
% and the best fit paraboloid of the distortion (characterised by the 
% radius of curvature).
%
% beam:         Structure storing beam parameters (see
%               FT_init_thermal_beam).
% mirror:       Structure containing mirror parameters (see
%               FT_init_thermal_mirror).
% r:            Radial coordinates [m]
% option:       'coating': for coating absorption
%               'bulk':    for bulk absorption
% num_terms:    Number of terms in approximation of thermal distortion.
%
% U_map:        Returned map of thermal distortion.
% res_map:      Residual map, the difference between the surface distortion
%               and the best fit paraboloid.
% Rc:           Radius of curvature of best fit paraboloid.
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    13.02.2012
%--------------------------------------------------------------------------
%

function [U_map,res_map,Rc] = FT_mirror_map_from_thermal_distortion(beam,mirror,r,option,num_terms)

    % Calculate 1D thermal distortion
    [U,c,p] = FT_thermal_distortion(beam,mirror,r,option,num_terms);
    
    % Setup map data
    rows = length(r);
    cols = length(r);
    
    % x-/y-axis
    x = r;
    y = r;
    
    % Into polar coordinates
    [X,Y] = meshgrid(r);
    R = sqrt(X.^2+Y.^2);
    theta = atan2(Y,X);
    
    % Calculate 2D thermal distortion
    U_data=FT_thermal_distortion(beam,mirror,R,option,num_terms);            
    
    % Calculate approximate paraboloid
    para_data = c*R.^2+p;
    
    % Set outside the mirror aperture to nan
    for i=1:rows
        for j=1:cols
            if R(i,j)>mirror.a
                U_data(i,j)=nan;
                para_data(i,j)=nan;
            end
            
        end
    end
    
    % Calculate residual
    res_data = U_data - para_data;
    
    % Map parameters
    type = 0;
    field = 0;
    xstep = x(2)-x(1);
    ystep = y(2)-y(1);
    scaling = 1e-9;
    
    % Radius of curvature
    Rc = 1/(2*c);
    
    % Rescale data (into nm)
    U_data = U_data/scaling;
    res_data = res_data/scaling;
    
    % Create thermal maps
    U_map = FT_new_surface_map('thermal_distortion',U_data,type,field,0,0,xstep,ystep,scaling);
    res_map = FT_new_surface_map('thermal_distortion_residual',res_data,type,field,0,0,xstep,ystep,scaling);
    
    % Recenter maps
    U_map = FT_recenter_mirror_map(U_map);
    res_map = FT_recenter_mirror_map(res_map);
            

end

