%
%------------------------------------------------------------------
% function []=FT_write_surface_map(filename, map)
%
% Function for Matlab, writes array of real numbers to file.
% The array shoud represent either an amplitude or a phasemap of
% an optical surface.
% 
% filename: name of file to be written
% map:      the surface map (variable must be a 'map' structure,
%           see FT_new_surface_map)
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Andreas Freise  03.07.2008
%------------------------------------------------------------------
%

% Description: writes a mirror map into a file in Finesse readable format
% Keywords: write, map, file, Finesse

function [] = FT_write_surface_map(filename, map)
  
  baseid='write_surface_map';
  
  FT_make_backup(filename);
  
  [FID, result]=fopen(filename,'w');
  
  if (FID==-1)
    msgid=[baseid,':fileopen'];
    error(msgid,result);
  end
  
  fprintf(FID,'%% Surface map\n');
  fprintf(FID,'%% Name: %s\n',map.name);
  fprintf(FID,'%% Type: ');
  switch (map.type)
   case {0} 
    fprintf(FID,'phase '); 
   case {1}
    fprintf(FID,'absorption '); 
   case {2}
    fprintf(FID,'reflectivity ');
  end
  switch (map.field)
   case {0} 
    fprintf(FID,'both\n'); 
   case {1}
    fprintf(FID,'reflection\n'); 
   case {2}
    fprintf(FID,'transmission\n');
  end
  
  [rows,cols]=size(map.data);
  fprintf(FID,'%% Size: %d %d\n',rows,cols);
  fprintf(FID,'%% Optical center (x,y): %g %g\n',map.x0,map.y0);
  fprintf(FID,'%% Step size (x,y): %g %g\n',map.xstep, map.ystep);
  fprintf(FID,'%% Scaling: %g\n',map.scaling);
  fprintf(FID,'\n\n');

  % write NaNs as zeros
  map.data(map.nan)=0;
  
  [rows,cols]=size(map.data);
  for i=1:rows;
    fprintf(FID,'%.15g ',map.data(i,:)');
    fprintf(FID,'\n');
  end
  
  fclose(FID);
