%%%% Code to obtain point distribution coordinates from DL detection %%%%
%%% Iban Berganzo Besga %%%
%% The DL detection result txt file must be edited to a result xlsx workbook with the following info:
% 1st column: image number
% 2nd column: 1
% 3rd column: % value
% 4th column: xcoord value
% 5th column: ycoord value
% 6th column: xdim value
% 7th column: ydim value
% 8th, 9th,... columns: another detected tumulus (continue from 2nd column) or zeros
% Each row: each image

format long
A0T = readtable('result.xlsx'); A0=A0T{:,:};
% DTM coordinates
x1=475275.4862965038046241; y1=4628318.7130783181637526; x2=686804.4862965038046241; y2=4851136.7130783181637526;
% Raster resolution
rr=1;
tesela=1024*rr;

A=A0(:,2:end);

i2=1; j2=1;

columns=ceil((x2-x1)/tesela);

for i=1:size(A,1)

for j=1:6:size(A,2)

if (A(i,j)==1 || A(i,j)==2)

if (A(i,j)==2 && j == 1) %% Si un NoTumulus esta en la primera posicion

	xcoord = A(i,j+2);
	ycoord = A(i,j+3);
	xcoordNext = A(i,j+8);
	ycoordNext = A(i,j+9);
	NtValue = A(i,j+1);
	tValueNext = A(i,j+7);

	if (A(i,j+6)==1 && xcoord==xcoordNext && ycoord==ycoordNext && tValueNext<NtValue)

		A(i,j+6)=3;

	end

elseif (A(i,j)==2 && j == size(A,2)-5) %% Si un NoTumulus esta en la ultima posicion de la matriz

	xcoord = A(i,j+2);
	ycoord = A(i,j+3);
	xcoordPrev = A(i,j-4);
	ycoordPrev = A(i,j-3);
	NtValue = A(i,j+1);
	tValuePrev = A(i,j-5);

	if (A(i,j-6)==1 && xcoord==xcoordPrev && ycoord==ycoordPrev && tValuePrev<NtValue)

		i2=i2-1;

	end

elseif (A(i,j)==2 && j > 1 && j < size(A,2)-5) %% El resto de NoTumulus

	xcoord = A(i,j+2);
	ycoord = A(i,j+3);
	xcoordNext = A(i,j+8);
	ycoordNext = A(i,j+9);
	xcoordPrev = A(i,j-4);
	ycoordPrev = A(i,j-3);
	NtValue = A(i,j+1);
	tValueNext = A(i,j+7);
	tValuePrev = A(i,j-5);

	if (A(i,j-6)==1 && xcoord==xcoordPrev && ycoord==ycoordPrev && tValuePrev<NtValue)

		i2=i2-1;

	elseif (A(i,j+6)==1 && xcoord==xcoordNext && ycoord==ycoordNext && tValueNext<NtValue)

		A(i,j+6)=3;

	end

else %% Los Tumulus

	numPNG = A0(i,1)+1;
	xcoord = A(i,j+2);
	ycoord = A(i,j+3);
	tumularity = A(i,j+1);

	rowT=ceil(numPNG/columns);
	columnT=numPNG-(columns*(rowT-1));
	xTumulus=x1+(tesela*(columnT-1))+xcoord;
	yTumulus=y2-(tesela*(rowT-1))-ycoord;


	sizeTumulus=max(A(i,j+4),A(i,j+5));

	B(i2,j2)=i2;
	B(i2,j2+1)=xTumulus;
	B(i2,j2+2)=yTumulus;
	B(i2,j2+3)=sizeTumulus;
	B(i2,j2+4)=tumularity;
	B(i2,j2+5)=numPNG-1;
	i2=i2+1;

end	

end	

end

end

if (i2 == size(B,1))

	B=B(1:end-1,:);

end

C = sortrows(B,4);

writematrix(B, 'resultGIS.xlsx');