#!/usr/bin/perl
# sylpheed2txt.pl
# convert sylpheed addressbook into plain text
# 22 May 2003
# Fred Marton <Fred.Marton@uni-bayreuth.de>
# Small changes 3 July 2003 Martin Kluge
#
# Copyright © 2003 Fred Marton
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

# check for argument
&usage if ($#ARGV < 2);
$directory=$ARGV[0];
$filename= $ARGV[1];
$addrbook = $ENV{HOME}.'/'.$directory.'/'.$filename;

# output file
$out = $ARGV[2];
open (IN,$addrbook);
open (OUT,">>$out");
while ($line = <IN>) {
#  split lines into fields
   @field = split(/\"/,$line);
#  get first and last names, nick names, and display names
   if ($field[8] eq " cn=") {
#     add spaces to fields and replace escape sequences
      &space_and_replace;
#     print names
      print OUT $field[3],$field[5],$field[7],$field[9];
   }
#  get and print e-dresses
   if ($field[4] eq " email=") {
      print OUT $field[5],"\n";
   }
}
# all done
close (OUT);
close (IN);

sub usage
{
   die ( " usage: sylpheed2txt.pl ADDR_BOOK_DIR ADDRESS_BOOK_NAME OUTPUT_FILE\n");
}

sub space_and_replace
# if field is non-blank, add a space to its end
# and replace &quot; with quotation mark,
# &amp; with ampersand; more escape sequence
# may be added as necessary
{
   $i = 3;
   while ($i < 11) {
      if ($field[$i] ne "" ) {
         $field[$i] = $field[$i]." ";
         $field[$i] =~ s/&quot;/\"/g;
         $field[$i] =~ s/&amp;/\&/g;
      }
   $i = $i + 2;
   }
}

