function [ XYZ ] = Create_Bathy( input_args )
%CREATE_BATHY Summary of this function goes here
%   Detailed explanation goes here

%% Hard settings
Params=[];
%Here you can insert hard settings (things you don't want the user to choose)

%% Load process settings txt file
Params=read_processparameters(Params)

%% Load GPS file 
GPS=Read_Cache

%% Load echosounderfile
disp('---------reading Echo.txt')
Echo=read_Echo;
Echo = rmfield(Echo, 'time_UTC') %%% Remove field, it is useless now

%% possible check whether echo and GPs are on the same date.

%% %%%%------------------ Edit echosounder (Removal of bad points)
Echo.validpoints=ones(size(Echo.depth));  %% vector keeping track of all valid points 

%%% Remove points where echosounder values keep constant for extended period of time 
if Params.EcC == 1
dE=diff(Echo.depth); % maak vecor met locale afgeleide
Echo.validpoints(2:end)=Echo.validpoints(2:end).*(dE~=0);    %gooi die slechte plekken eruit
end

%%% Remove spikes in the shallow region   % Adaptation MA nov 2010
Echo.depthsf= medfilt1(Echo.depth,100);
for i_dE=1:length(dE)-1
    if abs(dE(i_dE)) >= 0.1 && Echo.depth(i_dE) <= 2.5
Echo.validpoints(i_dE+1)=0;
    end
    if abs(Echo.depth(i_dE+1)-Echo.depthsf(i_dE+1)) >= 0.15 && Echo.depth(i_dE) <= 2.5
Echo.validpoints(i_dE+1)=0;
    end
end

%%% Find points with depth value 0 m
%Echo.validpoints=Echo.validpoints.*(Echo.depth~=0);
Echo.validpoints=Echo.validpoints.*(Echo.depth>=0.5);  % Adaptation MA nov 2010


%%% Change all bad points into NaN's (removal of these points is a bad idea the interpolation will give bad results)
Echo.depth(Echo.validpoints==0)=NaN;

%%% __________

%% Latency
Echo.GPSMatlabtime= Echo.GPSMatlabtime+Params.Latency/(60*60*24);  % rewrite the latency in matlabtime format. e.g 0.4s/(60*60*24)
%% Speed of Sound
Echo.depth= Echo.depth*Params.Soundspeed/1500; % Correct with the soundspeed as defined in the ProcessParameters.txt

%% Connect Echosounder 2 GPS
Echo.points_at_GPS = interp1(Echo.GPSMatlabtime,Echo.depth,GPS.Matlabtime); % find echosounder values on GPS times

Zbottom=GPS.Z_RD-Echo.points_at_GPS-Params.dZ; % Z value bottom = Z gps - ofset antenna-transducer - depth waarden GPS en diepte echosounder uitgezet

%% MAKE XYZ 
XYZ.X=GPS.X_RD(~isnan(Zbottom)); %%% Remove points with only GPS and no Echo
XYZ.Y=GPS.Y_RD(~isnan(Zbottom));
XYZ.Z=Zbottom(~isnan(Zbottom));

%% write XYZ to file
disp('Writing XYZ to file')
fname=['XYZ_jetski_RD_NAP.txt'];
fid=fopen(fname,'w');
fprintf(fid,'Survey of %s \n',datestr(GPS.Matlabtime(1),'mm/dd/yyyy'));
fprintf(fid,'Processed on %s using Create_Bathy.m \n',datestr(now));
fprintf(fid,'%10s \n',' Settings ');
fprintf(fid,'Speed of Sound [m/s] = %f \n',Params.Soundspeed);
fprintf(fid,'Latency [s] = %f \n',Params.Latency);
%fprintf(fid,'Offset antenna-transducer = %f \n',Params.dZ);
fprintf(fid,'Use for monthly NetCDF = %1.0f \n',Params.NetCDF);
fprintf(fid,'%10s \n','------------------------------------');

fprintf(fid,'%10s \n',['X (m RD) ; Y (m RD) ; Z (m NAP)']  );
fprintf(fid,'%10.3f %10.3f %10.3f \n',[XYZ.X ; XYZ.Y ; XYZ.Z]);

fclose(fid);


disp('done')

%% END OF FILE... Functions Below

function [Echo] = read_Echo
%%% allocate matrices
Echo.time_UTC=zeros(1e6,1);  %% arbirary high number (equivalent to 27 h of 10 Hz data)
Echo.depth=zeros(1e6,1);
%%% readfile
Filename.Echo='Echo.txt';
fid = fopen(Filename.Echo);
tline = fgetl(fid); Surveydate=datenum(tline(11:21)); % write the survey date in matlab format e.g. 07/16/2009 => 733970 
for i=1:3;tline = fgetl(fid);end %(Get rid of header lines)

ei=0; % set counter
go = 1;

while go  
    tline = fgetl(fid);
    if length(tline) >= 20
        ei=ei+1;
     
        %%% read tline to structure
        %%% tline info: Time UTC [HHMMSS.decSS] ; depth [m]
        [Echo.time_UTC(ei) Echo.depth(ei)] = strread(tline, '%f %f ', 'delimiter', ' ');
     else    
        go = 0;
     end
      
end    
fclose(fid); 
%%%Recut allocated matrices to right length
Echo.time_UTC=Echo.time_UTC(1:ei,:); 
Echo.depth=Echo.depth(1:ei,:);
Echo.Surveydate(1:ei)=Surveydate;

Echo.GPSMatlabtime = datenum([datestr(Echo.Surveydate(:),'yyyymmdd ') num2str(Echo.time_UTC(:),'%010.3f')],'yyyymmdd HHMMSS.FFF'); %% Matlabtime

%%
function [Params] = read_processparameters(Params)
%%% readfile
Filename.Params='ProcessParameters.txt';
fid = fopen(Filename.Params);

go = 1;

while go  
    tline = fgetl(fid);
    
    % read Speed of sound
    temp=strfind(tline,'SOS');
    if temp
        A=strread(tline, '%s', 'delimiter', ' ');
        Params.Soundspeed=str2double(A{3,1});
    end
    % read Echosounding clipping removal 
    temp=strfind(tline,'EcC');
    if temp
        A=strread(tline, '%s', 'delimiter', ' ');
        Params.EcC=str2double(A{3,1});
    end
    % read Vert. offset GPS antenna and transducer. 
    temp=strfind(tline,'dZ');
    if temp
        A=strread(tline, '%s', 'delimiter', ' ');
        Params.dZ=str2double(A{3,1});
    end
    % read Latency (can be evaluated using latency.m) 
    temp=strfind(tline,'LAT');
    if temp
        A=strread(tline, '%s', 'delimiter', ' ');
        Params.Latency=str2double(A{3,1});
    end
    
        temp=strfind(tline,'NetCDF');
    if temp
        A=strread(tline, '%s', 'delimiter', ' ');
        Params.NetCDF=str2double(A{3,1});
    end
    
    % read end of file
    temp=strfind(tline,'END');
    if temp
        go = 0;
    end
     
end    
fclose(fid); 


