function yearly_tmax_correction(filenameout)

% this program is design to adjust the daily Tmax generated by WG using
% new yearly Tmax series produced by FFT. 

% load the yearly averaged Tmax after FFT
load('Pnew_tmax');
tmax_FFT=Pnew_tmax';

% load WG generated daily Tmax
load(filenameout);
[n,m]=size(gTmax);
gTmax=gTmax';
tmax_WG=reshape(gTmax,[],1);

n=length(tmax_FFT); % years
m=length(tmax_WG);  % days

% calculate yearly Tmax generated by WG, namely (Y)
j=1;
Z=zeros(n,1);
for i=1:365:m
    Z(j,1)=mean(tmax_WG(i:i+365-1,1));
    j=j+1;
end

% calculate the ratio of yearly Tmax between those after FFT and
% generated by weather generator
for i=1:n
    tmax_ratio(i,1)=tmax_FFT(i,1)-Z(i,1);
end

% extend the yearly Tmax ratio to daily scale,the data in each
% year are the same
tmax_extent=zeros(m,1);
j=1;
for i=1:365:m
    tmax_extent(i:i+365-1,1)=tmax_ratio(j,1);
    j=j+1;
end

% adjust the daily Tmax generated by WG using above ratios
tmax_adjust=zeros(size(tmax_WG));
for i=1:m
    tmax_adjust(i,1)=tmax_WG(i,1)+tmax_extent(i,1);
end
yearly_corrected_tmax=tmax_adjust;
save('yearly_corrected_tmax','yearly_corrected_tmax')
