%
%---------------------------------------------------------------------  
% function [result] = FT_FFT_results_buildup(cavity, in_field, mygrid, dfile, lambda, result, make_video);
% 
% Matlab function that reads the temporary files saved by the function
% FT_FFT_precompute_roundtrips and saves them in a new format, 
% required for FT_FFT_cavity_scan.
%
% cavity (structure):  cavity parameters and components 
%                      (see FT_init_cavity.m)
% in_field (complex):  2D data of input beam splitude 
% mygrid (structure):  stores parameters of a 2D grid for FFT computations,
%                      see FT_init_grid.m
%
% dfile (structure):   stored information about the temporary data files.
%                      This functions adds the following fields:
%                      - lines_per_file - number of grid lines stored per file
%                      - number_of_linefiles=filenumber - number of files storing lines
%                      - tmplines - basename for temporary file storing lines
%
% result (structure):  storing results for a cavity scan and the power buildup
%                      this functions adds:
%                      - power_buildup - vector of intra-cavty power during roundtrips
%                      - video - basename of video files, showing buildup
% make_video (integer): make_video = 0 only computes the power_buildup vector
%                       make_video = 1 stores video files of the ciculating field asi it builds up
%                       make_video = 2 also shows the video 
% 
% Part of the SimTools package
% Andreas Freise, 26.12.2009 afreise@googlemail.com
%---------------------------------------------------------------------  

% Description: Reads temporary files saved by FT_FFT_precompute_roundtrips
% Description: and saves in a new format for FT_FFT_cavity_scan
% Keywords: reorganise, tmp, temporary, format, FT_FFT_cavity_scan
% Keywords: FT_FFT_precompute_roundtrips

function [result] = FT_FFT_results_buildup(cavity, in_field, mygrid, dfile, lambda, result, make_video);

  tic;
  k=2*pi/lambda;

  offset=result.operating_point;
  
  fprintf(' === Results: computing power buildup in cavity ...\n')
  total_time=tic;
    
  f_total = complex(zeros(mygrid.xpoints,mygrid.ypoints,'double'));
  result.power_buildup = zeros(1,dfile.roundtrips,'double');
  f_round = complex(zeros(mygrid.xpoints,mygrid.ypoints, ...
                              dfile.fields_per_file,'double'));

  video.basename=sprintf('video_%s_',dfile.datestr);

  qf=1;
    
  for qq=0:dfile.number_of_files-1
    filename=sprintf('%s%04d.mat',dfile.tmpfields,qq);
    fprintf(' Processing file number %d of %d\n',qq+1, dfile.number_of_files);
    data=load(filename);
    data_points=size(data.tmpfields,3);
    f_round(:)=0.0;
    f_round(:,:,1:data_points)=data.tmpfields;
    
    if (make_video>0)
      videoname=sprintf('%s%04d.avi',video.basename,qq);
      aviobj = avifile(videoname,'fps',60);
    
      if (make_video==1)
        hf=figure('Renderer','Zbuffer','visible','off');
      else
        hf=figure('Renderer','Zbuffer');
      end
      hax=axes;
      zi=abs(f_total).^2;
      mymap=FT_neg_colormap();
      p1=surf(1e3*mygrid.xaxis,1e3*mygrid.yaxis,zi,'Edgecolor','none','FaceColor','interp','parent',hax);
      pscale=1/4;
      set(hax, 'XLim', 1e3*pscale*[-mygrid.xsize mygrid.ysize]);
      set(hax, 'YLim', 1e3*pscale*[-mygrid.xsize mygrid.ysize]);  
      xlabel('x [mm]');
      ylabel('y [mm]');
      axis square
      grid off;
      box off;
      view(2);
      colormap(mymap)
      colorbar;
      hold(hax,'all');   
      set(hf,'BackingStore','Off');
      set(hf,'DoubleBuffer','on') % To turn it on 
    end

    tic;
    elapsed_time=0;

    for q=1:data_points  
      if (qf>dfile.roundtrips)
        fprintf('Warning: breaking loop at %d roundtrips!\n',dfile.roundtrips);
        break
      end
      f_total=f_total + f_round(:,:,q)* exp(1i*k* offset * (qf-1));
      result.power_buildup(qf) = result.power_buildup(qf) + sum(sum(abs(f_total).^2))*mygrid.xstep*mygrid.ystep;
      qf=qf+1;
    
      if (make_video>0)
        zi=abs(f_total).^2;
        maxc=max(max(zi));
        zi=zi/maxc;
        %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
      end
       
      if ((rem(q,round(data_points/100)) == 0) || q==data_points)
        [elapsed_time]=FT_print_progress(elapsed_time,q,data_points, 0);
        tic;
      end

    end
    
    if (make_video>0)
      aviobj = close(aviobj);
    end
  end

  if(make_video>0)
    hold off;
    if (make_video==1)
      close(hf);
    end
  end

  result.f_circ=f_total;
  
  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