%Makes climatology of data according to the month
%Input has to have time as first dimension
%The output has same dimension of data_in
%data_mon is format 20101010
%method is 'clim' or something else
%FORMAT: [data_new,monthnum,std_new] = make_clim(data_in,data_mon,method)

function [data_new,monthnum,std_new] = make_clim(data_in,data_mon,method)

if nargin < 3, method = [];end

%ndays = [31 29 31 30 31 30 31 31 30 31 30 31];
[nmonths,incday] = size(data_mon);
allmonths = nan*ones(1,nmonths);
for i=1:nmonths
    aux_mon = str2num(data_mon(i,5:6));
    if isempty(aux_mon),continue;end
    allmonths(i) = str2num(data_mon(i,5:6));
end


if strcmp(method,'clim')
 for i =1:12
 acha = find(allmonths == i);
 monthnum(i) = i;
 data_aux = nanmean(data_in(acha,:,:),1);
 data_new(i,:,:) = data_aux(1,:,:);
 std_aux = nanstd(data_in(acha,:,:),[],1);
 std_new(i,:,:) = std_aux(1,:,:);             %standard deviation
 %std_new(i,:,:) = std_aux(1,:,:)/sqrt(length(acha));%standard error
 end
return 
end

data_new = zeros(size(data_in));
monthnum = zeros(1,incday);
std_new  = nan*ones(size(data_in));

for i =1:12
 acha = find(allmonths == i);
 monthnum(acha) = i;
 data_aux = nanmean(data_in(acha,:,:),1);
 data_new(acha,:,:) = data_aux(ones(1,length(acha)),:,:);
 std_aux = nanstd(data_in(acha,:,:),[],1);
 std_new(acha,:,:) = std_aux(ones(1,length(acha)),:,:);
end


%year =  str2double(data_mon(i,1:4));
%month = str2double(data_mon(i,5:6));
% if incday>6
%    day   = str2double(data_mon(i,7:8));
% end
%
%frac_month = month/13;
%frac_month_p = (month+1)/13;
%frac_day = (frac_month_p-frac_month)*day/(ndays(month)+1);
%new_data(i)=year + frac_month + frac_day;
%end
