function [var_out, SSout] = remove_seasonal_cycle_grided(var, sample_frequency ,window_size)

% var=T;
% sample_frequency=1;
% window_size=30;

%removes the seasonal cycle from the record var which is three dimensional
%sample_frequency is the number of samples per day
%window_size is the number of time points to average over

[NT, NN,N]=size(var);
display(['Time dimension is ', num2str(NT),'. If this is not correct, shiftdim so that the time dimesion is the first index'])


for n=1:N;tic; 
    for nn=1:NN
        for nt=1:365
            centertime=nt:365:NT+364; %all the indexes of a particular date in a record
            dot=zeros(0); %null matrix for the time domain
            %weight=zeros(0); %null matrxi for weights
            for y=1:length(centertime)
                dot=[dot   (centertime(y)-min([round(window_size/2) centertime(y)-1 NT-centertime(y)])):1:(centertime(y)+min([round(window_size/2) centertime(y)-1 NT-centertime(y)]))];
                %newdo=(centertime(y)-min([round(window_size/2) centertime(y)-1 NT-centertime(y)])):1:(centertime(y)+min([round(window_size/2) centertime(y)-1 NT-centertime(y)]));
                %newweight=1-abs(newdo-centertime(y))/(window_size/2);
                %if length(newweight) > 0
                 %   weight=[weight newweight];
                %end
                
                %clear newweight newdo
                
                %if the window extends out of the domain, truncuate the the
                %window symetrically about the center point for that yearonly
            end  %each year of record

            SS(centertime(find(centertime<=NT)),nn,n) = mean2(squeeze(var(dot,nn,n))); %define that value for each centerpoint in the record
            
            clear dot centertime weight
        end %day of the year
        
    end %latitude
    toc; display(['longitude ', num2str(n), ' completed']) 
end %longitude
toc
          
SSout=SS(1:365,:,:); %the output seasonal cycle
var_out=var-SS; %the output record with seasonal cycle removed

figure(1);clf;
plot(1:720, SS(1:720,nn,n), 'r', 1:720, var(1:720,nn,n), 'b')
        
