#!/usr/bin/perl
#
# Made by Norbert Ligterink, University Twente, The Netherlands, 28-09-2004
# No warranty, distribute freely, improve possibly.
#
if($#ARGV ne 0){
  print "to calculate the correct IBAN number\n";
  print "USAGE: iban.pl [ nnnnnnnnnnnnnnn | help ]\n";
}else{
$inib = @ARGV[0];
#
# check for the typical non alnum's
#
if($inib !~ m/\_|\.|\=|\-/){
#
# The story of IBAN
#
 if($inib eq "help"){
 print "\nto calculate the correct IBAN number\n";
 print "USAGE: iban.pl nnnnnnnnnnnnnnn -or- (THIS HELP): iban.pl help\n\n";
print "The IBAN number is a concatenation of account number, 
bank details, country details, and the third and fourth digit are
the checksum, which is determined from all other details.\n
This program tests the checksum. If correct, it returns the checksum.
If incorrect, it returns the right checksum, corresponding to the number.
The IBAN number should be something like: NL56ABNA1234567890,
country codes (ISO 2-letters) first.\n
Note: if you have the wrong account number, it can still generate
a correct IBAN number for it!\n\n";
 }else{
#
##################################
#
 $string = '';
 $inib =~ tr/[A-Z]/[a-z]/;
 @list = split('',$inib);
 for $i (@list){
   $j = ord($i);
 #
 # turn letters into double digits
 #
   if($j > 57){$i = $j-87;}
   $string .= $i;
 }
  #
  # remove the checksum
  #
   $str = substr($string,6).substr($string,0,4)."00";
  #
  # succesive mod 97
  #
   while(length($str)>0){
  #
  # just making sure that 01 is 1
  #
   if($num != 0){
      $num .= substr($str,0,1);
   }else{
     $num = substr($str,0,1);
   }
    $str = substr($str,1);
    $num = $num % 97;
   }
  #
  # remainder
  #
   $num = 98-$num;
   if(length($num) < 2){$num = "0".$num;}
   $outib = substr($inib,0,2).$num.substr($inib,4);
  #
  # uppercase looks nicer 
  #
   $inib =~ tr/[a-z]/[A-Z]/;
   $outib =~ tr/[a-z]/[A-Z]/;
   if($inib eq $outib){print "The IBAN: $inib is correct\n";}else{
     print("The IBAN:  $inib\n");
     print("should be: $outib\n");
   }
  }
  }else{
   #
   #  in the case of "." or "-" or "_" or "="
   #
   print "The IBAN number should contain only numbers and letters\n";
  }
}
