%--------------------------------------------------------------------------
% function [map] = FT_read_lma_map(filename)
%
% A function for Matlab which reads in data which represents mirror surface
% heights (phase map) from a file and returns this data in the map 
% structure (see FT_new_surface_map.m).  The input file is in the lma 
% structure.
%
% filename:     Raw data file containing map data
%
% map:          Data returned in map structure, containg surface heights,
%               scaling factors etc.
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    23.07.2012
%--------------------------------------------------------------------------
%

function [map] = FT_read_lma_map(filename)

    baseid = 'read_lma_map';
    
    % Open file for reading
    [FID,result] = fopen(filename,'r');

    if (FID==-1)
        msgid=[baseid,':fileopen'];
        error(msgid,result)
    end
 
    % Take map name from filename
    name = FT_remove_file_extension(filename);
    
    % Phase maps represented by type 0 in the map structure
    type = 0;
    
    % Both reflected and transmitted light fields are affected by the map
    field = 0;
    
    % Data in nm
    scaling = 1e-9;
    
    % Read data in input file
    [data,count] = fscanf(FID,'%g');
    
    % Header data gives size of data array
    cols = data(1);
    rows = data(2);
    
    % Approximate optical centre from size of data, correct this later
    x0 = (cols+1)/2;
    y0 = (rows+1)/2;
    
    % Value indicating pixel is outside the map/mirror area
    zerodata = data(7);
    
    % Resolution of x/y axis
    stepsize = data(8);
    
    % The rest of the data refers to the surface heights making up the
    % mirror map
    % Reshape surface height data
    map_data = reshape(data(9:count),cols,rows);
    
    % Find pixels outside the mirror and set to nan
    [idx] = find(map_data==zerodata);
    map_data(idx) = nan;
    
    % Create map structure with the relevant parameters
    map = FT_new_surface_map(name,map_data,type,field,x0,y0,stepsize,stepsize,scaling);

    % Recenter map for more accurate optical centre
    map = FT_recenter_mirror_map(map);
    
end

