% function [nstruct] = struct_reorder(ostruct, namecell)
% re-order the fields in a structure
% if a name in namecell does not exist in the old struct,
% it is added as an empty array
%
% see also built-in orderfields; it's almost the same, but 
% struct and cell array must contain the same field names.
% this function allows extra names in cell array.

function [nstruct] = struct_reorder(ostruct, namecell)
debug=0;
fno=fieldnames(ostruct);
fnn= namecell;


if debug ==1,
  fprintf('fields in old struct %d new struct %d\n', ...
    length(fno), length(fnn));
end 

for ii=1:length(fnn)
    fn=fnn{ii};

    if isfield(ostruct,fn)
        cmd=['nstruct.' fn ' =  ostruct.' fn ';' ];
    else
        cmd=['nstruct.' fn ' = [];'];
    end
    
    eval (cmd);
    
    if debug ==1,
      fprintf('cmd: %s\n', cmd);  
    end
    if debug ==2
        nstruct
    end
end
  
    
