function  Kargs = keyargin(Vargs,defaults)

%KEYARGIN -- Utility for passing keyword arguments to M-functions.
%
% Kargs = keyargin(Vargs,defaults)
%
% This utility supports the transformation of &rest arguments into
% &keyword arguments (to use a Common Lisp convention).  The &rest
% arguments in Matlab are captured via the VARARGIN construct.
% The present function takes a list of keyword-value pairs ARGS
% and transforms it into a structure KARGS.
%
% For example, here's how one can define a funciton with two
% required arguments X and Y followed by &keyword arguments:
%   --- File MYFUN.M ----
%   function  v = myfun(x,y,varargin)    % function definition
%     defaults = struct('min',0,'max',100,'step',1) ;
%     Kargs = keyargin(varargin,defaults) ;
%     m = Kargs.min ; M = Kargs.max ; s = Kargs.step ;
%     ...
%   --- End file MYFUN.M ----
% Three &keyword arguments are thus implicitly defined: 'min', which
% defaults to 0; 'max', which defaults to 100; and 'step', deflt=1.
% One can then call MYFUN with &keyword syntax, for example:
%   v = myfun(x,y)                     % min=0, max=100, step=1
%   v = myfun(x,y,'step',3)            % min=0, max=100, step=3
%   v = myfun(x,y,'step',3,'max',120)  % min=0, max=120, step=3
% 
% VARGS is a cell array of keyword-value pairs captured by VARARGIN.
% DEFAULTS is a structure specifying the string keys and the 
% corresponding default values.
% KARGS is a structure with the same fields as DEFAULTS and with the
% same values for those arguments that are not supplied in VARGS.
%
% All string matches are case-sensitive. 
% An error is signalled if VARGS is badly formed or
% contains a string key that is not declared in DEFAULTS.
%
% See also VARARGIN, OPTIMSET.
% Matlab 7.4 (R2007a) introduced an inputParser class to handle args.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2004/11/22 12:00 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

%-- Start with DEFAULTS
Kargs = defaults ;

%-- Parse the list of keyword-value pairs and override defaults.
N = length(Vargs) ;
if (mod(N,2)~=0)  error('KEYARGS must come in pairs.') ; end
for k = 1:N/2
   key = Vargs{2*k-1} ;
   val = Vargs{2*k} ;
   if (~isstr(key))
      error('Each KEY must be a string.') ;
   elseif (~isfield(Kargs,key)) 
      error(['Key ''' key ''' is not defined.']) ; 
   else
      Kargs = setfield(Kargs,key,val) ;
   end
end

%--- Return KARGS
%%%%% End of file KEYARGIN.M