#!/usr/bin/perl
# longlat2taiwanmapno -- 將經緯度換成台灣圖號
# Convert longitude/latitude to Taiwan map number
# Copyright       : http://www.fsf.org/copyleft/gpl.html
# Author          : Dan Jacobson -- http://jidanni.org/geo/taiwan_datums/
# Created On      : Thu Jan 17 01:28:05 2002
# Last Modified On: Thu Mar 11 03:29:12 2021
# Update Count    : 290
#Reports Taiwan government map numbers.

=usage
echo 120.86617 24.18169|./longlat2taiwanmapno
#1> 120.86617 24.18169
1:5000 : 9521-2-025
1:10000: 9521-2-09...
Or $ ./longlat2taiwanmapno file... #one pair per line
=cut

#If point falls on a map boundary, this program reports the north
#and or east map number.

# Note I didn't say if this was using TWD67 or TWD97 coordinates!
# As "that is not our concern."

# Note islands near Taiwan have their own irregular map numbers often.

use strict;
use warnings;
my $F = "1:%-5d: ";
while (<>) {
    die "$0: garbled input at line $.\n" unless /^([\d.]+)\s+([\d.]+)$/;
    my $x    = $1;
    my $y    = $2;
    my $n100 = ( $x * 40 ) % 10 + 91 - ( $y * 40 ) % 10 * 10;
    my $n25  = ( $x * 10 ) % 5 + 1 + 5 * ( 4 - ( $y * 20 ) % 5 );
    my $nesw = ( ( $y * 8 ) % 2 ? "N" : "S" ) . ( ( $x * 8 ) % 2 ? "E" : "W" );
    my $xtmp = ( $x * 4 ) % 2;
    my $n4   = ( $y * 4 ) % 2 ? ( $xtmp ? 1 : 4 ) : ( $xtmp ? 2 : 3 );
    my $nx2 = ( ( $x - 73 ) * 2 ) % 100;    #73: 新疆, %:釣魚台
    my $ny2 = int( ( $y - 13.5 ) * 2 );     #南海
    ## https://sjm460405.blogspot.com/2019/02/blog-post.html says 73.5, 14 Hmmm. OK, I didn't add 1.
    print "#$.> $_";
    printf "$F%.02d%.02d-%d-%.03d\n", 5000,  $nx2, $ny2, $n4, $n100;    #.025
    printf "$F%.02d%.02d-%d-%.02d\n", 10000, $nx2, $ny2, $n4, $n25;     #.05
    printf "$F%.02d%.02d-%d-%s\n",    25000, $nx2, $ny2, $n4, $nesw;    #.125
    printf "$F%.02d%.02d-%d\n", 50000, $nx2, $ny2, $n4;                 #.25
    ## https://sjm460405.blogspot.com/2019/02/blog-post.html says 110, x15.3333x he's wrong!!!
    my $nx3 = ( $x - 110 ) * 2 + 1;
    my $ny3 = ( $y - 18 ) * 3 + 1;
    my $n34 = ( $y * 6 ) % 2 ? ( $xtmp ? 1 : 4 ) : ( $xtmp ? 2 : 3 );
    printf "$F%.02d%.02d-%d\n", 50000, $nx3, $ny3, $n34;    #.25x1/6 #2219-1,2
}

#當然不見得所列的圖都有出版，另有外島併入他圖
#$n100:政府設計：本來00至99就可以，豈至100，怕與25衝...
#$n25: the government should also have made it 00 to 05, 00 to 50, total 25.

# Local Variables:
# compile-command: "echo 120.86617 24.18169|./longlat2taiwanmapno"
# End:
