#!/usr/bin/perl
# Filename:	dial_wrap
# Author:	David Ljung Madison <DaveSource.com>
# See License:	http://MarginalHacks.com/License
# Description:	Wrapper to "dial"
use strict;

##################################################
# Setup the variables
##################################################
my $PROGNAME = $0;
$PROGNAME =~ s|.*/||;

my $DIAL	= "dial";

# Current area code (don't need to dial this)
my $AREA_CODE		= 415;

# If we only get four digits:
my $EXTENSION_PRE	= "408.999.";

##################################################
# Usage
##################################################
sub usage {
  my $msg;
  foreach $msg (@_) { print "ERROR:  $msg\n"; }
  print "\n";
  print "Usage:\t$PROGNAME <strings>\n";
  print "\tWrapper to dial:  [$DIAL]\n\n";
  exec("$DIAL -h");
  exit -1;
}

sub parse_args {
  my (@strs);
  while ($#ARGV>=0) {
    my $arg=shift(@ARGV);
    if ($arg =~ /^-h$/) { usage(); }
    if ($arg =~ /^-d$/) { $MAIN::DEBUG = 1; next; }
    if ($arg =~ /^-/) { usage("Unknown option: $arg"); }
    if ($arg =~ /^=/) { push(@strs,$arg); next; }
    push(@strs,number($arg));
  }
  usage("No dialing strings defined") unless (@strs);

  @strs;
}

sub number {
  my ($num) = @_;

  $num =~ s/\s//g;

  # Deal with 4 digit work numbers
  $num="$EXTENSION_PRE$1" if ($num =~ /^x?(\d{4})$/);

  # Remove parens
  $num =~ s/[\(\)]//g;

  # Deal with ### ###.####
  $num =~ s/[\.\s]/-/g;

  # Deal with letter->numbers
  if ($num =~ /[a-z]/i) {
    $num =~ s/[abc]/2/ig; $num =~ s/[def]/3/ig;
    $num =~ s/[ghi]/4/ig; $num =~ s/[jkl]/5/ig;
    $num =~ s/[mno]/6/ig; $num =~ s/[pqrs]/7/ig;
    $num =~ s/[tuv]/8/ig; $num =~ s/[wxyz]/9/ig;
    $num =~ s/-//g;
    $num =~ s/^(\d{3})(\d{3})(\d{4})$/$1-$2-$3/g;
    $num =~ s/^(\d{3})(\d{4})$/$1-$2/g;
  }

  # Deal with missing 1
  $num="1-$num" if ($num =~ /^\d{3}-\d{3}-\d{4}$/);

  # Remove superflous local area code
  $num = $1 if ($num =~ /^1-?${AREA_CODE}-?(.+)$/);

  $num;
}

##################################################
# Main code
##################################################
sub main {
  my @strs = parse_args();

  #my $cmd = "$DIAL =ats11=50 @strs";
  my $cmd = "$DIAL @strs";
  print "$cmd\n";
  unless ($MAIN::DEBUG) {
    exec("$cmd");
    usage("Couldn't run dial [$DIAL]");
  }
}
main();
