function [] = add_welfare_vars(infilename)

var_block = 0;
add_to_param_block = 0;
model_block = 0;

outfilename = [infilename,'_withwelfarevars'];

% copy the .mod file, adding the welfare variables Util, Welf, Welf1, and
% Welf2 and their respective equations.


fin = fopen([infilename,'.mod'],'r');
fout = fopen([outfilename,'.mod'],'w');

while ~feof(fin)
    s = fgets(fin);
    if strncmp(s,'//',2) & ~strfind(s,'// auxiliary variables')
        fprintf(fout,'%s',s);
        
    elseif strncmp(s,'var ',4) & var_block == 0,
        var_block = 1;
        rest_of_line = s(5:end);
        
        f2in = fopen('template_for_welfarevar.m','r');
        while ~feof(f2in)
            s = fgets(f2in);
            fprintf(fout,'%s',s);
        end;
        fclose(f2in);
        
        fprintf(fout,'%s',rest_of_line);
    
    elseif strfind(s,'parameters ') & add_to_param_block == 0,
        add_to_param_block = 1;
        fprintf(fout,'%s',s);
        f3in = fopen('template_for_welfareparam.m','r');
        while ~feof(f3in)
            s = fgets(f3in);
            fprintf(fout,'%s',s);
        end;
        fclose(f3in);
        
    elseif strfind(s,'model;') & model_block == 0,
        
        model_block = 1;
        fprintf(fout,'%s',s);
        
        f4in = fopen('template_for_welfareblock.m','r');
        while ~feof(f4in)
            s = fgets(f4in);
            fprintf(fout,'%s',s);
        end;
        
        fclose(f4in);
        
    else
        fprintf(fout,'%s',s);
    end;

end;

% copy _ss_defs.m and _paramfile.m - these don't need to be edited. the
% steady state definitions for Util, Welf, Welf1, and Welf2 are in the
% original _ss_defs.m.

eval(['!copy ',infilename,'_ss_defs.m ',outfilename,'_ss_defs.m']);
eval(['!copy ',infilename,'_paramfile.m ',outfilename,'_paramfile.m']);

% copy the _steadystate.m file, replacing all mentions of infilename with
% outfilename.

f2in = fopen([infilename,'_steadystate.m'],'r');
f2out = fopen([outfilename,'_steadystate.m'],'w');


while ~feof(f2in)
    s = fgets(f2in);
    s = strrep(s,infilename,outfilename);
    fprintf(f2out,'%s',s);
end;