%% Need to standardize each record - mainly to ensure that the varainces
% are similar, as the ANOVA will take care of the means 
load Ice_Locs
load timeline_ice
load Ice_Data_Matrix


Ice_Data_Normed_Matrix=NaN(size(Ice_Data_Matrix));


%Records [1,2,5,6,8,9,10,12,13,15] are complete from [1400 1974]. 
%Set means to zero and stds to 1 for these records over this interval:
prox_inds_long=[1,2,5,6,8,9,10,12,13,15];
prox_inds_short=setdiff(1:1:length(Ice_Locs(:,1)), prox_inds_long);

inds_nonan=find(isnan(sum(Ice_Data_Matrix(prox_inds_long,:)))==0);

for kk=1:1:length(prox_inds_long)
    Ice_Data_Normed_Matrix(prox_inds_long(kk),:)=(Ice_Data_Matrix(prox_inds_long(kk),:)-mean(Ice_Data_Matrix(prox_inds_long(kk),inds_nonan)))/std(Ice_Data_Matrix(prox_inds_long(kk),inds_nonan));
end

%for each of the others, find the intersection with the [1400, 1974] interval. Find
%the means and stds of the longs over this interval, take averages, and
%scale the record to these. 

for kk=1:1:length(prox_inds_short)
    inds_inter=intersect(find(isnan(Ice_Data_Matrix(prox_inds_short(kk),:))==0), inds_nonan);
    
    %get the means and stds for the long records over this interval.
    mean_scale=mean(mean(Ice_Data_Normed_Matrix(prox_inds_long,inds_inter),2));
    std_scale=mean(std(Ice_Data_Normed_Matrix(prox_inds_long,inds_inter),0,2));
    %and set the mean and std of the current record:
    Ice_Data_Normed_Matrix(prox_inds_short(kk),:)=(Ice_Data_Matrix(prox_inds_short(kk),:)-mean(Ice_Data_Matrix(prox_inds_short(kk),inds_inter)))/std(Ice_Data_Matrix(prox_inds_short(kk),inds_inter))*std_scale+mean_scale;
    

    [mean_scale, mean(Ice_Data_Normed_Matrix(prox_inds_short(kk),inds_inter))]
    [std_scale, std(Ice_Data_Normed_Matrix(prox_inds_short(kk),inds_inter))]
end


save Ice_Data_Normed_Matrix Ice_Data_Normed_Matrix
save Ice_Data_Normed_Matrix Ice_Data_Normed_Matrix -ASCII