#!/usr/bin/perl

# A script that converts Israel's old cellphone numbers to the new format.
# Author: Eitan Isaacson <eitan@ascender.com>
# Date 11.5.04

# Number conversion table:
$kidomet{'050'} = '0505';
$kidomet{'051'} = '0507';
$kidomet{'056'} = '0506';
$kidomet{'068'} = '0508';
$kidomet{'057'} = '0577';
$kidomet{'054'} = '0544';
$kidomet{'055'} = '0545';
$kidomet{'066'} = '0546';
$kidomet{'067'} = '0547';
$kidomet{'052'} = '0522';
$kidomet{'053'} = '0523';
$kidomet{'058'} = '0528';
$kidomet{'064'} = '0524';
$kidomet{'065'} = '0525';

if (grep (/-n/,@ARGV)) {
  if (@num = grep(/\d/,@ARGV)) {
    num_convert($num[0]);
    print $num[0]."\n";
  } else {
    while ($a = <STDIN>) {
      chomp ($a);
      num_convert($a);
      print $a."\n";
    }
  }
  exit;
} elsif (grep (/-vc/,@ARGV)) {
  while ($a = <STDIN>) {
    chomp ($a);
    if ($a =~ /^TEL/) {
      $a =~ s/(^TEL.*:)(.*)/$1/;
      $num = $2;
      num_convert($num);
      print $1.$num."\n";
    } else {
      print $a."\n";
    }
  }
  exit;
} else {
  print "Usage: $0 -vc|-n [-itl] <number>\n";
  print "-vc:  Takes vcard format as stdin and prints converted vcard with new numbers\n";
  print "-n:   Takes number as stdin or as second argument and prints converted number\n";
  print "-itl: Gives numbers in international format (+972...)\n";
  exit;
}

sub num_convert {
  $_[0] =~ s/-//g;
# Gets rid of trailing junk on our string.
  $_[0] =~ s/(^.)(\d*)(.*)/$1$2/;
# This takes Israeli numbers in international format and changes them to local format
  $_[0] =~ s/(^\+972)(.*)/0$2/;
  # This is what the script is all about.
  if ((length($_[0]) == 9) && ($_[0] =~ /^05|^06/)) {
    $_[0] =~ s/(^\d{3})(\d*)/$kidomet{$1}$2/;
  } 
  # If -int is given converts number to international format.
  if (grep (/-itl/,@ARGV)) {
    $_[0] =~ s/(^0)(.*)/\+972$2/;
  }
  return $_[0];
}

	
