% 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.

% Main script to run the registration to correct x,y,z offsets with respect
% to lidar data. It is a system call
%
% Version History
%   2017/03/28  Marc Bosch       Initial version
%   2017/04/17  Marc Bosch       remove pcs metrics data structure


function [filenameLAS_registered,XYZoffset,registeredpc] = XYZregistration(filename,referencepcpath,node_xyz,pointspacing)

%registration
CallingDir = cd;

WorkingDir = mfilename('fullpath');
WorkingDir = fileparts(WorkingDir);
cd(WorkingDir)
Registrationexecpath=['align3d'];

[PATHSTR,NAME,EXT] = fileparts(filename);
LASfilename=[NAME EXT];
pathstring=['./temp/' LASfilename];
%write LAS file to perform registration
[filenameLAS,~]=writeMeshNodes2LAS(node_xyz,pathstring);

Registrationpathstring=['./lasregistration/'];
copyfile(filenameLAS,[Registrationpathstring LASfilename])
Regexecpath=[Registrationexecpath ' ' referencepcpath];
command=([Regexecpath ' ' Registrationpathstring LASfilename ...
    ' gsd=' num2str(pointspacing) ' maxt=10.0']);                        
system(command);
%read registered file and replace node_xyz
filenameLAS_registered = [filename(1:end-4) '_aligned.las'];
%read xyz offset
filetxt=[Registrationpathstring LASfilename(1:end-4) '_offsets.txt'];
XYZoffset=readXYZoffset(filetxt);
%apply offset
% filenameLAS_registered=[WorkingDir '\' filenameLAS_registered];
node_xyz_reg(1,:) = node_xyz(1,:)+XYZoffset(1,1);
node_xyz_reg(2,:) = node_xyz(2,:)+XYZoffset(2,1);
node_xyz_reg(3,:) = node_xyz(3,:)+XYZoffset(3,1);
%write registered las
writeMeshNodes2LAS(node_xyz_reg,filenameLAS_registered);

% filenameLAS_registered=[WorkingDir '\' filenameLAS_registered];
registeredpc.x = node_xyz_reg(1,:);
registeredpc.y = node_xyz_reg(2,:);
registeredpc.z = node_xyz_reg(3,:);
if length(find(XYZoffset==0))==3
    %read from file
    if exist([Registrationpathstring LASfilename(1:end-4) '_aligned.las'],'file')~=0
        registeredpc = lasdata(filenameLAS_registered);
    else
        filenameLAS_registered='';
        disp('ERROR! registered las file does not exist. Use "bpf" file or use xyzoffset')
    end
end

%remove file from temporal registration folder
delete([Registrationpathstring LASfilename]);
delete([Registrationpathstring LASfilename(1:end-4) '_aligned.las']);
delete([Registrationpathstring LASfilename(1:end-4) '_aligned.bpf']);
delete([Registrationpathstring LASfilename(1:end-4) '_aligned.tif']);
cd(CallingDir)