%
%--------------------------------------------------------------------------
% An example function for Matlab demonstrating the use of SimTools for 
% mirror maps. The script reads in raw mirror map data and assigns it to a 
% standard map structure. The map is then recentered and invalid elements
% removed. The diameter of the mirror map is then calibrated to 1 inch 
% (2.54 cm). An average offset is removed and any tilt is then fitted and 
% removed from the surface of the mirror map. The resulting mirror map is 
% plotted
%
% This script then writes the map in the format for use in Finesse and
% creates and writes an apeture map corespondin to the mirror map, also for
% use in Finesse. 
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond 04.05.2011
%--------------------------------------------------------------------------
%

% Description: Example for reading a Zygo mirror map
% Keywords: zygo, mirror, map, read

clear all;

% Example raw map file used in the example
filename='pr95_orientation1_C.asc.gz';

% File is .asc so filetype is 2
filetype=2;

% unzipping the file if required
filename=FT_check_for_gzip(filename);
  
w=0;
displaystyle=0;

% read in zygo map
map=FT_read_zygo_map(filename, filetype);

% prepare output filename
basename=FT_remove_file_extension(filename);
map_name=sprintf('%s', basename, '_for_finesse.txt');
amp_map_name=sprintf('%s', basename, '_aperture.txt');
result_name=sprintf('%s', basename, '_conversion_info.txt');

FT_message(' --- recentering map ...');
% recenter map
map=FT_recenter_mirror_map(map);

% Zoom in on the valid area of the mirror map and exclude non-valid
% elements
map=FT_remove_elements_outside_map(map);

% The chosen calibration diameter is 1 inch
D=2.54e-2;

% Calibrate the map diameter
map=FT_calibrate_map_diameter(map, D);

FT_message(' --- removing offset ...');
% average over mirror and remove the offset
[map,offset1]=FT_remove_offset_from_mirror_map(map,D/2);

FT_message(' --- removing piston ...');
% remove piston
[map,x_tilt,y_tilt,offset2]=FT_remove_piston_from_mirror_map(map,w,displaystyle);

offset=offset1+offset2;

% Write map to file in finesse format
FT_message(sprintf('saving file "%s" ...\n',map_name));
FT_write_surface_map(map_name,map);

% Create aperture map
amp_map=FT_create_aperture_map(map);

% Write aperture map to file in finesse format
FT_message(sprintf('saving file "%s" ...\n',amp_map_name));
FT_write_surface_map(amp_map_name,amp_map);

% Write results to STDOUT
FT_write_map_fit_results(1,map,0,x_tilt,y_tilt,offset,w,0);

% ... and to file
FT_message(sprintf('writing results to file "%s" ...\n',result_name));
FT_make_backup(result_name);
[FID, result]=fopen(result_name,'w');  
if (FID==-1)
  msgid=[baseid,':fileopen'];
  error(msgid,result);
end
FT_write_map_fit_results(FID,map,0,x_tilt,y_tilt,offset,w,0);
fclose(FID);

% Plot the final map
FT_plot_mirror_map(map,0);


