#!/usr/bin/perl
# taiwanmapno2longlat -- 將台灣圖號換成經緯度
# Convert Taiwan map numbers to longitude/latitude
# Copyright       : http://www.fsf.org/copyleft/gpl.html
# Author          : Dan Jacobson -- http://jidanni.org/geo/taiwan_datums/
# Created On      : April 2002
# Last Modified On: Tue Apr 11 22:15:30 2006
# Update Count    : 61
#輸入圖號， 輸出經緯度
#For each Taiwan government map number, one per line of input,
#output the map number, longitude, and latitude, in decimal degrees,
#of its southeast corner (TWD67).
#Usage: $ echo 9521-2-025|./taiwanmapno2longlat
#Or $ ./taiwanmapno2longlat map_numbers.txt ... #gives:
# #1> 9521-2-025
# 120.600 24.175
# #2> 9521-2-07
# 120.550 24.150
# #3> 9521-2-SE
# 120.625 24.000
# #4> 9521-2
# 120.500 24.000
# which show all four valid input formats at present 四種輸入式
use strict;
use warnings;
while (<>) {
    garbled() unless /^(\d\d)(\d\d)-([1-4])(?:-([NS][EW]|0\d\d|100|[012]\d))?$/;
    my $x =
      73 + ( $1 < 10 ? $1 + 100 : $1 ) / 2;   #73:新疆 100:釣魚台 10:隨意
    my $y = 13.5 + $2 / 2;                    #南海
    if ( $3 < 3 ) { $x += .25 }
    if ( $3 == 1 || $3 == 4 ) { $y += .25 }
    if ( defined $4 ) {
        {
            my $t = $4;
            if ( $t =~ /\d\d\d/ ) {
                garbled() unless $t > 0;
                $t -= 1;
                $x += $t % 10 * .025;
                $y += ( 9 - int( $t / 10 ) ) * .025;
                last;
            }
            if ( $t =~ /\d\d/ ) {
                if ( $t > 25 || $t < 1 ) { garbled() }
                $t -= 1;
                $x += $t % 5 * .05;
                $y += ( 4 - int( $t / 5 ) ) * .05;
                last;
            }
            if ( $t =~ /E/ ) { $x += .125 }
            if ( $t =~ /N/ ) { $y += .125 }
        }
    }
    printf "#$.> $_%.03f %.03f\n", $x, $y;
}
sub garbled { die "$0: garbled input at line $.\n" }

#test with perl -we '
#for $h(94,95){for $i(21,22){for $j(1..4){for $k(1..100)
#{printf"%02d%02d-%d-%03d\n",$h,$i,$j,$k}}}}'|./taiwanmapno2longlat|
#sed /#/d>/tmp/lt;cd /tmp;echo plot \'lt\'|nohup gnuplot -persist #in emacs
