%--------------------------------------------------------------------------
% function [zernike_map] = FT_create_zernike_polynomial_map(map,zc)
%
% A function for Matlab which creates a surface map from a sum of Zernike 
% polynomials with the same dimensions, scaling and other map properties 
% as the given map.  Ideal for comparing real and zernike maps. 
%
% map:          Original map 
% zc:           Structure containing amplitudes of particular zernike
%               polynomials
%
% zernike_map:  Returned map created from sum of Zernike polynomials
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    27.12.2009
%--------------------------------------------------------------------------
%

function [zernike_map] = FT_create_zernike_polynomial_map(map,zc)
    
    % From the size of the zernike amplitude matrix the zernike polynomial 
    % maximum index n can be found
    [N,I]=size(zc.amp);
    n_max=N-1;
    
    % Recenter map for correct value of x0 and y0 when creating zernike map
    map=FT_recenter_mirror_map(map);
    
    [rows,cols]=size(map.data);
    r=FT_find_map_radius(map);
    
    % Zernike map name
	basename=FT_remove_file_extension(map.name);
	mapname=sprintf('%s',basename,'_from_zernike_polynomials');
    
    data=0;
    
    % Calculate each zernike polynomial with the respective amplitude
    for n=0:n_max
        i=1;
        for m=-n:2:n
            Z=zc.amp(n+1,i)*FT_zernike_polynomial_for_grid(cols,rows,map.x0,map.y0,r,r,n,m);
            % Add all the surface heights specified by the polynomials
            data=data+Z;
            i=i+1;
        end
    end
    
    % Set points outside the surface to nan
	[nidx]=map.nan;
	data(nidx)=nan;
    
    % Make a map using the data and values from the original map
	zernike_map=FT_new_surface_map(mapname,data,map.type,map.field,map.x0,map.y0,map.xstep,map.ystep,map.scaling);


end