
function [g,power] = GaussCoef(s,theta_s,phi_s,N,m)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%==========================================================================
%Calculates Schmidt-normalized spherical harmonic expansion coefficients
%for the monopole field model and the powerspectrum for input model m and
%maximum SH degree and order N 
%
%uses build-in Matlab Associated Legendre functions Pnm
%
%output1: Gauss coefficients - g
% g = (g_1^0; g_1^1; h_1^1; g_2^0; g_2^1; h_2^1; ... g_N^N; h_N^N) 
%
%output2: power spectrum - power
%calculated by the program powerspec.m by Nils Olsen
%
%
%test
% a   = 6371.2;
% g_1 = (1/a^2).*sum((s./a).^1.*m_r.*cosd(theta_s));
% g_11 = (1/a^2).*sum((s./a).^1.*m_r.*sind(theta_s).*cosd(phi_s));
% h_11 = (1/a^2).*sum((s./a).^1.*m_r.*sind(theta_s).*sind(phi_s));
% gg=[g_1;g_11;h_11]
% powerspec(gg)
%
%
% Author:
% Magnus Danel Hammer
% Master Thesis project 2011, Copenhagen University
%==========================================================================
disp('Calculate Gauss coefficients and power spectrum')
tic
m_mod = m;                                      %input model
a = 6371.2;                                     %Earth radius
cos_theta = cosd(theta_s);
g = [];
k = 0;
hwait=waitbar(0,'Please wait - Gauss coefficients');
for n = 1:N
        waitbar(n/N,hwait);
    for m = 0:n
        Pnm = legendre(n, cos_theta, 'sch')';   %Schmidt normialized 'sch'
        if m == 0
        k = k+1;       % terms corresponding to g_n^0
        g(k) = (1/a^2).*sum((s./a).^n.*m_mod.*Pnm(:,1));
        else
        k = k+1;       % terms corresponding to g_n^m        
        g(k) = (1/a^2).*sum((s./a).^n.*m_mod.*Pnm(:,m+1).*cosd(m.*phi_s));
        k = k+1;       % terms corresponding to h_n^m
        g(k) = (1/a^2).*sum((s./a).^n.*m_mod.*Pnm(:,m+1).*sind(m.*phi_s));
        end
    end 
end
close(hwait)

%Gauss coefficients
g = g';
disp('number of coefficients ')
coef_num = N*(N+2)

%power spectrum
power = powerspec(g);
toc
end
%==========================================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%












