#!/usr/bin/perl -w

# slices big PTS LIDAR file into slices of N points, maintaining all points

# for these PTS files: first line of file is number of points in file
# all remaining lines look like:
# -13.332040 9.806205 -4.952839 -1078 191 157 136
# X Y Z I R G B

if($#ARGV != 2) { print "\nusage: slice.pl num_points infile.pts outBaseName\n\n"; exit; }

my $Nout = shift;  # num of output points per slice
my $infile = shift;
my $outBaseName = shift;

my $Nin = 0;   # number of input points;
my $i = 0;  # current point index
my $fnum = 0;

open(FP, "<$infile") or die "\nCouldn't open $infile\n\n";

while(<FP>) {
    my($line) = $_;  # next line from input file

    if($Nin == 0) {   # reading very first line: contains total num points
	$Nin = $line;
	chomp $Nin;
    } 
    else {

	if($i == 0) {  # start a new output slice file
	    close(OFP);
	    open(OFP, ">$outBaseName$fnum.ply");

	    # edge case: if last file, not exactly $Nout points
	    my $npnts = $Nout;
	    if((($fnum+1) * $Nout) > $Nin) { $npnts = $Nin - $fnum*$Nout; }

	    # outputting PLY files: this is their header:
	    #print "ply\nformat ascii 1.0\nelement vertex $Nout\n".
	    print OFP "ply\nformat ascii 1.0\nelement vertex $npnts\n".
		"property float x\nproperty float y\nproperty float z\n".
		"property uchar intensity\n".
		"property uchar red\nproperty uchar green\nproperty uchar blue\n".
		"end_header\n";
	    ++$fnum;
	} 

	print OFP $line;
	++$i;
	if($i == $Nout) { $i = 0; }   # open a new file
    }
}

close(FP);
close(OFP);

