function changePar(fname,par,val,te)
%changePar(fname,par,val,te)
%fname = name of the bngl file
%par = {'par1' 'par2'}: names of the parameters as they appear in the bngl
%file
%val = [val1 val2]: values of the parameters
%te = final time (optional)

n = length(par);
fid = fopen(fname);

try
    %find the beginning and end of the parameters section
    cul = fgetl(fid);
    ind = 0;
    npar = [0 0];
    nl = 0;
    while cul > -1
        ind = ind+1;
        if ~isempty(strfind(cul,'begin parameters'))
            npar(1) = ind;
        end
        if ~isempty(strfind(cul,'end parameters'))
            npar(2) = ind;
        end
        cul = fgetl(fid);
        if isempty(cul)
            cul = 0;
        end
        nl = nl +1;
    end
    fclose(fid);
    
    parl = zeros(n,1);
    plin = cell(nl,1);
    
    fid = fopen(fname,'r');
    for j = 1:nl
        plin{j} = fgetl(fid);
        if j > npar(1)&&j < npar(2)
            cuc = strfind(plin{j},'#');
            for i = 1:n
                cui = strfind(plin{j},par{i});
                if ~isempty(cui)
                    if cui(1) < cuc
                        parl(i) = j;
                    elseif isempty(cuc)
                        parl(i) = j;
                    end
                end
            end
        end
    end
    fclose(fid);
    
    [parls,paris] = sort(parl);
    paris(parls == 0) = [];
    parls(parls == 0) = [];
    fid = fopen(fname,'w');
    cup = 1;
    
    for j = 1:nl
        if j == parls(cup)
            fseek(fid,0,'cof');
            cui = strfind(plin{j},'#');
            culnc = plin{j}(cui:end);
            culnp = par{paris(cup)};
            culnv = num2str(val(paris(cup)),'%0.5f');
            culn = ['    ',culnp, ' ', culnv,' ',culnc];
            %culn = regexprep(plin{j},'(\s)[\d,.,e,-,*,+,/]+',[' ',num2str(val(paris(cup)),'%0.5f')],'once');
            
            fprintf(fid,[culn,'\n']);
            cup = min(cup + 1,length(parls));
        elseif ~isempty(strfind(plin{j},'t_end'))&&nargin == 4
            culn = regexprep(plin{j},'t_end(\s*)=>(\s*)\d*\.*\d*',['t_end=>',num2str(te,'%0.5f')]);
            fprintf(fid,[culn,'\n']);
        else
            fprintf(fid,[plin{j},'\n']);
        end
    end
    
    
    fclose(fid);
    
catch
    fclose(fid);
end

