% function [nstruct] = struct_trunc(ostruct, indx)
% sort and truncate a structure using indx AND MDAY
% mday is used to determine whether to sort on rows or
% columns

function [nstruct] = struct_trunc(ostruct, indx)

debug=0;
% use mday to figure out where to truncate 2d arrays
ntpts=length(ostruct.mday);

if debug ==1,
  fprintf('length mday %d length indx %d\n', ...
    npts, length(indx));
end

% get length of time param, for 2d arrays later
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
% removed this: don't sort unless one dim matches mday...
% if m ==1 | n ==1,
% this is a 1-d array
%       cmd=['nstruct.' field_name ' =  tetmpvar(indx);' ];
%       eval(cmd);
