% Copyright 2017 The Johns Hopkins University Applied Physics Laboratory.
% Licensed under the MIT License. See LICENSE.txt in the project root for full license information.

% Reads the input las file, removes non-unique entries and sorts data using
% X coordinates, and trinagulates to create mesh (note that this is only in
% case point cloud is input and not already a mesh)
% according 
%
% Version History
%   2017/03/28  Marc Bosch       Initial version

function meshinput1=get_inputdata(pathinputpc1,gtAOIpath,pointspacing,writelas,writeply)


inputpc1 = lasdata(pathinputpc1);
%inputpc1 = lasdataread(inputpc1,pathinputpc1);

pcMat=[inputpc1.x inputpc1.y];
[pcMatu,ppo]=unique(pcMat,'rows','stable');
[inputpc1.x,posorted]=sort(pcMatu(:,1));
inputpc1.y=pcMatu(posorted,2);
temp=inputpc1.z;
inputpc1.z=temp(ppo);
temp=inputpc1.z;
inputpc1.z=temp(posorted);
%subsample point cloud for testing metrics
DSlevel=1;
%[inputpc1]=decimationgrid(inputpc1,gtAOIpath,DSlevel);


%create mesh with delaunay triangulation (this will come from performers)
%fill mesh data structure:
tic;
triinput1 = delaunay(inputpc1.x(1:DSlevel:end),inputpc1.y(1:DSlevel:end));
% TODO:This is to be used when meshes are provided not point clouds
%triinput1 = populatefromFile(inputpc1.x(1:DSlevel:end),inputpc1.y(1:DSlevel:end));

meshinput1=subdivision(triinput1',[inputpc1.x(1:DSlevel:end)';inputpc1.y(1:DSlevel:end)';inputpc1.z(1:DSlevel:end)'], ...
    pointspacing,gtAOIpath);
filename=[fileparts(pathinputpc1) '/solution'];
LASfilename = [filename '.las'];
%write lasdatastruct so that registered las file has current fields updated
testobj3=inputpc1;
testobj3.x=[];
testobj3.y=[];
testobj3.z=[];
save('./Registration/lasdatastruct.mat','testobj3');
%write LAS
if writelas==1 
    [meshinput1.filenameLAS,meshinput1.lasobject]=writeMeshNodes2LAS(meshinput1.node_xyz,LASfilename);
end

%write DSM
%create dsm
%params.gsd = 0.3;
%dem_struct = demGenerate(meshinput1.lasobject, params);

%write geotiff
% filenameGEOTIF = [filename '.tif'];
% geotiffwrite(filenameGEOTIF,A,R);    
% meshinput1.filenameGEOTIF=filenameGEOTIF;
    
%write ply
if writeply==1
 PLYfilename = [filename '.ply'];
 meshinput1.filenamePLY = write_mesh2ply(meshinput1.node_xyz',meshinput1.triangle_node',...
          PLYfilename);
end