% Contact ythomas@csail.mit.edu or msabuncu@csail.mit.edu for bugs or questions 
%
%=========================================================================
%
%  Copyright (c) 2008 Thomas Yeo and Mert Sabuncu
%  All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are met:
%
%    * Redistributions of source code must retain the above copyright notice,
%      this list of conditions and the following disclaimer.
%
%    * Redistributions in binary form must reproduce the above copyright notice,
%      this list of conditions and the following disclaimer in the documentation
%      and/or other materials provided with the distribution.
%
%    * Neither the names of the copyright holders nor the names of future
%      contributors may be used to endorse or promote products derived from this
%      software without specific prior written permission.
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
%ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
%WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
%DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
%ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
%(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
%LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
%ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.    
%
%=========================================================================
%
% This function performs forward and inverse wavelet transform of the
% feature of MARS_sbjMesh (MARS_sbjMesh.data).
%
% The function
%           (1) Interpolates data of MARS_sbjMesh onto lat-lon grid
%           (2) Performs fast spherical harmonic transform using the yawtb and S2kit toolkits.
%           (3) In the spherical harmonic domain, perform convolution of data with
%               analysis filters to get wc.
%           (4) In the spherical harmonic domain, perform convolution of wc with
%               synthesis filters to get rc.
%
function [wc, rc] = WaveletTransformCurvature(MARS_sbjMesh, analysis_filters, synthesis_filters, checkBool)

% [analysis_outputs, synthesis_outputs] = WaveletTransformCurvature(MARS_sbjMesh, analysis_filters, synthesis_filters, checkBool)

if(nargin < 4)
   checkBool = 0; 
end

if(size(analysis_filters, 2) ~= size(synthesis_filters, 2))
   error('We expect analysis and synthesis filters to be of same bandwidth');
end

if(size(analysis_filters, 1) ~= size(synthesis_filters, 1))
   error('We expect the number of analysis and synthesis filters to be the same');
end


% Compute initials
num_filters = size(analysis_filters, 1);
BW = 1/2 *(-1 + sqrt(1+8*size(analysis_filters, 2)));

if( BW - round(BW) ~= 0)
   error('BW not correct!'); 
end

% Fast spherical harmonic transform on mesh
disp('Interpolate mesh data onto lat-lon grid');
mesh_data_s2kit = ResampleDataOntoS2kitGrid(MARS_sbjMesh, BW);

disp('Performing fast spherical harmonic transform of mesh coordinates');
mesh_yawtb_compatible = transpose(reshape(mesh_data_s2kit, BW*2, BW*2));
mesh_s2kit_coeffs = s2fst(double(mesh_yawtb_compatible));

if(checkBool)
    disp('================ Check that inverse spherical harmonic transform is invertible ================');
    mesh_yawtb_compatible2 = s2ifst(mesh_s2kit_coeffs);
     
    disp(['Imag Part of recon (should be 0): ' num2str(max(abs(imag(mesh_yawtb_compatible2(:))))) ', diff in real part of recon (should be non-zero): '  ...
        num2str(max(abs(mesh_yawtb_compatible2(:) - mesh_yawtb_compatible(:))))]);
end
mesh_harm_coefficients = ConvertS2kitFormat2MyFormat(mesh_s2kit_coeffs);
mesh_harm_coefficients = transpose(mesh_harm_coefficients); %code below expects a row vector.

% Convolve Mesh with analysis filters
disp('Wavelet Transform');
wc = zeros(size(analysis_filters));
for i = 1:num_filters
   wc(i, :) =  convolveSphere(transpose(mesh_harm_coefficients), transpose(analysis_filters(i, :)), 1);
end

% Convolve wavelet coeffs with synthesis filters
disp('Inverse Wavelet Transform');
rc = zeros(size(analysis_filters));
for i = 1:num_filters
    rc(i, :) =  convolveSphere(transpose(wc(i, :)), transpose(synthesis_filters(i, :)), 0);
end

% check invertibility
if(checkBool)
    
    disp('================ Check that Inverse Wavelet Transform is indeed invertible ================');
    disp(['Following should be close to 0 for invertibility: ' num2str(max(abs(sum(rc, 1) - mesh_harm_coefficients)))]);
   
    mat = ConvertMyFormat2S2kitFormat(transpose(sum(rc, 1)));
    mesh_s2kit_recon = s2ifst(mat);   
    mesh_yawtb_compatible = double(transpose(reshape(mesh_data_s2kit, BW*2, BW*2)));
    
    disp(['Imag Part of recon: ' num2str(max(abs(imag(mesh_s2kit_recon(:))))) ', diff in real part of recon (should be non-zero, but same as above):'  ...
            num2str(max(abs(real(mesh_s2kit_recon(:)) - mesh_yawtb_compatible(:))))]);
    
end







