#!/usr/bin/perl
# taiwanidchecksum -- 計算台灣國民身份證,居留證字號檢查號碼
# Compute Taiwan citizen and resident identification number checksums
# Copyright       : http://www.fsf.org/copyleft/gpl.html
# Author          : 積丹尼 Dan Jacobson -- http://jidanni.org/comp/checksums/
# Created On      : Sun Jul 11 04:33:18 2004
# Last Modified On: Sun Dec  6 21:33:33 2020
# Update Count    : 110
# 輸入:未冠檢號之身碼,一行一碼
# 輸出:有冠檢號之身碼
# Input: letter+number without checksum, one per line
# Output: letter+number with checksum. 例 Example:
# $ taiwanidchecksum < 'all';
while (<>) {
    chomp;
    die "非未加檢查碼之身份證或居留證字號 Invalid data: \"$_\""
##    unless /^[A-Z]([12][0-3]|[A-D]\d)\d{6}$/;      #12:男女,A-D居留證
      unless /^[A-Z]([12][0-3]|[A-D89]\d)\d{6}$/;    #12:男女,A-D89居留證
    my $id = $_;
    s/(.)([ABCD])(.*)/$1 . ((ord $2) - (ord 'A')) . $3/e;
    my @A = reverse split '',
      index( '__________ABCDEFGHJKLMNPQRSTUVXYWZIO', ( substr $_, 0, 1 ), 10 )
      . substr $_, 1;
    my $total = pop @A;
    my $i     = 0;
    for (@A) { $total += $_ * ++$i }
    printf "$id%d\n", ( 10 - $total % 10 ) % 10;
}

# 所有可能身碼總數為 One notes the maximum number of IDs is
# print 26 * 2 *  4 * 10 ** 6; #=208,000,000, but
# print 26 * 4 ... at least twice as many foreigners?!?
# 參考如 reference http://zh.wikipedia.org/wiki/中華民國國民身分證