%--------------------------------------------------------------------------
% function [map] = FT_read_ligo_map(filename)
%
% A function for Matlab which produces a mirror map structure from data
% given in a map file.
%
% filename: name of ligo file
% map:      a surface map, in the standard mirror map structure
%
%
% 27.10.2010    Charlotte Bond
%--------------------------------------------------------------------------
%

function [map] = FT_read_ligo_map(filename)

  baseid='read_ligo_map';
    
  % Open file for reading
  [FID, result]=fopen(filename,'r');
    
  if (FID==-1)
    msgid=[baseid,':fileopen'];
    error(msgid,result);
  end
  
  name=FT_remove_file_extension(filename);
  name=FT_remove_phrase_from_string(name,'_asc');
  
  % Standard maps have type 'phase' (they store surface
  % heights)
  type=0;
  
  % Both (reflected and transmitted) light fields are affected 
  field=0;
  
  % Measurements in nanometers
  scaling=1e-09;
  
  % Skip unescary data
  for i=1:2
    [M_tmp,count_tmp]=fscanf(FID,'%g ');
    tmp=fgets(FID);
  end

  % Read in numbers coresponding to cols and rows
  [M,count]=fscanf(FID,'%g ');
  
  x0=M(8);
  y0=M(7);
  cols=M(10);
  rows=M(9);
  
  % Skip unescary data
  for i=1:3
    [M_tmp,count_tmp]=fscanf(FID,'%g ');
    tmp=fgets(FID);
  end
  
  % Read in data for the actual step size and scaling factors
  [M,count]=fscanf(FID,'%g ');
  tmp=fgets(FID);
   
  % Scaling factors:
  % S: interferometric scale factor
  % lambda: wavelength
  % O: obliquity factor
  S=M(2);
  lambda=M(3);
  O=M(5);

  xstep=M(7);
  ystep=M(7);
  
  [M,count]=fscanf(FID,'%g ');
  tmp=fgets(FID);
  
  % Resolution of phase data points, 1 or 0
  PhaseRes=M(11);
  
  if PhaseRes==0
      R=4096;
  elseif PhaseRes==1
      R=32768;
  end
  
  Hscale=S*O*lambda/R;
  
  for i=1:3
    [M_tmp,count_tmp]=fscanf(FID,'%g ');
    tmp=fgets(FID);
  end

    
  [M,count]=fscanf(FID,'%g ');
  
  % Scale data to nanmetres
  data=M(1:count);

  % Set to nan all the points outside the mirror surface, i.e. are given as
  % a large offset number in the file
  zero_point=data(1);
  
  [nidx]=find(data==zero_point);
  data(nidx)=nan;
  
  % Reshape and rotate the data to match those in the ligo files
  data=fliplr(rot90(fliplr(reshape(data,rows,cols)),-1));
  data=Hscale*data/scaling;
  
  % Create new surface map
  map=FT_new_surface_map(name,data,type,field,x0,y0,xstep,ystep,scaling);
  map=FT_recenter_mirror_map(map);
  

end