function out=get_tavg(var,name,diry,L);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function out=get_tavg(var,name,diry,L);
%
% Get the time average of a variable for a range of netcdf files.
%
% diry should be the directory where the netcdf files are located
% var is the name of the variable you want to get
%   both are stings
% L is the level if it is a 4D variable
% name = the search string, what the dir command looks for to pick out
% which files to loop through, i.e. *his*
%
%               Aaron J. Bever 23 June 2005
%                       modified July 2008
%                       modified June 2009
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin==3 | nargin==4
    Fname=dir([diry,name]);
else
    diry = pwd;
    diry = [diry,'/'];
    Fname=dir([diry,name]);
end

if (nargin < 4)
    out=[];
for j=1:length(Fname)
    disp(sprintf('file # %d',j))
    d=nc_varget([diry,Fname(j).name],var);
    p=size(d);
    if length(p)==4
        d=squeeze(mean(d,2));
    end
    out=[out;d];
    clear p d
end

p=size(out);
if length(p)==4
    out=squeeze(mean(mean(out,1),2));
else
    out=squeeze(mean(out,1));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% separating the part for getting the time average for a certain level of a
% 4D variable
else
    out=[];
for j=1:length(Fname)
    disp(sprintf('file # %d',j))
    S = get_varsize([diry,Fname(j).name],var);
    d=squeeze(nc_varget([diry,Fname(j).name],var,...
        [0 L-1 0 0],[S(1) 1 S(3) S(4)]));
    out=[out;d];
    clear p
end
    out=squeeze(mean(out,1));
end
