
% Dynare to PerturbationAIM parser
% It generates a rough conversion. Some details need to be changed by hand.
% model file needs to have semicolumns denoting end of lines;
% if have a c++ comment, make it follow by "//;"
% Recall that subscripts don't work in mathematica i.e. L_a will be changed
% to LSUBa
% note that some names are incompatible with perturbationAIM e.g. N, won't
% be recognized as a variable
% best is to change it later manually (by search and replace)
% variables in perturbationAIM are in alphabetical order

disp(' ');
disp('This code translates your Dynare model into PerturbationAIM syntax');
disp(' ');
% gg=which('dynare');
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
filename=input('name of file : ','s');
filename=regexprep(filename,'\.mod','');
fname=filename;
filename=[filename,'.mod'];
% Run original to get some information;
eval(['dynare ',fname,' noclearall']); % this necessary only if you need to retrieve steady state and param values
steady_state=oo_.steady_state;
param_assign=[M_.param_names,repmat('->',length(M_.params),1),num2str(M_.params)];

model=(textread(filename,'%c','bufsize',1000000,'commentstyle','c++'));
model2=(strread(model','%s','delimiter',';'));




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% reading in endogenous variables

% modstrt=find_incell((model2),['var(?!\_)']);
% vary=[model(modstrt,:) ',']; 
% vary=regexprep(vary,'var','');
% zz=textscan(regexprep(vary,',',' '),'%s','endofline',' ');
% endonames=zz{1};
endonames0=str2cell(M_.endo_names);
namestmp=upper(endonames0);
[endonames,sortord]=sort(namestmp);
endonames=endonames0(sortord,:);
steady_state=steady_state(sortord);


% reading in shocks

% modstrt=find_incell((model2),['varexo(?!\_)']);
% varexo=[model(modstrt,:) ',']; % varexo=[varexo ',']
% varexo=regexprep(varexo,'varexo','');
% name_inno=varexo;

name_inno=str2cell(M_.exo_names);

for jj=1:length(name_inno);
    model2=regexprep(model2,['\<',name_inno{jj},'\>'],['eps[',name_inno{jj},'][t]']);
end

model=char(model2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the equation with breaks from your mod file

% model=(textread('three_country_oil4_real.mod','%c','bufsize',1000000,'commentstyle','c++'));
% model=char(strread(model','%s','delimiter',';'));

modstrt= find_incell(model2,'\<model');
modend=find_incell(model2(modstrt+1:end,:),'\<end')+modstrt;
% modend=modjunk(min(find(modjunk>modstrt)));
model2=model2(modstrt+1:modend-1,:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GET PARAMETER VALUES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try
% modstrt= strmatch('%parametervalues',model);
% modjunk=strmatch('%endparametervalues',model);
% modend=modjunk(min(find(modjunk>modstrt)));
% paramval=regexprep(str2cell(model(modstrt:modend,:)),'[@ #  "]|(include)','');
% paramval=cell2str(regexprep(regexprep(paramval,'(?<=\.).*',' '),'\.',''));
% % paramval=model(modstrt:modend,:);
% for kk=1:size(paramval,1);
%     eval([paramval(kk,:),';']);
% end
% catch
%     warning('No ''parametervalues'' delimiter. Consider entering parameter values block manually');
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% equate LHS to RHS here



nmod=size(model2,1);
dd=[];
model=[];
model=model2;
%     model=regexprep(model,';','');
    
%     model=regexprep(model,'(?<![\^\*\/\+\-\s])(\([\+\-][1-9]\))','');
for jj=1:5
     condrep=['(?<![\^\*\/\+\-\s])(\([\+][',num2str(jj),']\))'];
    model=regexprep(model,condrep,['\[t\+',num2str(jj),'\]']); 
    condrep=['(?<![\^\*\/\+\-\s])(\([\-][',num2str(jj),']\))'];
    model=regexprep(model,condrep,['\[t\-',num2str(jj),'\]']); 
    
end
  

% Note that functions must be replaced manually e.g.
model=regexprep(model,'\<exp\>','');

% contemporaneous variables 
for jj=1:size(endonames,1)
    model=regexprep(model,['\<',endonames{jj},'\>','(?![\[])'],[endonames{jj},'[t]']);
end
model=regexprep(model,'\=','\=\=');
%%%%%%%%%%%%%%%%%%%%
% WRITING FILE
model=regexprep(model,'\_','SUB');
param_assign=regexprep(str2cell(param_assign),'\_','SUB');
endonames=regexprep(endonames,'\_','SUB');
fid=fopen([fname,'_math.m'],'w+');
fprintf(fid,'%s\n','(*Mathematica model for Perturbation AIM*)');
fprintf(fid,'%s\n',sprintf('(*Created on %s *)',date));
fprintf(fid,'%s\n','(*------------------------------*)');
fprintf(fid,'%s\n','eqns={');
for jj=1:length(model)-1
    fprintf(fid,'%s\n',[model{jj},',']);
end
fprintf(fid,'%s\n',[model{end}]);
fprintf(fid,'%s\n','}')
logvars = ['{',regexprep(cell2str(endonames,0),'\[|\]',''),'}'];
fprintf(fid,'%s\n',['logvars=',logvars]);
fprintf(fid,'%s\n',['logrules = Map[#[x_]->E^(#[x])&, logvars]']);
fprintf(fid,'%s\n',['(* parameter values *)']);
fprintf(fid,'%s\n',['parametervals = {']);
for jj=1:length(param_assign);
   fprintf(fid,'%s\n', [param_assign{jj},',']);
end
    fprintf(fid,'%s\n', param_assign{jj});
fprintf(fid,'%s\n','}');

   fprintf(fid,'%s\n','(* substitute log transformation rules and parameter values into equations: *)');

fprintf(fid,'%s\n',['sgmodel = eqns /. logrules //. parametervals']);

fprintf(fid,'%s\n',['ssguess={' regexprep(cell2str(str2cell(num2str(steady_state)),0),'\[|\]',''),'}']);

fprintf(fid,'%s\n','AIMSS[sgmodel,AIMSSGuess->ssguess]');
fprintf(fid,'%s\n','(* Find the sixth-order approximation:');
fprintf(fid,'%s\n','AIMSeries[sgmodel,6]');
fprintf(fid,'%s\n','*)');

fclose(fid)


    