%---------------------------------------------------------
% fread_srtm3
%---------------------------------------------------------
% read in SRTM topography data data
%
% input:        	hgtfile  	string  	filename to read
% output:       	s        	int(n,n) 	topography matrix
%               	n        	int        	x and y dimensions
%			ierr		int		0 = OK, 1=error
%
% usage:        [s,n,ierr] = fread_srtm3(hgtfile);
%
%---------------------------------------------------------
% N.Teanby      31/10/2013       Original version
%---------------------------------------------------------
function [s,n,ierr] = fread_srtm3(hgtfile);

% read the file
fid = fopen(hgtfile,'r');
s = fread(fid,[1201,inf],'int16','b');
fclose(fid);

% check it has a dimension of 1201x1201
n = length(s);
if (n ~= 1201);
  ierr = 1;
else
  ierr = 0;
end

% correct orientation
s = s' ;
s = flipud(s);

% replace bad data with NaNs
s(find(s == -32768)) = NaN;

% apply a NaN mean
for i=2:1200;
  for j=2:1200;
    if isnan(s(i,j)) == 1;
      s(i,j) = nanmean(nanmean(s(i-1:i+1,j-1:j+1)));
    end
  end
end

end
