function [value,found]=getvaluefromdict(dict,key,defaultvalue)
%GETVALUEFROMDICT Get the value by the key from a dictionary
%
% Usage:
%   value=getvaluefromdict(dict,key,defaultvalue);
%   [value,found]=getvaluefromdict(dict,key,defaultvalue);
% dict is a cell array {'key1',value1,'key2',value2,...}
% The keys can repeat, then the warning is generated and only the last
% value is used.
% Output variable found==0 indicates that defaultvalue is used.
% See also: PARSEARGUMENTS, GETSUBDICT
%
% BSD License:
% Copyright (c) 2010, Nikolai G. Lehtinen (Email: nlehtinen at gmail.com)
% All rights reserved.
% 
% Redistribution and use in source and binary forms, with or without 
% modification, are permitted provided that the following conditions are 
% met:
% 
%     * Redistributions of source code must retain the above copyright 
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright 
%       notice, this list of conditions and the following disclaimer in 
%       the documentation and/or other materials provided with the distribution
%       
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
% POSSIBILITY OF SUCH DAMAGE.

if ~iscell(dict)
    error('Dictionary cell array expected');
end
if rem(length(dict),2)~=0
   error('Key-value pairs expected.')
end
n=length(dict)/2;
value=defaultvalue;
found=0;
for k=1:n
    ckey=dict{2*k-1}; cvalue=dict{2*k};
    if strcmp(ckey,key)
        if found
            disp(['WARNING: resetting value of ''' key '''']);
        end
        value=cvalue;
        found=1;
    end
end
