% replace initial value in priors block
clear all
namemodel=input('give name of model file with extension : ','s');%'nawm_fin_linear.mod';
modeltext=textread(namemodel,'%s','commentstyle','c++','bufsize', 1000000, 'delimiter',';');
[xx,othcom]=find_incell(modeltext,'^\%');
uncom=setdiff([1:size(modeltext,1)]', othcom);
modeltext=modeltext(uncom,:);
tmp=regexp(namemodel,'\.');
fname=namemodel(1:tmp-1);

modmean=input('USE MEAN OR MODE (0=mode[default],1=mean) :');
if ~exist([namemodel(1:tmp-1),'_mean.mat'],'file');
    modmean=0;
    disp('No mean file: using mode ');
end
if modmean==1;
 
eval(['load ',namemodel(1:tmp-1),'_mean.mat']);
xmean=xparam1;
   
else
eval(['load ',namemodel(1:tmp-1),'_mode.mat']);
xmode=xparam1;
    
end


ff=[];
para=[];
zz=1;
strt=find_incell(modeltext,'estimated\_params');
endst=find_incell(modeltext(strt:end,:),'\<end\>')+strt-1;
gg=modeltext(strt+1:endst-1,:);
names=[];
for jj=1:size(gg,1);
    k=regexp(gg{jj},['(\,)']);
    if ~isempty(k)& length(k)>3;
    ff{zz,1}=[gg{jj}(1:k(1)),num2str( xparam1(zz),8),gg{jj}(k(2):end),';'];
    para{zz,1}=[gg{jj}(1:k(1)-1),'=',num2str( xparam1(zz),8),';'];
    names{zz,1}=[gg{jj}(1:k(1)-1)];
%    ff{zz,1}=[gg{jj}(1:k(1)),'',gg{jj}(k(2):end),';'];
%    ff{zz,1}=regexprep(ff{zz,1},',,',',');
    zz=zz+1;
    end
end

disp(char(ff))

%%%%%%%%%%%%%%%%%%%% table of results

if exist(fname,'dir')
    curd=pwd;
    cd([fname,'/metropolis'])
    
    [gg]=ls;
    files=strread(gg,'%s');
    [xx,kk]=find_incell(files,[fname,'\_mh[1-9]+']);
    metrexp=files(kk,:);
    
    alldat=[];
    for jj=1:length(kk);
        tmp=load(metrexp{jj});
        alldat=[alldat,tmp.x2'];
    end
    cd(curd);
    upperp=prctile(alldat',95);
    lowerp=prctile(alldat',5);
    meanp=load([fname,'_mean']);
    meanp=meanp.xparam1;
    
    dist=[lowerp',meanp,upperp'];
    tb=tabtex(strvcat('Name','lower 5pc ','mean','upper 95pc'),'',3,strvcat(regexprep((names),'\_','\\_')),(dist));
    tabtex2texpdf('MCMC_result',1,'Moments of estimates',tb,1);
    
    
end
    

if 0
    gg={'Y','C','INVS','X','IM','PII','CHI_F','NTW','Credit','Employ','PII_W1','Rn'};
    stdv=sqrt(diag(oo_.var));
   corre=oo_.var./(stdv*stdv');
   tb=tabtex(strvcat('variables',strvcat(regexprep(gg,'\_','\\_'))),'',3,strvcat(regexprep(gg,'\_','\\_')),(corre));
    tabtex2texpdf('correlation',1,'Correlations',tb,0);
end
    
