% this program is designed to induce yearly variability for the data after
% induced monthly variability by FFT using a simple linear relationship

function [yearly_corrected_precip]=yearly_precip_correction(monthly_corrected_precip)
% load the yearly precipitation after FFT
load('Pnew_precip');
P_FFT=Pnew_precip';

load(monthly_corrected_precip);

n=length(P_FFT); % years
m=length(monthly_corrected_precip);  % days

% calculate yearly precip 
% the fourth column of Y is precip
j=1;
Z=zeros(n,1);
for i=1:365:m
    Z(j,1)=sum(monthly_corrected_precip(i:i+365-1,4));
    %Z(j,1)=sum(gP(i:i+365-1,1));
    j=j+1;
end

% calculate the ratio of yearly precip between those after FFT and
% generated by weather generator
for i=1:n
    P_ratio(i,1)=P_FFT(i,1)/Z(i,1);
end
 
% extend the yearly precip ratio to daily scale,the data in each
% year are the same
P_extent=zeros(m,1);
j=1;
for i=1:365:m
    P_extent(i:i+365-1,1)=P_ratio(j,1);
    j=j+1;
end

% adjust the daily precip generated by WG using above ratios
P_adjust=zeros(size(monthly_corrected_precip));
P_adjust(:,1:3)=monthly_corrected_precip(:,1:3);
for i=1:m
    P_adjust(i,4)=monthly_corrected_precip(i,4)*P_extent(i,1);
end
yearly_corrected_precip=P_adjust;

mm=find(yearly_corrected_precip(:,4)<0);
yearly_corrected_precip(mm,4)=0;

save('yearly_corrected_precip','yearly_corrected_precip')

