#!/usr/bin/python
# adr_conv.py
#
# Converts a vCard address book into abook addressbook format
#
# Author:   Gavin Costello
# Date:     19.02.2009

import sys

count = -1;
argc = len(sys.argv)

if (argc == 1):
    cfile = open('contacts.vcf', 'r')
elif (argc == 2):
    cfile = open(sys.argv[1], 'r')
else:
    cfile = open(sys.argv[1], 'r')
    afile = open(sys.argv[2], 'w')
    saveout = sys.stdout
    sys.stdout = afile

for line in cfile.readlines():
    if (line.startswith('FN')):
        count += 1
        name = line.split(':')[1]
        print
        print u'[%d]' % count
        print 'name=%s' % name,
    if (line.startswith('BDAY')):
        bday = line.split(':')[1]
        print u'custom1=%s-%s-%s' % (bday[0:4], bday[4:6], bday[6:8])
    if (line.startswith('ADR')):
        adr = line.split(':')[1]
	adr = adr.split(';')
	address = adr[2]
	city = adr[3]
	zip = adr[5]
	country = adr[6]
	if (address is not ''):
            print 'address=%s' % address
	if (city is not ''):
            print 'city=%s' % city
	if (zip is not ''):
            print 'zip=%s' % zip
	if (country is not ''):
            print 'country=%s' % country,
    if (line.startswith('URL')):
        url = line.split(':', 1)[1]
        print u'url=%s' % url,
    if (line.startswith('EMAIL')):
        email = line.split(':')[1]
        print u'email=%s' % email,
    if (line.startswith('TEL')):
        type = line.split(':')[0]
        phone = line.split(':')[1]
        if (type.endswith('CELL')):
            print u'mobile=%s' % phone,
        elif (type.endswith('HOME') or type.endswith('TEL')):
            print u'phone=%s' % phone,
        elif (type.endswith('WORK')):
            print u'work=%s' % phone,

if (argc >= 2):
    sys.stdout = saveout
    afile.close()
cfile.close()

