%
%---------------------------------------------------------------------  
% function [result] = FT_make_finesse_video(filename)
% 
% Matlab function that reads a finesse output file that has been
% created with x3axis and creates a video output.
%
% 
% Part of the SimTools package
% Andreas Freise, 26.12.2009 afreise@googlemail.com
%--------------------------------------------------------------------- 

% Description: Reads finesse output file with x3axis and creates video output
% Keywords: make, finesse, video, create, x3axis

 function [result] = FT_make_finesse_video(basename)

   outfilename=[basename,'.out'];
    
   fprintf(' Reading file %s\n.',outfilename);
   make_video=2;
   data = load(outfilename);
   [rows,cols]=size(data);
   X1=data(:,1);
   X2=data(:,2);
   X3=data(:,3);
   Z=data(:,4:cols);
   total_max=max(data(:,4));
   
   [x1,x2,x3,M]=FT_convert_finesse_4D(X1,X2,X3,Z);
      
   npoints=length(x3)
   
   videoname=sprintf('%s_video.avi',basename);
   aviobj = avifile(videoname,'fps',2);
    
   hf=figure('Renderer','Zbuffer','visible','off');
   hax=axes;
   zi=M(:,:,1);
   mymap=FT_neg_colormap();
   p1=surf(x1,x2,zi,'Edgecolor','none','FaceColor','interp','parent',hax);
   pscale=1;
   set(hax, 'XLim', pscale*[min(x1) max(x1)]);
   set(hax, 'YLim', pscale*[min(x2) max(x2)]);  
   xlabel('x/w0');
   ylabel('y/w0');
   axis square
   grid off;
   box off;
   view(2);
   colormap(mymap)
   cb=colorbar;
   caxis manual; % allow subsequent plots to use the same color limits
   caxis([0 1]);
   hold(hax,'all');   
   set(hf,'BackingStore','Off');
   set(hf,'DoubleBuffer','on') % To turn it on 
   

    fprintf(' Making video\n.');
    total_time=tic;
    elapsed_time=0;

    for q=1:npoints
      zi=M(:,:,q);
      maxc=max(max(zi));
      %zi=zi/maxc;
      zi=zi/total_max;
      %surf(1e3*Grid.axis,1e3*Grid.axis,zi,'Edgecolor','none','FaceColor','interp','parent',hax);
      set(p1,'zdata',zi);
      aviobj = addframe(aviobj,hf);
      %if (make_video>1)
      %  drawnow;
      %end
    
       
      if ((rem(q,round(npoints/100)) == 0) || q==npoints)
        [elapsed_time]=FT_print_progress(elapsed_time,q,npoints, 0);
        tic;
      end      
    end
    
    aviobj = close(aviobj);
    
    
    hold off;
    if (make_video<2)
      close(hf);
    end
 
  
    elapsed_time=toc(total_time);
    fprintf([' --> total elapsed time: %2.0fh:%2.0fmin:%2.0fsec\n'] ...
          ,fix(elapsed_time/3600),fix(mod(elapsed_time,3600)/60),fix(mod(mod(elapsed_time,3600),60)));

  return