
% define the directory where the raw files are stored
datadir=fullfile('..','raw');
% check which files are in the data directory
files=dir(fullfile(datadir, '92_N-33-66-D-c-3-2.txt'));
dataset=load(fullfile(datadir, files(1).name));

% the file contains 6 columns
x=dataset(:,1);
y=dataset(:,2);
z=dataset(:,3);

 %plot3(x,y,z);
% split the data into the different transects
% compute distances between sequential points
d = (x(1:(end-1)) - x(2:end)).^2 + (y(1:(end-1)) - y(2:end)).^2;
[b, ix] = sort(d);

% check the number of transects visualy (plot them x,y) (or use some
% cutoff)
ntransects = 15 
% total number of points
npointstotal = size(x,1)
splitpoints=ix(end-(ntransects-1):end);
splitpoints=[sort(splitpoints)' npointstotal];
 
% Compute the maximum number of points per transect  
npoints = max(diff([0 splitpoints]))

% Create a structure for each transect. 
transects = struct('x', [], 'y', [], 'z',[]);
start = 1
for i=1:ntransects
    transects(i).x = x(start:splitpoints(i));
    transects(i).y = y(start:splitpoints(i));
    transects(i).z = z(start:splitpoints(i));
 start = splitpoints(i)+1
end

% this is the file we're saving results to 
filename=('92_N-33-66-D-c-3-2.nc');
nc_create_empty(filename)
nc_add_dimension(filename,'points',npoints)
nc_add_dimension(filename,'transects',ntransects)

varstruct.Name='x';
varstruct.Nctype='double';
varstruct.Dimension={'transects','points'};
nc_addvar(filename,varstruct)
nc_attput(filename,'x','units','degree_east')
nc_attput(filename, 'x', 'standard_name', 'latitude')

varstruct.Name='y';
varstruct.Nctype='double';
varstruct.Dimension={'transects','points'};
nc_addvar(filename,varstruct)
nc_attput(filename,'y','units','degrees_north')
nc_attput(filename, 'y', 'standard_name', 'longitude')

varstruct.Name='z';
varstruct.Nctype='double';
varstruct.Dimension={'transects','points'};
nc_addvar(filename,varstruct)
nc_attput(filename,'z','units','meters')
nc_attput(filename, 'z', 'standard_name', 'mean_high')

for i=1:ntransects
    nc_varput(filename, 'x', transects(i).x, [i-1,0], [1,size(transects(i).x,1)])
    nc_varput(filename, 'y', transects(i).y, [i-1,0], [1,size(transects(i).x,1)])
    nc_varput(filename, 'z', transects(i).z, [i-1,0], [1,size(transects(i).x,1)])
end


nc_dump(filename)
