function write_geo_params(in_fname, out_fname, varargin)
%WRITE_GEO_PARAMS Summary of this function goes here
%   Detailed explanation goes here

if nargin == 3
    if ~isstruct(varargin{1})
        error('In the three-argument mode the 3rd parameter must be a structure');
    end
    names = fieldnames(varargin{1});
    value_cell = struct2cell(varargin{1});
    values = [value_cell{:}];
elseif nargin >= 4
    if mod(nargin, 2) ~= 0
        error('Arguments must be name / value pairs');
    end
    names = varargin(1 : 2 : end);
    values = cell2mat(varargin(2 : 2 : end));
end
    
fid = fopen(in_fname, 'r');
if (fid < 0)
    error('Could not open input file: %s', in_fname);
end

% Scan the text
text = textscan(fid, '%s', 'Delimiter', '\n');
text = text{1};
fclose(fid);

% Replace the parameter definitions
n_params = numel(names);
for i_param = 1 : n_params
    name = names{i_param};
    value = values(i_param);
    def_pattern = sprintf('%s = DefineNumber[', name);
    line_idx = find(strncmpi(text, def_pattern, length(def_pattern)));
    if isempty(line_idx)
        error('Definition of parameter ''%s'' not found in input file', name);
    elseif numel(line_idx) > 1
        error('Definition of parameter ''%s'' is given in multiple lines', name);
    end

    text{line_idx} = sprintf('%s = DefineNumber[ %g, Name "Parameters/%s" ];', ...
        name, value, name);
end

% Write to the file
fid = fopen(out_fname, 'w');
if (fid < 0)
    error('Error opening output file %s', out_fname);
end
fprintf(fid, '%s\n', text{:});
fclose(fid);

end % of function write_geo_params
