function [data_mon,std_mon,year_mon] = make_monthly_mean(datap,dias_ax8)
%This function calculates the monthly means of data

addpath('/data/mgoes/AX8/Time_transform/')
%disp('Toma cuidado, NAO INTERPOLA MAIS')
%sel_lat = lat_ax8(1,:);
%if nargin < 5, error('Enter sel_lat vector as argument 5'); end

[new_date] = month2yfraction(dias_ax8);
n_times = length(new_date);
as = find(size(datap) == n_times);

%sort data by year %CAREFULL IF YOU USE OTHER VARIABLES WITHOUT SORTING IT
   [~,ii] = sort(new_date); 
new_date  = new_date(ii); 
dias_ax8  = dias_ax8(ii,:);
%lat_new   = lat_ax8(ii,:);
%lon_new   = lon_ax8(ii,:);
if (as ==1)
    datap = datap(ii,:,:);
elseif (as==2)
    datap = datap(:,ii,:);
else
    datap = datap(:,:,ii);
end
%Define latitude to be plotted. WARNING: THERE ARE LAT=0 FOR NANs

% mon = [12 3:3:12];

 %For temperature and longitude
%     mnum = str2num(dias_ax8(:,5:6));
% for mi = 2:length(mon)
%     count = count +1;
%     ii = find((mnum>=mon(mi-1) & mnum<mon(mi)-1));
%     if isempty(ii), ii= find( mnum<mon(mi)-1 | mnum>=mon(mi-1) );end
% data_sea(:,count,:) = mean(datap(:,ii,:),2);
% std_sea(:,count,:) = std(datap(:,ii,:),0,2);
% lon_sea(count,:) = mean(lon_new(ii,:),1);
% end
year_i = str2num(dias_ax8(1,1:4));
year_l = str2num(dias_ax8(end,1:4));

%Monthly means
     mnum = str2num(dias_ax8(:,5:6));
     ynum = str2num(dias_ax8(:,1:4));
 count = 0;

for yi = year_i:year_l
 for mi = 1:12
   count = count+1;
%     yy = find(ynum == yi);
     ii = find(ynum == yi & mnum == mi);
     if isempty(ii),continue;end
      if (as ==1)
       data_aux = datap(ii,:,:);
 data_mon(count,:,:) = nanmean(data_aux,as);%datap(:,ii,:),2);
  std_mon(count,:,:) =  nanstd(data_aux,0,as);%(:,ii,:),0,2);
      elseif (as==2)
       data_aux = datap(:,ii,:);
 data_mon(:,count,:) = nanmean(data_aux,as);%datap(:,ii,:),2);
  std_mon(:,count,:) =  nanstd(data_aux,0,as);%(:,ii,:),0,2);
      else
       data_aux = datap(:,:,ii);
  data_mon(:,:,count) = nanmean(data_aux,as);%datap(:,ii,:),2);
  std_mon(:,:,count) =  nanstd(data_aux,0,as);%(:,ii,:),0,2);
     end

 if mi > 9
 year_mon(count,:) = strcat(num2str(yi),num2str(mi),'15');
 else
 year_mon(count,:) = strcat(num2str(yi),num2str(mi,'0%1.0f'),'15');
 end
% lon_mon(mi,:) = mean(lon_new(ii,:),1);
 end
end

return

