#!/usr/local/bin/perl
# 
# elm-to-pine: Convert elm aliases file to pine address book
# Author: Klaus Wacker (wacker@Physik.Uni-Dortmund.DE)
#
# Usage e.g.
# elm-to-pine ~/.elm/aliases.text >~/.addressbook
#
# Option:
#   -s    Create a single address for multiple nicknames by making 
#         additional nicknames point back to the first one.
#
require 'getopt.pl';

# get a line, combining continuation lines
#  that start with whitespace
# (taken from the perl man page and modified)
sub get_line {
    return 0 if $eof;
    $thisline = $lookahead;
    $eof=1;
  line: while ($lookahead = <>) {
      if ($lookahead =~ /^[ \t]/) {
	  $thisline .= $lookahead;
      }
      else {
	  $eof=0;
	  last line;
      }
  }
    $thisline;
}

do Getopt('');

$eof=!($lookahead = <>);	# get first line
while ($_ = do get_line()) {
    next if /^\#/;		# Skip comments
    chop;
    s/\t/ /g;			# Lets not get confused by tabs in the file
    ($nicks,$name,$address)=split(/ *= */,$_,3);
    @nick=split(/ *, */,$nicks);
    ($fullname,$remark)=split(/ *, */,$name,2);
    $fullname =~ s/;/,/;	# Lastname[;,] Firstname
    if ($address =~ /,/ ) {	# Its a list
	$address="(".$address.")";
    }
    foreach $nicki (@nick) {	# Pine doesn't allow multiple nicknames
	printf "%s\t%s\t%s\t\t%s\n",
	$nicki, $fullname, $address, $remark;
	$address = $nick[0] if $opt_s;	# Let additional nicks point to the first one
    }
}
