#!/usr/bin/perl
# par2kml2 -- 台灣地籍 .par 格式中幾筆地中心點轉成 KML
# Taiwan cadastral .par format to KML for a set of center points
# 給地號，輸出每筆中心點
# Given parcel numbers, returns each's center point.
# Copyright       : http://www.fsf.org/copyleft/gpl.html
# Author          : 積丹尼 Dan Jacobson -- http://jidanni.org/
# Created On      : Thu Apr 14 10:43:42 2011
# Last Modified On: Thu Nov 22 07:32:27 2012
# Update Count    : 204
use strict;
use warnings FATAL => 'all';
use constant USAGE => "Usage 例:
\$ ls
le0714.bnp le0714.coa le0714.par
\$ $0 le0714 地號 [地號...] :
\$ $0 le0714 3250-0 3254-0 4232-7 ...
";
use Geography::NationalGrid;
use Geography::NationalGrid::TW;
my %parcels;
my ($filebasename) = (shift);
die USAGE unless $filebasename;
for (@ARGV) { $parcels{$_}{Easting} = $parcels{$_}{Northing} = undef; }
die USAGE unless -f "$filebasename.par";
@ARGV = ("$filebasename.par");

while (<>) {
    next
      unless
/^(?<parcel>.{4})(?<subparcel>.{4}).{35}(?<Northing>.{9})(?<Easting>.{8}).../;
    my $r = $+{parcel} . "-" . $+{subparcel};
    $r =~ tr/ //d;
    next unless exists $parcels{$r};
    map { $parcels{$r}{$_} = $+{$_} } qw/Easting Northing/;
}
print <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
EOF
for my $r ( sort keys %parcels ) {
    unless ( $parcels{$r}{Easting} && $parcels{$r}{Northing} ) {
        print STDERR "Parcel $r not found. Skipping.\n";
        next;
    }
    my $p = new Geography::NationalGrid::TW(
        Projection => q(TWD67),
        map { $_ => $parcels{"$r"}{$_} } qw/Easting Northing/
    );
    $p = $p->transform(q(TWD97));
    printf
"  <Placemark><name>%s</name><Point><coordinates>%f,%f</coordinates></Point></Placemark>\n",
      $r, $p->longitude, $p->latitude;
}
print <<EOF;
 </Document>
</kml>
EOF
