#!/usr/bin/perl

use strict;
use warnings;

   calculateImei( "123456789010101" );

# --------------------------------
# calculateIMEI
# --------------------------------

sub calculateImei {

	my $imei = $_[0];
	my $sum;
	my $odd;
	my $even;
	my $chk;

#my @newImei;
   my @change =  (  0, 2, 4, 6, 8, 1, 3, 5, 7, 9 );

# ------------------------------------------------------
#     1. Compute the sum of all digits on odd places.
#     2. Replace the digits on even places by the formula:
#
#        0=>0, 1=>2, 2=>4, 3=>6, 4=>8, 5=>1, 6=>3, 7=>5, 
#        8=>7, 9=>9 and summarize them.
#
#     3. Summarize the two results.
#     4. In case the sum of digits ends in 0, 0 is the 
#        check digit. Otherwise, the checksum is equal to 
#        the number that needs to be added to the result 
#        to get the next highest "round" number.
# ------------------------------------------------------ 

#   $newImei = $imei;
	my @newImei = split (//, $imei); 
   print "@newImei" . "\n";

   $odd = int( $newImei[0] ) + int( $newImei[2] ) + int( $newImei[4] ) + int( $newImei[6] ) +
    	    int( $newImei[8] ) + int( $newImei[10] ) + int( $newImei[12] );

   $even = $change[int( $newImei[1] )] + $change[int( $newImei[3] )] + $change[int( $newImei[5] )] +
    	     $change[int( $newImei[7] )] + $change[int( $newImei[9] )] + $change[int( $newImei[11] )] + $change[int( $newImei[13] )];


   $sum = int($odd) + int($even);
   $sum = $sum % 10;
   $chk = 10 - $sum;
   my $newData = substr($imei,0,14) . $chk;
   return $newData;
}


