function [nstruct] = struct_sort(ostruct, sortname)
% sort otruct fields based on ascending values of 
% 'sortname' - usually yearday or m-day. 
% Leaves single elements alone
% Works on 2-d fields too.
%
debug=0;
eval(['tempvar = ostruct.' sortname ';']);
[j,indx, j] = unique(tempvar); clear j

% get length of time param, for 2d arrays later
ntpts=length(tempvar);

% loop through all the fields in the structure
fno=fieldnames(ostruct);
for i=1:length(fno)
    field_name=fno{i};
    if debug ==1,
       fprintf('%s ',field_name); end
    cmd=['tempvar =  ostruct.' field_name ';' ];
    eval (cmd);
    [m,n]=size(tempvar);
    if debug ==1,
      fprintf(' size %d %d\n',n,m);  end
    if m == ntpts,
        % time is first dimension
        cmd=['nstruct.' field_name ' =  tempvar(indx,:);' ];
        eval(cmd);
    else
        if n == ntpts,
            % time is second dimension
            cmd=['nstruct.' field_name ' =  tempvar(:,indx);' ];
            eval(cmd);
        else
            % if no dimension matches time, don't sort
            cmd=['nstruct.' field_name ' =  tempvar;' ];
            eval(cmd);
        end
    end
end
