"""
    csv2eventcal.py  Version 0.90  May 12, 2006
                                                                                                           
    This parses to convert outlook .csv file into EventCalendar event data format.
                                                                                                           
    @copyright: 2006 by Seungik Lee <seungiklee<at>gmail.com>  http://www.silee.net/
    @license: GPL
    
    For more information, please visit http://moinmoin.wikiwikiweb.de/MacroMarket/EventCalendar
    
    Usage:
        $python csv2eventcal.py input_file.csv 
        or $python csv2eventcal.py input_file.csv > result.txt
        
    
    .csv file rules:
         - date format in the form "YYYY-MM-DD" or modify the 'dateformat' below
         - time format in the form "AM HH:MM:SS" or "PM HH:MM:SS" or modify the 'timeformat' below
         - the first line which identyfies the csv fields has to be in english
         - acceptable fields: "Subject","Start Date","Start Time","End Date","End Time","All day event","Description"

    
"""

# Modify the following lines for your format ###

# datetime format of outlook .csv file
dateformat = '%Y-%m-%d'
timeformat = '%p %I:%M:%S'

# datetime format of EventCalendar event data
targetdateformat = '%B %d, %Y'
targettimeformat = '%I:%M %p'
###

def formatdatetime(strdatetime, allday=0, flgend=0):
    datetimeformat = '%s %s' % (dateformat, timeformat)
    EpochSeconds = time.mktime(time.strptime(strdatetime, datetimeformat)) 
    now = datetime.datetime.fromtimestamp(EpochSeconds)
    if allday:
        if flgend:
            now = now + datetime.timedelta(days=-1)
        datetime_fmt = targetdateformat
    else:
        datetime_fmt = '%s %s' % (targetdateformat, targettimeformat)
    return now.strftime(str(datetime_fmt))


## start main

import string, os, StringIO, time, datetime
import codecs, sys

try:
    filename = sys.argv[1]
except IndexError:
    print 'No file specified.'
    sys.exit()

try:
    csvfile = codecs.open(filename, 'r')
except IOError:
    print 'Fail to read "%s".' % filename
    sys.exit()
    
# skip the first line of the fields
in_line = csvfile.readline()
lineno = 1

while 1:
    in_line = csvfile.readline()
    lineno += 1
    
    if in_line == "":
        break
    
    fcount = string.count(in_line, ',')
    
    try:
        if fcount == 5:
            [title, startdate, starttime, enddate, endtime, allday] = string.split(in_line, ',')
            description = ''
        else:
            [title, startdate, starttime, enddate, endtime, allday, description] = string.split(in_line, ',')
    except ValueError:
        print 'PARSE ERROR: line %d syntax error: %s' % (lineno, in_line)
        sys.exit()
        
    title = title[1:-1].replace('""', '"')
    startdate = startdate[1:-1]
    enddate = enddate[1:-1]
    startdate += ' %s' % starttime[1:-1]
    enddate += ' %s' % endtime[1:-1]
    
    if allday[1:-1].startswith('True'):
        allday = 1
    else:
        allday = 0
        
    total_description = []
    
    if description:
        while 1:
            description = description.replace('\n', '')
            description = description.replace('\r', '')
            total_description.append(description)
            if description[-1] != '"':
                description = csvfile.readline()
                lineno += 1
                continue
            else:
                break
        
        total_description = ' '.join(total_description)
        total_description = total_description[1:-1]
        total_description = total_description.replace('\n', ' ')
        total_description = total_description.replace('\r', '')
        total_description = total_description.replace('""', '"')
        
        description = total_description
    
    try:
        startdate = formatdatetime(startdate, allday)
    except ValueError:
        print 'PARSE ERROR: line %d syntax (datetime format) error: %s' % (lineno, startdate)
        sys.exit()
    
    try:
        enddate = formatdatetime(enddate, allday, 1)
    except ValueError:
        print 'PARSE ERROR: line %d syntax (datetime format) error: %s' % (lineno, startdate)
        sys.exit()

    print '== %s ==' % title
    print ' start:: %s' % startdate
    print ' end:: %s' % enddate

    if description:
        print ' description:: %s' % description
    print ''

csvfile.close()
print '----\nCategoryEventCalendar'