#!/usr/local/bin/php
<?php
Function domorse($input) {
  $map = array(
        'A' => '.-',
        'B' => '-...',
        'C' => '-.-.',
        'D' => '-..',
        'E' => '.',
        'F' => '..-.',
        'G' => '--.',
        'H' => '....',
        'I' => '..',
        'J' => '.---',
        'K' => '-.-',
        'L' => '.-..',
        'M' => '--',
        'N' => '-.',
        'O' => '---',
        'P' => '.--.',
        'Q' => '--.-',
        'R' => '.-.',
        'S' => '...',
        'T' => '-',
        'U' => '..-',
        'V' => '...-',
        'W' => '.--',
        'X' => '-..-',
        'Y' => '-.--',
        'Z' => '--..',
        '0' => '-----',
        '1' => '.----',
        '2' => '..---',
        '3' => '...--',
        '4' => '....-',
        '5' => '.....',
        '6' => '-....',
        '7' => '--...',
        '8' => '---..',
        '9' => '----.',
        '.' => '.-.-.-',
        ',' => '--..--',
        '?' => '..--..'
  );
  $mapr = array_flip($map);
  if (preg_match('/\w/', $input)) { #word->morse
    $output = preg_replace('#([A-Z0-9.,?])#ie', '\' \'.$map[strtoupper("$1")]', str_replace('-','',$input));
  } else { #morse->word
    $output = preg_replace('#([.-]+)#ie', '$mapr["$1"]', $input);
  }

  return $output;
}

  if (count($argv)>1) {
    array_shift($argv);
    $input = implode(' ', $argv);
    echo domorse($input), "\n";
  } else {
    $fp = fopen('php://stdin', 'r');
    while ( $input = fgets($fp) )
      print domorse($input);
  }