#! /usr/local/bin/perl
#
#     palm_lsaddr - Palm address database helper utility for lbdb
#     Copyright (C) 2000 Dave Pearson <davep@davep.org>
#
#     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, USA.

use Palm::PDB;
use Palm::Address;

if ( $#ARGV > -1 )
{
    my $pdb = new Palm::PDB;

    if ( $pdb )
    {
        $pdb->Load( $ARGV[ 0 ] );

        my $record;

        for ( $i = 0, $record = $pdb->{records}[ $i ]; $record; $i++, $record = $pdb->{records}[ $i ] )
        {
            my $name = $record->{fields}{firstName} . " " . $record->{fields}{name};

            # Remove leading and trailing whitespace.
            $name =~ s/\s+$//;
            $name =~ s/^\s+//;

            # If the name is empty, use the company name instead.
            $name = $record->{fields}{company} unless ( length( $name ) > 0 );

            if ( length( $name ) > 0 )
            {
                my $phone;

                # Any of the phone fields could contain an email address.
                foreach $phone ( $record->{fields}{phone1},
                                 $record->{fields}{phone2},
                                 $record->{fields}{phone3},
                                 $record->{fields}{phone4},
                                 $record->{fields}{phone5} )
                {
                    # A phone field can also contain multiple lines.
                    foreach $contact ( split( /\n/, $phone ) )
                    {
                        # Does it look like an email address?
                        # (simply looking for an "@" is a bit lame but it's a
                        # start, feel free to offer a better method of doing
                        # the test)
                        if ( $contact =~ /\@/ )
                        {
                            print "$contact\t$name\t(Palm)\n";
                        }
                    }
                }
            }
        }
    }
}
