% Write out Ramsey model to dynare .MOD file
% Assumes that rawfile, focmat, lmult_string, and lmult_initstr
% have been set by dynmod2sym and get_ramsey

% if there's no initval block to set the steady-state values of the
% endogenous variables, check for a _steadystate.m file. If so, set
% endinitline = 1.
if exist([infilename,'_steadystate.m'],'file') && endinitline == 0
    endinitline = 1;
else
    error('Need to declare steady-states in the .mod file or in a _steadystate.m file.')
end;

% Confirm that modline, ruleline, endruleline, and endinitline
% have been determined by dynmod2sym

if ~modline | ~endinitline | ~rulecount,
    error('Key line in input file not found (modline, ruleline, or endinitline)');
end;


% Open output file (assumes that outfilename has been set)

[outfid,msg] = fopen([outfilename,'.mod'],'w');

% Copy all lines of input file prior to "model" keyword

for iline = 1:(modline-1),
    fprintf(outfid,'%s \n',char(rawfile(iline)));
end;

% Declare lagrange multipliers as dynare endogenous variables
% and declare lagrange multiplier steady states as "parameters".

% If policy_problem = 'nash' or 'ramsey', we add Welf1 and Welf2 back as
% variables in the model.

delim = ', ';
endline = ' ';
if isempty(strmatch(policy_problem,'one_agent_ramsey'))
    lmultlist = vertcat(lmultlist,{'Welf1';'Welf2'});
end;

writelist(outfid,'var',lmultlist,delim,endline);

if welfare_correction_flag
    writelist(outfid,'var',{'Welfcorrection'},delim,endline);
end
%writelist(outfid,'parameters',lmss_list,delim,endline);

% Dynare 6: seed parameter values for preprocessor normalization.
% The steadystate function overwrites these at runtime.
fprintf(outfid,'\n%s\n','// Seed all parameter values for Dynare 6 preprocessor normalization.');
fprintf(outfid,'%s\n',['// Steadystate function overwrites at runtime via ',outfilename,'_paramfile.']);
eval([infilename,'_paramfile']);
for ipar = 1:size(parmat,1),
    parname = strtrim(deblank(parmat(ipar,:)));
    if ~isempty(parname)
        try
            fprintf(outfid,'%s\n',[parname,' = ',num2str(eval(parname),'%.15g'),';']);
        catch
        end
    end
end
% nbeta is set equal to the discount factor in the generated _paramfile,
% so the seed above would make nbeta = c1beta, causing Ramsey FOC equations
% of the form  lmultN - (c1beta/nbeta)*lmultN(-1)  to have a zero static
% Jacobian at the seed point.  Override to 0.5 so the preprocessor sees a
% non-zero Jacobian; the steadystate function restores the correct value.
fprintf(outfid,'%s\n','nbeta = 0.5;');
fprintf(outfid,'\n');

for iline = modline
    fprintf(outfid,'%s \n',char(rawfile(iline)));
end;


% Write out Ramsey FOCs
fprintf(outfid,'%s \n', '// Policymaker''s First-Order Conditions');

for ifoc = 1:length(focmat),
    fprintf(outfid,'%s \n',char(focmat(ifoc)));
end;

% Write out Correction term
if welfare_correction_flag
    fprintf(outfid,'%s \n', '// Welfare Correction Term');
    fprintf(outfid,'%s \n',char(correction));
    fprintf(outfid,'%s \n', '// Welfare Correction Term for the shadow file -- swap out after shadow file is created');
    fprintf(outfid,'%s \n',['// ',char(shadow_correction)]);
end

% Copy all lines from "model" keyword until first policy rule equation
for iline = modline+1:rulestartline(1),
    if strncmp('//Welf1 =',char(rawfile(iline)),8) | strncmp('//Welf2 =',char(rawfile(iline)),8)
        rawfile(iline) = cellfun(@(x) x(3:end), rawfile(iline), 'UniformOutput', false);
    end;
    fprintf(outfid,'%s \n',char(rawfile(iline)));
end;


% Copy input file lines (not including any other simple policy equations)
% prior to the end of the variable initialization block
startline = rulestopline(1) + 1;
for irule = 2:rulecount,
    stopline = rulestartline(irule);
    for iline = startline:stopline,
        fprintf(outfid,'%s \n',char(rawfile(iline)));
    end;
    startline = rulestopline(irule) + 1;
end;

% If endinitline was set to 1 above, then just print the new .mod file. If
% an initval block has been declared (which means that endinitline > 1),
% then write initial guesses for the Lagrange multipliers in the initval
% block and otherwise print the rest of the new .mod file as is.

if endinitline < 2,
    for iline = startline:length(rawfile),
        rawline = char(rawfile(iline));
        % Dynare 6: insert initval block for lmult variables before steady;
        % so normalization has non-zero Jacobian entries for FOC equations.
        if strncmpi(strtrim(rawline),'steady',6),
            fprintf(outfid,'initval;\n');
            for ilm = 1:length(lmultlist),
                lmname = char(lmultlist(ilm));
                if strncmp(lmname,'lmult',5),
                    fprintf(outfid,'%s = 1e-4;\n',lmname);
                end
            end
            fprintf(outfid,'end;\n\n');
        end
        fprintf(outfid,'%s \n',rawline);
    end;
    
    
else
    for iline = startline:(endinitline-1),
        fprintf(outfid,'%s \n',char(rawfile(iline)));
    end;
    
    % Write out initial guesses for Lagrange multipliers
    
    for ilm = 1:length(lmultlist),
        lmname = char(lmultlist(ilm));
        lmult_initstr = [lmname,' = 0;'];
        fprintf(outfid,'%s \n',lmult_initstr);
    end;
    
    % Write out "end" keyword for initialization block,
    % and then copy the rest of the input file
    
    for iline = endinitline:length(rawfile),
        fprintf(outfid,'%s \n',char(rawfile(iline)));
    end;
    
end;


fclose(outfid);

% save info regarding positions of behavioral equations
%save([deblank(outfilename),'_behaveq'],'behav_forward_looking_eqvec','behav_eqvec')