function raw2bathy(filename,area);
%% SIMPLE FILTER FOR ERRORS IN THE BATHYMETRIC DATA %%
%
% INPUT FILE IS THE BATHYMETRY FILE CORRECTED FROM TIDAL VARIATIONS

% 'area' the area where the data were collected (4 characters string)
%        that surves as a key for the area (i.e 'camp' for Camposoto and 
%        'cort' for Cortadura).

% OUTPUT FILE IS THE TRANSFERED IN ED50 UTM29 WITH STANDART CORRECTION
% ALSO A SIMPLE SPATIAL FILTER IS APPLIED TO ELIMINATE OUTLIERS IN EACH 
% 20x20m GRID CELL USING THE MEDIAN/MAD METHOD. FORTMAT IS A MATLAB 
% VARIABLE IN THE FORM OF XYZ THAT IS STORED AS AN .MAT FILE
%
%   ***********************************************************************
%   *** IMPORTANT: THE SCRIPT READS AND WRITES IN THE CURRENT DIRECTORY ***
%   ***********************************************************************

%% IMPORT FILE
     % A = xlsread(filename);
     [x,y,z]=textread(filename ,'%f %f %f');
 
%% CORRECT X, Y AND Z COORDINATES   
     switch area
         case 'cort'
              bathy = [x+126.697 y+211.984 z-0.9472];
         case 'camp'
              bathy = [x+126.782 y+211.970 z-0.9472];
     end
%% FILTER LARGE VARIATIONS IN BATHYMETRY 
% for i=1:10
%     slp = diff(bathy(:,3));
%     c_off = 3*std(slp)
%     ind = find(abs(slp)<=c_off);
%     indnot = find(abs(slp)>=c_off);
%     del(i)=length(indnot);
%     output = bathy(ind+1,:);
%     bathy  = output;
% end
ds = 10; % grid spatial resolution in meters
X = [min(bathy(:,1)):ds:max(bathy(:,1))];
Y = [min(bathy(:,2)):ds:max(bathy(:,2))];
for i=1:length(Y)-1
    for j=1:length(X)-1
        id{i,j}  = find(bathy(:,1)>X(j) & bathy(:,1)<X(j+1) & bathy(:,2)>Y(i) & bathy(:,2)<Y(i+1));
        d_id{i,j}= z(id{i,j});
    end
end
loc_med = cellfun(@median ,d_id); % Get outliers the Median/MAD method
loc_std = cellfun(@median, cellfun(@abs, cellfun(@minus, num2cell(loc_med),d_id,'Un',0),'Un',0));
up_lim = loc_med+1.5*loc_std;
lo_lim = loc_med-1.5*loc_std;

for i=1:length(Y)-1
    for j=1:length(X)-1
        out_id{i,j}  = id{i,j}(find(d_id{i,j}>up_lim(i,j) | d_id{i,j}<lo_lim(i,j)));
    end
end
outliers = cat(1,out_id{:,:});
bathy(outliers,:)=[];

%% MAKE OUTPUT FILE
dir = pwd;
f = filesep;
lchar = max(strfind(dir,f));
fw = dir(lchar+3:end);

  name = [area '_bathy_fw' num2str(fw)];
%   makename = [name '= bathy;'];
%   eval(makename)
 
 comsave = ['save(''' name '.mat'', ''bathy'');'];
 eval(comsave)
     