#!/usr/bin/perl
use constant USAGE => '
台灣TWD(67)座標轉上河出版社地圖集座標。
Taiwan TWD(67) to Sunriver map coordinates.
框外者，如南島71圖A2以左，及非本島者將致誤。
Out of frame and non Taiwan island points will produce errors.
使用例 Usage example:
$ echo 207577 2553333 甲仙|twd2sunriver
#207577 2553333 甲仙
1:50000 南島40圖D 6
1:100000    38圖A14
';
## Copyright       : http://www.fsf.org/copyleft/gpl.html
## Author          : 積丹尼 http://jidanni.org/geo/taipower/sunriver/
## Created On      : Tue Apr 21 17:52:29 2009
## Last Modified On: Wed Apr 22 12:31:00 2009
## Update Count    : 250
use strict;
use warnings FATAL => q(all);
use constant MAP5  => '
-------@@-
-----@@@@@
-----@@@@@
----@@@@@-
----@@@@@-
---@@@@@@-
---@@@@@@-
--@@@@@@@-
--@@@@@@@-
--@@@@@@--
-@@@@@@@--
-@@@@@@@--
-@@@@@@@--
@@@@@@@@--
-@@@@@@@--
@@@@@@@---
@@@@@@@---
-@@@@@@---
-@@@@@@---
-@@@@@----
-@@@@-----
--@@@-----
---@@-----
---@------';
use constant MAP10 => '
----@-
---@@@
--@@@@
--@@@@
-@@@@@
-@@@@-
-@@@@-
@@@@@-
@@@@@-
@@@@@-
@@@@--
-@@@--
-@@@--
--@---
--@---';

while (<>) {
    print "#$_";
    my ( $x, $y ) = /^(\d+)\D(\d+)/ or die USAGE;
    ## 1:50000
    {
        my ( $page, $yl );
        my $xp = $x - 138000;
        if ( $y <= 2439000 ) {    #南島71圖頭行座標「斷層」
            $page = 132;
            $yl   = ( 2439000 - $y ) / 1000;
        }
        else {
            my $yp = 2799000 - $y;
            $page =
              ( substr MAP5, 1, 1 + ( int $xp / 22000 ) + 11 * int $yp / 15000 )
              =~ tr/@//;
            $yl = $yp % 15000 / 1000 + 1;
        }
        printf "1:50000 %s島%2d圖%c%2d\n",
          $page > 61 ? "南"      : "北",
          $page > 61 ? $page - 61 : $page,
          65 + ( $page > 130 ? $xp - 13000 : $xp ) % 22000 / 1000, $yl;
    }
    ## 1:100000
    {
        my ( $xp, $yp ) = ( $x - 130000, 2812000 - $y );
        printf "1:100000    %2d圖%c%2d\n",
          ( substr MAP10, 1, 1 + 7 * ( int $yp / 26000 ) + int $xp / 38000 ) =~
          tr/@//, 65 + $xp % 38000 / 2000, 2 + $yp % 26000 / 2000;
        ## Y擇2-14而非1-13，能含鵝鑾鼻
    }
}
