#include <stdio.h>
#include <string.h>
#include <time.h>

int main(int argc, const char *argv[])
{
    char buf[256];
    int  bufpos = 0;
    int  sepno = 0;
    int  newevent = 1;
    struct tm timeptr;

    char *pevent, *pdate, *ptime, *comment = &buf[0];
    char c;

    memset(buf, 0x0, sizeof(buf));

    printf("BEGIN:VCALENDAR\n");
    printf("VERSION:2.0\n");
    printf("PRODID:-//uugrn.org//Event Calendar 1.0//EN\n");
    printf("CALSCALE:GREGORIAN\n");
    printf("METHOD:PUBLISH\n");
    printf("ORGANIZER:Unix User Group Rhein-Neckar\n\n");

    while((c = getc(stdin)) != EOF) {

        if(newevent) {
            printf("BEGIN:VEVENT\n");
            newevent = 0;
        }

        /* append the current charater to our buffer */
        buf[bufpos] = c;

        /* we found a tab or newline */
        if(c == 0x9 || c == 0x0a) {

            /* count it */
            sepno++;

            /* ... and terminate here, so we can print buf */
            buf[bufpos] = 0x0;

            /* skip lines without at least two tabs and one newline */
            if(sepno < 3 && c == 0x0a) {
                bufpos = sepno = 0;
                continue;
            }

            if (sepno == 1)
                printf("SUMMARY:%s\n", buf);

            else if (sepno == 2) {
                strptime(buf, "%d.%m.%Y", &timeptr);
                printf("DTSTART:%.4d%.2d%.2d", 
                        timeptr.tm_year + 1900,
                        timeptr.tm_mon + 1,
                        timeptr.tm_mday);

            } else if (sepno == 3) {
                strptime(buf, "%H:%M", &timeptr);
                printf("%.2d%.2d\n", 
                        timeptr.tm_hour,
                        timeptr.tm_min);
                printf("DTEND:%.2d%.2d\n", 
                        timeptr.tm_hour + 3,
                        timeptr.tm_min);
            }

            else if (sepno == 4)
                printf("DESCRIPTION:%s\n", buf);

            if (c == 0x0a) {
                printf("END:VEVENT\n\n");
                newevent = 1;

                sepno = 0;
            }

            bufpos = 0;
        } else 
            bufpos++;
    }

    printf("END:VCALENDAR\n");

    return 0;
}
