clear all

path='test.tex';
%path='onespike.tex';
%path='~/u/misc/t/num/naca/*.tex';
L=ls(path);
resize_str='\resizebox{14cm}!{';
i1=strfind(path,'/');
i2=strfind(path,'.');
i2=i2-1;
if isempty(i1)
  i1=1;
else
  i1=i1(end)+1;
end
label_str=['\label{' path(i1:i2) '}'];

for f=1:size(L,1)
  file=deblank(L(f,:));
  filer=fopen(file,'r');
  filew=fopen([file(1:end-4) '_clean' file(end-3:end)],'w');
  fdisp(filew,'\begin{figure}[h]')
  fdisp(filew,'\centering')
  fdisp(filew,resize_str);

  fflag=1;
  s=fgets(filer);
  while ischar(s)
    ix_lp=strfind(s,'\put(');
    ix_rp=strfind(s,')');
    if ~isempty(ix_lp)
      ix_lp=ix_lp(1)+4;
      ix_rp=ix_rp(1);
      p=s(ix_lp+1:ix_rp-1);
      xy=eval(['[' p '];']);
      xy=round(xy);
      x=num2str(xy(1)); y=num2str(xy(2));
      s=[s(1:ix_lp) x ',' y s(ix_rp:end)];
      disp(['Replaced ' p ' with ' x ',' y])
    end
    ixc=strfind(s,'0.15,0.15,0.15');
    if length(ixc==1)
      s=[s(1:ixc-1) '0,0,0' s(ixc+14:end)];
    end
    ix=strfind(s,'[scale=1]');
    if ~isempty(ix)
      s=s([1:(ix-1) (ix+9):end]);
    end
    ix=strfind(s,'-inc');
    if ~isempty(ix)
      s=[s(1:(ix-1)) '.eps' s((ix+4):end)];
    end
    i1=find(double(s)==37); % remove comments
    if ~isempty(i1) 
      if i1(1)>1
        s=sprintf("%s\n",s(1:(i1(1)-1)));
      else
        s=blanks(0);
      end
    end
    ix_f1=strfind(s,'\fontsize');
    if ~isempty(ix_f1)
      if fflag 
        fflag=0;
        ix_f2=strfind(s,'}');
        s1=sprintf("%s\n",[s(ix_f1(1):ix_f2(2)) '\selectfont']);
        fputs(filew,s1);
      end
      s=sprintf("%s\n",deblank(s((ix_f2(2)+1):end)));
    end
    ix_lp=strfind(s,'\put(');
    if ~isempty(ix_lp)
      s=s(ix_lp(1):end);
    end
    if length(s)>1
      fputs(filew,s);
    end
    s=fgets(filer);
  end
  fclose(filer);

  fdisp(filew,'}');
  fdisp(filew,'\caption{}');
  fdisp(filew,label_str);
  fdisp(filew,'\end{figure}');

  fclose(filew);
end
