function [answer] = computeAndSaveWaveletDecomp(oDir, periods, Phi64Lower48, ...
                                        emissionsLower48, emissionsPreds)
%computeAndSaveWaveletDecomp Decompose into wavelets and save to file
%   answer = computeAndSaveWaveletDecomp(oDir, periods, Phi64Lower48, ...
%                                       emissionsLower48, emissionsPreds) 
% Decomposes true and estimated emissions in the Lower48 states onto the
% chosen set of wavelet bases, plots them to screen, saves plot and saves
% the wavelet weights to file.
%
% INPUT:
%   oDir : Which dir do the plots and data files get saved
%
%   periods: Which 8-day periods are we interested in. Needed for filenames
%
%   Phi64Lower48: Wavelet bases, restricted to Lower48, but all 1031 bases
%   emissionsLower48 : True emissions, for Lower 48, for all periods
%   emissionsPreds : same as above, but estimated emissions.
%
%
% OUTPUT :
%  answer : struct containing the true and est wavelet coefficients
%
% Jaideep Ray, 1/8/2013
% -------------------------------------------------------------------------

% ---- Project each of the emissions onto bases and get weights.
for i = 1 : (periods(2) - periods(1) + 1)
    wtsTrue(:, i) = transpose(Phi64Lower48) * emissionsLower48(:, i) ;
    wtsEst (:, i) = transpose(Phi64Lower48) * emissionsPreds(:, i) ;
end

% ---- Plot the wavelets
figure() ;
plot(wtsTrue(:), 'or') ; hold on ; plot(wtsEst(:), '-b') ;
xlabel('8-day periods') ; ylabel('Wavelet coefficients') ;
title('Wavelet coefficients for true and estimated emissions') ;
legend('True emissions', 'Estimated emissions', 'Location', 'Best');
legend boxoff;

% ---- Save the plots
str = sprintf('WaveletCoeffs_P%02d-P%02d.jpg', periods(1), periods(2)) ;
fname = [oDir '/', str] ;
print('-djpeg', fname) ;

%% ---- Save the true waveletCoeffs
str = sprintf('/coeffsTrue_P%02d-P%02d.dat', periods(1), periods(2)) ;
filename = [oDir '/' str] ;

% Open the file, write out header
fprintf('Saving %s\n', filename) ;
fid = fopen(filename, 'w');
fprintf(fid, '# Period  Coeffs -->\n') ;
fclose(fid) ;

% Write out observations
save(filename, 'wtsTrue', '-ascii', '-append') ;

%% Save the reconstructed-values-of-wavelet-coeffs file. 

str = sprintf('/coeffsRecons_P%02d-P%02d.dat', periods(1), periods(2)) ;
filename = [oDir '/' str] ;

% Open the file, write out header
fprintf('Saving %s\n', filename) ;
fid = fopen(filename, 'w');
fprintf(fid, '# Period  Coeffs -->\n') ;
fclose(fid) ;

% Write out observations
save(filename, 'wtsEst', '-ascii', '-append') ;

%% Return
answer.wtsTrue = wtsTrue ;
answer.wtsEst  = wtsEst ;

end

