#!/usr/bin/perl
# bnpcoa21kml -- 台灣地籍 .coa, .bnp 格式中一筆地轉成 KML
# Taiwan cadastral .coa, .bnp format to KML for ONE PARCEL
# 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: Fri Apr 15 07:52:47 2011
# Update Count    : 100
#猜試轉
#宗地資料檔 (.PAR) 格式
#地號界址檔 (.BNP) 格式
#界址坐標檔 (.COA) 格式
#中一筆地轉成 .KML
use strict;
use warnings FATAL => 'all';
use constant USAGE => "Usage 例:
\$ ls
le0714.bnp le0714.coa le0714.par
\$ $0 le0714 地號 [附號] [[Easting correction]] [[[Northing correction]]] 例如
\$ $0 le0714 3254
\$ $0 le0714 3254 0 -7 6
";
use Geography::NationalGrid;
use Geography::NationalGrid::TW;
my ( %corners, %correction, $filebasename, $parcel, $subparcel );
$_ = shift || 0
  for $filebasename, $parcel, $subparcel, $correction{Easting},
  $correction{Northing};
die USAGE unless $filebasename && $parcel;
@ARGV = ("$filebasename.bnp");
my $count = 0;

while (<>) {
    my @a = split;
    next unless $#a;
    next unless $parcel == shift @a;
    next unless $subparcel == shift @a;
    shift @a;
    shift @a;
    $corners{$_}{count} = $count++ for @a;
}
die "尋無該地號" unless $count;
@ARGV = ("$filebasename.coa");
LINE: while (<>) {
    my @a = split;
    for my $corner ( shift @a ) {
        next LINE unless exists $corners{$corner};
        $corners{$corner}{coordinates}{$_} = shift @a for qw/Northing Easting/;
    }
}
print <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
  <Placemark>
   <name>$parcel-$subparcel 地號</name>
   <Polygon>
    <outerBoundaryIs>
     <LinearRing>
      <coordinates>
EOF
my $connect_back;
for my $corner (
    sort { $corners{$a}{count} <=> $corners{$b}{count} }
    keys %corners
  )
{
    my $p = new Geography::NationalGrid::TW(
        Projection => q(TWD67),
        map { $_ => $corners{$corner}{coordinates}{$_} + $correction{$_} }
          qw/Easting Northing/
    );
    $p = $p->transform(q(TWD97));
    for ( sprintf "       %f,%f\n", $p->longitude, $p->latitude ) {
        print;
        $connect_back = $_ unless $corners{$corner}{count};
    }
}
print $connect_back;
print <<EOF;
      </coordinates>
     </LinearRing>
    </outerBoundaryIs>
   </Polygon>
  </Placemark>
 </Document>
</kml>
EOF

