1function c = read_key_value_string(s)
2
3% Transforms a string of Key-Value options as returned by the preprocessor (for optim option in the
4% estimation command) into a cell (first column for the option name ans second column for the
5% option value).
6
7% Copyright (C) 2011-2017 Dynare Team
8%
9% This file is part of Dynare.
10%
11% Dynare is free software: you can redistribute it and/or modify
12% it under the terms of the GNU General Public License as published by
13% the Free Software Foundation, either version 3 of the License, or
14% (at your option) any later version.
15%
16% Dynare is distributed in the hope that it will be useful,
17% but WITHOUT ANY WARRANTY; without even the implied warranty of
18% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19% GNU General Public License for more details.
20%
21% You should have received a copy of the GNU General Public License
22% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
23
24i_opening_bracket = strfind(s,'(');
25i_closing_bracket = strfind(s,')');
26
27if ~isequal(length(i_opening_bracket),length(i_closing_bracket))
28    error('read_key_value_string: The number of opening and closing brackets does not match!')
29end
30
31%deal with sublists
32i_begin_sublist = strfind(s,'''(');
33i_end_sublist = strfind(s,')''');
34
35if ~isequal(length(i_begin_sublist),length(i_end_sublist))
36    error('read_key_value_string: Sublists could not be identified!')
37end
38
39iComma = strfind(s,',');
40
41%delete commata in sublists from further checks
42for sublist_iter=length(i_begin_sublist):-1:1
43    iComma(iComma>=i_begin_sublist(sublist_iter) & iComma<=i_end_sublist(sublist_iter))=[];
44end
45
46nComma = length(iComma);
47
48if iseven(nComma)
49    error('read_key_value_string: Wrong number of Key-Value pairs!')
50end
51
52c = cell((nComma+1)/2,2);
53
54for i = 1:nComma
55    j = comma2opt(i);
56    if j>0
57        continue
58    end
59    if isequal(i,1)
60        i1 = 1;
61        i2 = iComma(i)-1;
62    else
63        i1 = iComma(i-1)+1;
64        i2 = iComma(i)-1;
65    end
66    if isequal(i,nComma)
67        i3 = iComma(i)+1;
68        i4 = length(s);
69    else
70        i3 = iComma(i)+1;
71        i4 = iComma(i+1)-1;
72    end
73    c(-j,1) = {s(i1+1:i2-1)};
74    tmp = str2num(s(i3:i4));
75    if isempty(tmp)
76        if strcmp(s(i3:i3+1),'''(') && strcmp(s(i4-1:i4),')''') %sublist, delete brackets
77            c(-j,2) = {s(i3+2:i4-2)};
78        else
79            c(-j,2) = {s(i3+1:i4-1)};
80        end
81    else
82        c(-j,2) = {tmp};
83    end
84end
85
86
87function j = comma2opt(i)
88if isodd(i)
89    % The comma is a separator between a Key and a Value (returned j is minus the option number).
90    j = - (i+1)/2;
91else
92    % The comma is a separator between two options (returned j is the option number).
93    j = i/2;
94end