summaryrefslogtreecommitdiffstats
path: root/libkcal/vcalformat.cpp
blob: 973f8c2279d15810c254dac04254f51c24d30cfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
/*
    This file is part of libkcal.

    Copyright (c) 1998 Preston Brown <[email protected]>
    Copyright (c) 2001 Cornelius Schumacher <[email protected]>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <tqapplication.h>
#include <tqdatetime.h>
#include <tqstring.h>
#include <tqptrlist.h>
#include <tqregexp.h>
#include <tqclipboard.h>
#include <tqdialog.h>
#include <tqfile.h>

#include <kdebug.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <klocale.h>

#include "vcc.h"
#include "vobject.h"
extern "C" {
#include <libical/icaltime.h>
#include <libical/icaltimezone.h>
}
#include "vcaldrag.h"
#include "calendar.h"

#include "vcalformat.h"

using namespace KCal;

VCalFormat::VCalFormat()
{
}

VCalFormat::~VCalFormat()
{
}

bool VCalFormat::load(Calendar *calendar, const TQString &fileName)
{
  mCalendar = calendar;

  clearException();

  kdDebug(5800) << "VCalFormat::load() " << fileName << endl;

  VObject *vcal = 0;

  // this is not necessarily only 1 vcal.  Could be many vcals, or include
  // a vcard...
  vcal = Parse_MIME_FromFileName(const_cast<char *>(TQFile::encodeName(fileName).data()));

  if (!vcal) {
    setException(new ErrorFormat(ErrorFormat::CalVersionUnknown));
    return FALSE;
  }

  // any other top-level calendar stuff should be added/initialized here

  // put all vobjects into their proper places
  populate(vcal);

  // clean up from vcal API stuff
  cleanVObjects(vcal);
  cleanStrTbl();

  return true;
}


bool VCalFormat::save(Calendar *calendar, const TQString &fileName)
{
  mCalendar = calendar;

  TQString tmpStr;
  VObject *vcal, *vo;

  kdDebug(5800) << "VCalFormat::save(): " << fileName << endl;

  vcal = newVObject(VCCalProp);

  //  addPropValue(vcal,VCLocationProp, "0.0");
  addPropValue(vcal,VCProdIdProp, productId().latin1());
  addPropValue(vcal,VCVersionProp, _VCAL_VERSION);

  // TODO STUFF
  Todo::List todoList = mCalendar->rawTodos();
  Todo::List::ConstIterator it;
  for ( it = todoList.begin(); it != todoList.end(); ++it ) {
    vo = eventToVTodo( *it );
    addVObjectProp( vcal, vo );
  }

  // EVENT STUFF
  Event::List events = mCalendar->rawEvents();
  Event::List::ConstIterator it2;
  for( it2 = events.begin(); it2 != events.end(); ++it2 ) {
    vo = eventToVEvent( *it2 );
    addVObjectProp( vcal, vo );
  }

  writeVObjectToFile(TQFile::encodeName(fileName).data() ,vcal);
  cleanVObjects(vcal);
  cleanStrTbl();

  if (TQFile::exists(fileName)) {
    kdDebug(5800) << "No error" << endl;
    return true;
  } else  {
    kdDebug(5800) << "Error" << endl;
    return false; // error
  }

  return false;
}

bool VCalFormat::fromString( Calendar *calendar, const TQString &text )
{
  // TODO: Factor out VCalFormat::fromString()
  mCalendar = calendar;

  TQCString data = text.utf8();

  if ( !data.size() ) return false;

  VObject *vcal = Parse_MIME( data.data(), data.size());
  if ( !vcal ) return false;

  VObjectIterator i;
  VObject *curvo;
  initPropIterator( &i, vcal );

  // we only take the first object. TODO: parse all incidences.
  do  {
    curvo = nextVObject( &i );
  } while ( strcmp( vObjectName( curvo ), VCEventProp ) &&
            strcmp( vObjectName( curvo ), VCTodoProp ) );

  if ( strcmp( vObjectName( curvo ), VCEventProp ) == 0 ) {
    Event *event = VEventToEvent( curvo );
    calendar->addEvent( event );
  } else {
    kdDebug(5800) << "VCalFormat::fromString(): Unknown object type." << endl;
    deleteVObject( vcal );
    return false;
  }

  deleteVObject( vcal );

  return true;
}

TQString VCalFormat::toString( Calendar *calendar )
{
  // TODO: Factor out VCalFormat::asString()
  mCalendar = calendar;

  VObject *vcal = newVObject(VCCalProp);

  addPropValue( vcal, VCProdIdProp, CalFormat::productId().latin1() );
  addPropValue( vcal, VCVersionProp, _VCAL_VERSION );

  // TODO: Use all data.
  Event::List events = calendar->events();
  Event *event = events.first();
  if ( !event ) {
    cleanVObject( vcal );
    return TQString();
  }

  VObject *vevent = eventToVEvent( event );

  addVObjectProp( vcal, vevent );

  char *buf = writeMemVObject( 0, 0, vcal );

  TQString result( buf );

  cleanVObject( vcal );

  return result;
}

VObject *VCalFormat::eventToVTodo(const Todo *anEvent)
{
  VObject *vtodo;
  TQString tmpStr;

  vtodo = newVObject(VCTodoProp);

  // due date
  if (anEvent->hasDueDate()) {
    tmpStr = qDateTimeToISO(anEvent->dtDue(),
                            !anEvent->doesFloat());
    addPropValue(vtodo, VCDueProp, tmpStr.local8Bit());
  }

  // start date
  if (anEvent->hasStartDate()) {
    tmpStr = qDateTimeToISO(anEvent->dtStart(),
                            !anEvent->doesFloat());
    addPropValue(vtodo, VCDTstartProp, tmpStr.local8Bit());
  }

  // creation date
  tmpStr = qDateTimeToISO(anEvent->created());
  addPropValue(vtodo, VCDCreatedProp, tmpStr.local8Bit());

  // unique id
  addPropValue(vtodo, VCUniqueStringProp,
               anEvent->uid().local8Bit());

  // revision
  tmpStr.sprintf("%i", anEvent->revision());
  addPropValue(vtodo, VCSequenceProp, tmpStr.local8Bit());

  // last modification date
  tmpStr = qDateTimeToISO(anEvent->lastModified());
  addPropValue(vtodo, VCLastModifiedProp, tmpStr.local8Bit());

  // organizer stuff
  // @TODO: How about the common name?
  tmpStr = "MAILTO:" + anEvent->organizer().email();
  addPropValue(vtodo, ICOrganizerProp, tmpStr.local8Bit());

  // attendees
  if ( anEvent->attendeeCount() > 0 ) {
    Attendee::List::ConstIterator it;
    Attendee *curAttendee;
    for ( it = anEvent->attendees().begin(); it != anEvent->attendees().end();
          ++it ) {
      curAttendee = *it;
      if (!curAttendee->email().isEmpty() &&
          !curAttendee->name().isEmpty())
        tmpStr = "MAILTO:" + curAttendee->name() + " <" +
                 curAttendee->email() + ">";
      else if (curAttendee->name().isEmpty())
        tmpStr = "MAILTO: " + curAttendee->email();
      else if (curAttendee->email().isEmpty())
        tmpStr = "MAILTO: " + curAttendee->name();
      else if (curAttendee->name().isEmpty() &&
               curAttendee->email().isEmpty())
        kdDebug(5800) << "warning! this Event has an attendee w/o name or email!" << endl;
      VObject *aProp = addPropValue(vtodo, VCAttendeeProp, tmpStr.local8Bit());
      addPropValue(aProp, VCRSVPProp, curAttendee->RSVP() ? "TRUE" : "FALSE");
      addPropValue(aProp, VCStatusProp, writetqStatus(curAttendee->status()));
    }
  }

  // description BL:
  if (!anEvent->description().isEmpty()) {
    VObject *d = addPropValue(vtodo, VCDescriptionProp,
                              anEvent->description().local8Bit());
    if (anEvent->description().tqfind('\n') != -1)
      addPropValue(d, VCEncodingProp, VCQuotedPrintableProp);
  }

  // summary
  if (!anEvent->summary().isEmpty())
    addPropValue(vtodo, VCSummaryProp, anEvent->summary().local8Bit());

  // location
  if (!anEvent->location().isEmpty())
    addPropValue(vtodo, VCLocationProp, anEvent->location().local8Bit());

  // completed
  // status
  // backward compatibility, KOrganizer used to interpret only these two values
  addPropValue(vtodo, VCStatusProp, anEvent->isCompleted() ? "COMPLETED" :
                                                             "NEEDS_ACTION");
  // completion date
  if (anEvent->hasCompletedDate()) {
    tmpStr = qDateTimeToISO(anEvent->completed());
    addPropValue(vtodo, VCCompletedProp, tmpStr.local8Bit());
  }

  // priority
  tmpStr.sprintf("%i",anEvent->priority());
  addPropValue(vtodo, VCPriorityProp, tmpStr.local8Bit());

  // related event
  if (anEvent->relatedTo()) {
    addPropValue(vtodo, VCRelatedToProp,
                 anEvent->relatedTo()->uid().local8Bit());
  }

  // categories
  TQStringList tmpStrList = anEvent->categories();
  tmpStr = "";
  TQString catStr;
  for ( TQStringList::Iterator it = tmpStrList.begin();
        it != tmpStrList.end();
        ++it ) {
    catStr = *it;
    if (catStr[0] == ' ')
      tmpStr += catStr.mid(1);
    else
      tmpStr += catStr;
    // this must be a ';' character as the vCalendar specification requires!
    // vcc.y has been hacked to translate the ';' to a ',' when the vcal is
    // read in.
    tmpStr += ";";
  }
  if (!tmpStr.isEmpty()) {
    tmpStr.truncate(tmpStr.length()-1);
    addPropValue(vtodo, VCCategoriesProp, tmpStr.local8Bit());
  }

  // alarm stuff
  kdDebug(5800) << "vcalformat::eventToVTodo was called" << endl;
  Alarm::List::ConstIterator it;
  for ( it = anEvent->alarms().begin(); it != anEvent->alarms().end(); ++it ) {
    Alarm *alarm = *it;
    if (alarm->enabled()) {
      VObject *a = addProp(vtodo, VCDAlarmProp);
      tmpStr = qDateTimeToISO(alarm->time());
      addPropValue(a, VCRunTimeProp, tmpStr.local8Bit());
      addPropValue(a, VCRepeatCountProp, "1");
      addPropValue(a, VCDisplayStringProp, "beep!");
      if (alarm->type() == Alarm::Audio) {
        a = addProp(vtodo, VCAAlarmProp);
        addPropValue(a, VCRunTimeProp, tmpStr.local8Bit());
        addPropValue(a, VCRepeatCountProp, "1");
        addPropValue(a, VCAudioContentProp, TQFile::encodeName(alarm->audioFile()));
      }
      else if (alarm->type() == Alarm::Procedure) {
        a = addProp(vtodo, VCPAlarmProp);
        addPropValue(a, VCRunTimeProp, tmpStr.local8Bit());
        addPropValue(a, VCRepeatCountProp, "1");
        addPropValue(a, VCProcedureNameProp, TQFile::encodeName(alarm->programFile()));
      }
    }
  }

  if (anEvent->pilotId()) {
    // pilot sync stuff
    tmpStr.sprintf("%lu",anEvent->pilotId());
    addPropValue(vtodo, KPilotIdProp, tmpStr.local8Bit());
    tmpStr.sprintf("%i",anEvent->synctqStatus());
    addPropValue(vtodo, KPiloStatusProp, tmpStr.local8Bit());
  }

  return vtodo;
}

VObject* VCalFormat::eventToVEvent(const Event *anEvent)
{
  VObject *vevent;
  TQString tmpStr;

  vevent = newVObject(VCEventProp);

  // start and end time
  tmpStr = qDateTimeToISO(anEvent->dtStart(),
                          !anEvent->doesFloat());
  addPropValue(vevent, VCDTstartProp, tmpStr.local8Bit());

  // events that have time associated but take up no time should
  // not have both DTSTART and DTEND.
  if (anEvent->dtStart() != anEvent->dtEnd()) {
    tmpStr = qDateTimeToISO(anEvent->dtEnd(),
                            !anEvent->doesFloat());
    addPropValue(vevent, VCDTendProp, tmpStr.local8Bit());
  }

  // creation date
  tmpStr = qDateTimeToISO(anEvent->created());
  addPropValue(vevent, VCDCreatedProp, tmpStr.local8Bit());

  // unique id
  addPropValue(vevent, VCUniqueStringProp,
               anEvent->uid().local8Bit());

  // revision
  tmpStr.sprintf("%i", anEvent->revision());
  addPropValue(vevent, VCSequenceProp, tmpStr.local8Bit());

  // last modification date
  tmpStr = qDateTimeToISO(anEvent->lastModified());
  addPropValue(vevent, VCLastModifiedProp, tmpStr.local8Bit());

  // attendee and organizer stuff
  // TODO: What to do with the common name?
  tmpStr = "MAILTO:" + anEvent->organizer().email();
  addPropValue(vevent, ICOrganizerProp, tmpStr.local8Bit());

  // TODO: Put this functionality into Attendee class
  if ( anEvent->attendeeCount() > 0 ) {
    Attendee::List::ConstIterator it;
    for ( it = anEvent->attendees().begin(); it != anEvent->attendees().end();
          ++it ) {
      Attendee *curAttendee = *it;
      if (!curAttendee->email().isEmpty() &&
          !curAttendee->name().isEmpty())
        tmpStr = "MAILTO:" + curAttendee->name() + " <" +
                 curAttendee->email() + ">";
      else if (curAttendee->name().isEmpty())
        tmpStr = "MAILTO: " + curAttendee->email();
      else if (curAttendee->email().isEmpty())
        tmpStr = "MAILTO: " + curAttendee->name();
      else if (curAttendee->name().isEmpty() &&
               curAttendee->email().isEmpty())
        kdDebug(5800) << "warning! this Event has an attendee w/o name or email!" << endl;
      VObject *aProp = addPropValue(vevent, VCAttendeeProp, tmpStr.local8Bit());
      addPropValue(aProp, VCRSVPProp, curAttendee->RSVP() ? "TRUE" : "FALSE");
      addPropValue(aProp, VCStatusProp, writetqStatus(curAttendee->status()));
    }
  }

  // recurrence rule stuff
  const Recurrence *recur = anEvent->recurrence();
  if ( recur->doesRecur() ) {
    bool validRecur = true;
    TQString tmpStr2;
    switch ( recur->recurrenceType() ) {
    case Recurrence::rDaily:
      tmpStr.sprintf("D%i ",recur->frequency());
      break;
    case Recurrence::rWeekly:
      tmpStr.sprintf("W%i ",recur->frequency());
      for (int i = 0; i < 7; i++ ) {
        TQBitArray days ( recur->days() );
        if ( days.testBit(i) )
          tmpStr += dayFromNum(i);
      }
      break;
    case Recurrence::rMonthlyPos: {
      tmpStr.sprintf("MP%i ", recur->frequency());
      // write out all rMonthPos's
      TQValueList<RecurrenceRule::WDayPos> tmpPositions = recur->monthPositions();
      for ( TQValueListConstIterator<RecurrenceRule::WDayPos> posit = tmpPositions.begin();
            posit != tmpPositions.end(); ++posit ) {
        int pos = (*posit).pos();
        tmpStr2.sprintf("%i", (pos>0) ? pos : (-pos) );
        if ( pos < 0)
          tmpStr2 += "- ";
        else
          tmpStr2 += "+ ";
        tmpStr += tmpStr2;
        tmpStr += dayFromNum( (*posit).day() - 1 );
      }
      break; }
    case Recurrence::rMonthlyDay: {
      tmpStr.sprintf("MD%i ", recur->frequency());
      // write out all rMonthDays;
      TQValueList<int> tmpDays = recur->monthDays();
      for ( TQValueListIterator<int> tmpDay = tmpDays.begin();
            tmpDay != tmpDays.end(); ++tmpDay ) {
        tmpStr2.sprintf( "%i ", *tmpDay );
        tmpStr += tmpStr2;
      }
      break; }
    case Recurrence::rYearlyMonth: {
      tmpStr.sprintf("YM%i ", recur->frequency());
      // write out all the months;'
      // TODO: Any way to write out the day within the month???
      TQValueList<int> months = recur->yearMonths();
      for ( TQValueListIterator<int> mit = months.begin();
            mit != months.end(); ++mit ) {
        tmpStr2.sprintf( "%i ", *mit );
        tmpStr += tmpStr2;
      }
      break; }
    case Recurrence::rYearlyDay: {
      tmpStr.sprintf("YD%i ", recur->frequency());
      // write out all the rYearNums;
      TQValueList<int> tmpDays = recur->yearDays();
      for ( TQValueListIterator<int> tmpDay = tmpDays.begin();
            tmpDay != tmpDays.end(); ++tmpDay ) {
        tmpStr2.sprintf( "%i ", *tmpDay );
        tmpStr += tmpStr2;
      }
      break; }
    default:
      // TODO: Write rYearlyPos and arbitrary rules!
      kdDebug(5800) << "ERROR, it should never get here in eventToVEvent!" << endl;
      validRecur = false;
      break;
    } // switch

    if (recur->duration() > 0) {
      tmpStr2.sprintf("#%i",recur->duration());
      tmpStr += tmpStr2;
    } else if (recur->duration() == -1) {
      tmpStr += "#0"; // defined as repeat forever
    } else {
      tmpStr += qDateTimeToISO(recur->endDateTime(), FALSE);
    }
    // Only write out the rrule if we have a valid recurrence (i.e. a known
    // type in thee switch above)
    if ( validRecur )
      addPropValue(vevent,VCRRuleProp, tmpStr.local8Bit());

  } // event repeats

  // exceptions to recurrence
  DateList dateList = recur->exDates();
  DateList::ConstIterator it;
  TQString tmpStr2;

  for (it = dateList.begin(); it != dateList.end(); ++it) {
    tmpStr = qDateToISO(*it) + ";";
    tmpStr2 += tmpStr;
  }
  if (!tmpStr2.isEmpty()) {
    tmpStr2.truncate(tmpStr2.length()-1);
    addPropValue(vevent, VCExDateProp, tmpStr2.local8Bit());
  }

  // description
  if (!anEvent->description().isEmpty()) {
    VObject *d = addPropValue(vevent, VCDescriptionProp,
                              anEvent->description().local8Bit());
    if (anEvent->description().tqfind('\n') != -1)
      addPropValue(d, VCEncodingProp, VCQuotedPrintableProp);
  }

  // summary
  if (!anEvent->summary().isEmpty())
    addPropValue(vevent, VCSummaryProp, anEvent->summary().local8Bit());

  // location
  if (!anEvent->location().isEmpty())
    addPropValue(vevent, VCLocationProp, anEvent->location().local8Bit());

  // status
// TODO: define Event status
//  addPropValue(vevent, VCStatusProp, anEvent->statusStr().local8Bit());

  // secrecy
  const char *text = 0;
  switch (anEvent->secrecy()) {
    case Incidence::SecrecyPublic:
      text = "PUBLIC";
      break;
    case Incidence::SecrecyPrivate:
      text = "PRIVATE";
      break;
    case Incidence::SecrecyConfidential:
      text = "CONFIDENTIAL";
      break;
  }
  if (text) {
    addPropValue(vevent, VCClassProp, text);
  }

  // categories
  TQStringList tmpStrList = anEvent->categories();
  tmpStr = "";
  TQString catStr;
  for ( TQStringList::Iterator it = tmpStrList.begin();
        it != tmpStrList.end();
        ++it ) {
    catStr = *it;
    if (catStr[0] == ' ')
      tmpStr += catStr.mid(1);
    else
      tmpStr += catStr;
    // this must be a ';' character as the vCalendar specification requires!
    // vcc.y has been hacked to translate the ';' to a ',' when the vcal is
    // read in.
    tmpStr += ";";
  }
  if (!tmpStr.isEmpty()) {
    tmpStr.truncate(tmpStr.length()-1);
    addPropValue(vevent, VCCategoriesProp, tmpStr.local8Bit());
  }

  // attachments
  // TODO: handle binary attachments!
  Attachment::List attachments = anEvent->attachments();
  Attachment::List::ConstIterator atIt;
  for ( atIt = attachments.begin(); atIt != attachments.end(); ++atIt )
    addPropValue( vevent, VCAttachProp, (*atIt)->uri().local8Bit() );

  // resources
  tmpStrList = anEvent->resources();
  tmpStr = tmpStrList.join(";");
  if (!tmpStr.isEmpty())
    addPropValue(vevent, VCResourcesProp, tmpStr.local8Bit());

  // alarm stuff
  Alarm::List::ConstIterator it2;
  for ( it2 = anEvent->alarms().begin(); it2 != anEvent->alarms().end(); ++it2 ) {
    Alarm *alarm = *it2;
    if (alarm->enabled()) {
      VObject *a = addProp(vevent, VCDAlarmProp);
      tmpStr = qDateTimeToISO(alarm->time());
      addPropValue(a, VCRunTimeProp, tmpStr.local8Bit());
      addPropValue(a, VCRepeatCountProp, "1");
      addPropValue(a, VCDisplayStringProp, "beep!");
      if (alarm->type() == Alarm::Audio) {
        a = addProp(vevent, VCAAlarmProp);
        addPropValue(a, VCRunTimeProp, tmpStr.local8Bit());
        addPropValue(a, VCRepeatCountProp, "1");
        addPropValue(a, VCAudioContentProp, TQFile::encodeName(alarm->audioFile()));
      }
      if (alarm->type() == Alarm::Procedure) {
        a = addProp(vevent, VCPAlarmProp);
        addPropValue(a, VCRunTimeProp, tmpStr.local8Bit());
        addPropValue(a, VCRepeatCountProp, "1");
        addPropValue(a, VCProcedureNameProp, TQFile::encodeName(alarm->programFile()));
      }
    }
  }

  // priority
  tmpStr.sprintf("%i",anEvent->priority());
  addPropValue(vevent, VCPriorityProp, tmpStr.local8Bit());

  // transparency
  tmpStr.sprintf("%i",anEvent->transparency());
  addPropValue(vevent, VCTranspProp, tmpStr.local8Bit());

  // related event
  if (anEvent->relatedTo()) {
    addPropValue(vevent, VCRelatedToProp,
                 anEvent->relatedTo()->uid().local8Bit());
  }

  if (anEvent->pilotId()) {
    // pilot sync stuff
    tmpStr.sprintf("%lu",anEvent->pilotId());
    addPropValue(vevent, KPilotIdProp, tmpStr.local8Bit());
    tmpStr.sprintf("%i",anEvent->synctqStatus());
    addPropValue(vevent, KPiloStatusProp, tmpStr.local8Bit());
  }

  return vevent;
}

Todo *VCalFormat::VTodoToEvent(VObject *vtodo)
{
  VObject *vo;
  VObjectIterator voi;
  char *s;

  Todo *anEvent = new Todo;

  // creation date
  if ((vo = isAPropertyOf(vtodo, VCDCreatedProp)) != 0) {
      anEvent->setCreated(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
      deleteStr(s);
  }

  // unique id
  vo = isAPropertyOf(vtodo, VCUniqueStringProp);
  // while the UID property is preferred, it is not required.  We'll use the
  // default Event UID if none is given.
  if (vo) {
    anEvent->setUid(s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
  }

  // last modification date
  if ((vo = isAPropertyOf(vtodo, VCLastModifiedProp)) != 0) {
    anEvent->setLastModified(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setLastModified(TQDateTime(TQDate::tqcurrentDate(),
                                       TQTime::currentTime()));

  // organizer
  // if our extension property for the event's ORGANIZER exists, add it.
  if ((vo = isAPropertyOf(vtodo, ICOrganizerProp)) != 0) {
    anEvent->setOrganizer( s = fakeCString(vObjectUStringZValue(vo) ) );
    deleteStr(s);
  } else {
    anEvent->setOrganizer( mCalendar->getOwner() );
  }

  // attendees.
  initPropIterator(&voi, vtodo);
  while (moreIteration(&voi)) {
    vo = nextVObject(&voi);
    if (strcmp(vObjectName(vo), VCAttendeeProp) == 0) {
      Attendee *a;
      VObject *vp;
      s = fakeCString(vObjectUStringZValue(vo));
      TQString tmpStr = TQString::fromLocal8Bit(s);
      deleteStr(s);
      tmpStr = tmpStr.simplifyWhiteSpace();
      int emailPos1, emailPos2;
      if ((emailPos1 = tmpStr.tqfind('<')) > 0) {
        // both email address and name
        emailPos2 = tmpStr.tqfindRev('>');
        a = new Attendee(tmpStr.left(emailPos1 - 1),
                         tmpStr.mid(emailPos1 + 1,
                                    emailPos2 - (emailPos1 + 1)));
      } else if (tmpStr.tqfind('@') > 0) {
        // just an email address
        a = new Attendee(0, tmpStr);
      } else {
        // just a name
        // WTF??? Replacing the spaces of a name and using this as email?
        TQString email = tmpStr.tqreplace( ' ', '.' );
        a = new Attendee(tmpStr,email);
      }

      // is there an RSVP property?
      if ((vp = isAPropertyOf(vo, VCRSVPProp)) != 0)
        a->setRSVP(vObjectStringZValue(vp));
      // is there a status property?
      if ((vp = isAPropertyOf(vo, VCStatusProp)) != 0)
        a->setqStatus(readtqStatus(vObjectStringZValue(vp)));
      // add the attendee
      anEvent->addAttendee(a);
    }
  }

  // description for todo
  if ((vo = isAPropertyOf(vtodo, VCDescriptionProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    anEvent->setDescription(TQString::fromLocal8Bit(s));
    deleteStr(s);
  }

  // summary
  if ((vo = isAPropertyOf(vtodo, VCSummaryProp))) {
    s = fakeCString(vObjectUStringZValue(vo));
    anEvent->setSummary(TQString::fromLocal8Bit(s));
    deleteStr(s);
  }


  // location
  if ((vo = isAPropertyOf(vtodo, VCLocationProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    anEvent->setLocation( TQString::fromLocal8Bit(s) );
    deleteStr(s);
  }
  // completed
  // was: status
  if ((vo = isAPropertyOf(vtodo, VCStatusProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    if (strcmp(s,"COMPLETED") == 0) {
      anEvent->setCompleted(true);
    } else {
      anEvent->setCompleted(false);
    }
    deleteStr(s);
  }
  else
    anEvent->setCompleted(false);

  // completion date
  if ((vo = isAPropertyOf(vtodo, VCCompletedProp)) != 0) {
    anEvent->setCompleted(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }

  // priority
  if ((vo = isAPropertyOf(vtodo, VCPriorityProp))) {
    anEvent->setPriority(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }

  // due date
  if ((vo = isAPropertyOf(vtodo, VCDueProp)) != 0) {
    anEvent->setDtDue(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
    anEvent->setHasDueDate(true);
  } else {
    anEvent->setHasDueDate(false);
  }

  // start time
  if ((vo = isAPropertyOf(vtodo, VCDTstartProp)) != 0) {
    anEvent->setDtStart(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
    //    kdDebug(5800) << "s is " << //          s << ", ISO is " << ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))).toString() << endl;
    deleteStr(s);
    anEvent->setHasStartDate(true);
  } else {
    anEvent->setHasStartDate(false);
  }

  /* alarm stuff */
  //kdDebug(5800) << "vcalformat::VTodoToEvent called" << endl;
  if ((vo = isAPropertyOf(vtodo, VCDAlarmProp))) {
    Alarm* alarm = anEvent->newAlarm();
    VObject *a;
    if ((a = isAPropertyOf(vo, VCRunTimeProp))) {
      alarm->setTime(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(a))));
      deleteStr(s);
    }
    alarm->setEnabled(true);
    if ((vo = isAPropertyOf(vtodo, VCPAlarmProp))) {
      if ((a = isAPropertyOf(vo, VCProcedureNameProp))) {
        s = fakeCString(vObjectUStringZValue(a));
        alarm->setProcedureAlarm(TQFile::decodeName(s));
        deleteStr(s);
      }
    }
    if ((vo = isAPropertyOf(vtodo, VCAAlarmProp))) {
      if ((a = isAPropertyOf(vo, VCAudioContentProp))) {
        s = fakeCString(vObjectUStringZValue(a));
        alarm->setAudioAlarm(TQFile::decodeName(s));
        deleteStr(s);
      }
    }
  }

  // related todo
  if ((vo = isAPropertyOf(vtodo, VCRelatedToProp)) != 0) {
    anEvent->setRelatedToUid(s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
    mTodosRelate.append(anEvent);
  }

  // categories
  if ((vo = isAPropertyOf(vtodo, VCCategoriesProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    TQString categories = TQString::fromLocal8Bit(s);
    deleteStr(s);
    TQStringList tmpStrList = TQStringList::split( ';', categories );
    anEvent->setCategories(tmpStrList);
  }

  /* PILOT SYNC STUFF */
  if ((vo = isAPropertyOf(vtodo, KPilotIdProp))) {
    anEvent->setPilotId(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setPilotId(0);

  if ((vo = isAPropertyOf(vtodo, KPiloStatusProp))) {
    anEvent->setSynctqStatus(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setSynctqStatus(Event::SYNCMOD);

  return anEvent;
}

Event* VCalFormat::VEventToEvent(VObject *vevent)
{
  VObject *vo;
  VObjectIterator voi;
  char *s;

  Event *anEvent = new Event;

  // creation date
  if ((vo = isAPropertyOf(vevent, VCDCreatedProp)) != 0) {
      anEvent->setCreated(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
      deleteStr(s);
  }

  // unique id
  vo = isAPropertyOf(vevent, VCUniqueStringProp);
  // while the UID property is preferred, it is not required.  We'll use the
  // default Event UID if none is given.
  if (vo) {
    anEvent->setUid(s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
  }

  // revision
  // again NSCAL doesn't give us much to work with, so we improvise...
  if ((vo = isAPropertyOf(vevent, VCSequenceProp)) != 0) {
    anEvent->setRevision(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setRevision(0);

  // last modification date
  if ((vo = isAPropertyOf(vevent, VCLastModifiedProp)) != 0) {
    anEvent->setLastModified(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setLastModified(TQDateTime(TQDate::tqcurrentDate(),
                                       TQTime::currentTime()));

  // organizer
  // if our extension property for the event's ORGANIZER exists, add it.
  if ((vo = isAPropertyOf(vevent, ICOrganizerProp)) != 0) {
    // FIXME:  Also use the full name, not just the email address
    anEvent->setOrganizer( s = fakeCString(vObjectUStringZValue(vo) ) );
    deleteStr(s);
  } else {
    anEvent->setOrganizer( mCalendar->getOwner() );
  }

  // deal with attendees.
  initPropIterator(&voi, vevent);
  while (moreIteration(&voi)) {
    vo = nextVObject(&voi);
    if (strcmp(vObjectName(vo), VCAttendeeProp) == 0) {
      Attendee *a;
      VObject *vp;
      s = fakeCString(vObjectUStringZValue(vo));
      TQString tmpStr = TQString::fromLocal8Bit(s);
      deleteStr(s);
      tmpStr = tmpStr.simplifyWhiteSpace();
      int emailPos1, emailPos2;
      if ((emailPos1 = tmpStr.tqfind('<')) > 0) {
        // both email address and name
        emailPos2 = tmpStr.tqfindRev('>');
        a = new Attendee(tmpStr.left(emailPos1 - 1),
                         tmpStr.mid(emailPos1 + 1,
                                    emailPos2 - (emailPos1 + 1)));
      } else if (tmpStr.tqfind('@') > 0) {
        // just an email address
        a = new Attendee(0, tmpStr);
      } else {
        // just a name
        TQString email = tmpStr.tqreplace( ' ', '.' );
        a = new Attendee(tmpStr,email);
      }

      // is there an RSVP property?
      if ((vp = isAPropertyOf(vo, VCRSVPProp)) != 0)
        a->setRSVP(vObjectStringZValue(vp));
      // is there a status property?
      if ((vp = isAPropertyOf(vo, VCStatusProp)) != 0)
        a->setqStatus(readtqStatus(vObjectStringZValue(vp)));
      // add the attendee
      anEvent->addAttendee(a);
    }
  }

  // This isn't strictly true.  An event that doesn't have a start time
  // or an end time doesn't "float", it has an anchor in time but it doesn't
  // "take up" any time.
  /*if ((isAPropertyOf(vevent, VCDTstartProp) == 0) ||
      (isAPropertyOf(vevent, VCDTendProp) == 0)) {
    anEvent->setFloats(TRUE);
    } else {
    }*/

  anEvent->setFloats(FALSE);

  // start time
  if ((vo = isAPropertyOf(vevent, VCDTstartProp)) != 0) {
    anEvent->setDtStart(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
    //    kdDebug(5800) << "s is " << //          s << ", ISO is " << ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))).toString() << endl;
    deleteStr(s);
    if (anEvent->dtStart().time().isNull())
      anEvent->setFloats(TRUE);
  }

  // stop time
  if ((vo = isAPropertyOf(vevent, VCDTendProp)) != 0) {
    anEvent->setDtEnd(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(vo))));
      deleteStr(s);
      if (anEvent->dtEnd().time().isNull())
        anEvent->setFloats(TRUE);
  }

  // at this point, there should be at least a start or end time.
  // fix up for events that take up no time but have a time associated
  if (!(vo = isAPropertyOf(vevent, VCDTstartProp)))
    anEvent->setDtStart(anEvent->dtEnd());
  if (!(vo = isAPropertyOf(vevent, VCDTendProp)))
    anEvent->setDtEnd(anEvent->dtStart());

  ///////////////////////////////////////////////////////////////////////////

  // repeat stuff
  if ((vo = isAPropertyOf(vevent, VCRRuleProp)) != 0) {
    TQString tmpStr = (s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
    tmpStr.simplifyWhiteSpace();
    tmpStr = tmpStr.upper();
// kdDebug() <<" We have a recurrence rule: " << tmpStr<< endl;

    // first, read the type of the recurrence
    int typelen = 1;
    uint type = Recurrence::rNone;
    if ( tmpStr.left(1) == "D") {
      type = Recurrence::rDaily;
    } else if ( tmpStr.left(1) == "W") {
      type = Recurrence::rWeekly;
    } else {
      typelen = 2;
      if ( tmpStr.left(2) == "MP") {
        type = Recurrence::rMonthlyPos;
      } else if ( tmpStr.left(2) == "MD" ) {
        type = Recurrence::rMonthlyDay;
      } else if ( tmpStr.left(2) == "YM" ) {
        type = Recurrence::rYearlyMonth;
      } else if ( tmpStr.left(2) == "YD" ) {
        type = Recurrence::rYearlyDay;
      }
    }

    if ( type != Recurrence::rNone ) {
// kdDebug() << " It's a supported type " << endl;

      // Immediately after the type is the frequency
      int index = tmpStr.tqfind(' ');
      int last = tmpStr.tqfindRev(' ') + 1; // find last entry
      int rFreq = tmpStr.mid(typelen, (index-1)).toInt();
      ++index; // advance to beginning of stuff after freq

      // Read the type-specific settings
      switch ( type ) {
        case Recurrence::rDaily:
               anEvent->recurrence()->setDaily(rFreq);
               break;

        case Recurrence::rWeekly: {
               TQBitArray qba(7);
               TQString dayStr;
               if( index == last ) {
                 // e.g. W1 #0
                 qba.setBit(anEvent->dtStart().date().dayOfWeek() - 1);
               }
               else {
                 // e.g. W1 SU #0
                 while (index < last) {
                   dayStr = tmpStr.mid(index, 3);
                   int dayNum = numFromDay(dayStr);
                   qba.setBit(dayNum);
                   index += 3; // advance to next day, or possibly "#"
                 }
               }
               anEvent->recurrence()->setWeekly( rFreq, qba );
               break; }

        case Recurrence::rMonthlyPos: {
               anEvent->recurrence()->setMonthly( rFreq );

               TQBitArray qba(7);
               short tmpPos;
               if( index == last ) {
                 // e.g. MP1 #0
                 tmpPos = anEvent->dtStart().date().day()/7 + 1;
                 if( tmpPos == 5 )
                   tmpPos = -1;
                 qba.setBit(anEvent->dtStart().date().dayOfWeek() - 1);
                 anEvent->recurrence()->addMonthlyPos( tmpPos, qba );
               }
               else {
                 // e.g. MP1 1+ SU #0
                 while (index < last) {
                   tmpPos = tmpStr.mid(index,1).toShort();
                   index += 1;
                   if (tmpStr.mid(index,1) == "-")
                     // convert tmpPos to negative
                     tmpPos = 0 - tmpPos;
                   index += 2; // advance to day(s)
                   while (numFromDay(tmpStr.mid(index,3)) >= 0) {
                     int dayNum = numFromDay(tmpStr.mid(index,3));
                     qba.setBit(dayNum);
                     index += 3; // advance to next day, or possibly pos or "#"
                   }
                   anEvent->recurrence()->addMonthlyPos( tmpPos, qba );
                   qba.detach();
                   qba.fill(FALSE); // clear out
                 } // while != "#"
               }
             break;}

        case Recurrence::rMonthlyDay:
             anEvent->recurrence()->setMonthly( rFreq );
             if( index == last ) {
               // e.g. MD1 #0
               short tmpDay = anEvent->dtStart().date().day();
               anEvent->recurrence()->addMonthlyDate( tmpDay );
             }
             else {
               // e.g. MD1 3 #0
               while (index < last) {
                 int index2 = tmpStr.tqfind(' ', index);
                 short tmpDay = tmpStr.mid(index, (index2-index)).toShort();
                 index = index2-1;
                 if (tmpStr.mid(index, 1) == "-")
                   tmpDay = 0 - tmpDay;
                 index += 2; // advance the index;
                 anEvent->recurrence()->addMonthlyDate( tmpDay );
               } // while != #
             }
             break;

        case Recurrence::rYearlyMonth:
             anEvent->recurrence()->setYearly( rFreq );

             if( index == last ) {
               // e.g. YM1 #0
               short tmpMonth = anEvent->dtStart().date().month();
               anEvent->recurrence()->addYearlyMonth( tmpMonth );
             }
             else {
               // e.g. YM1 3 #0
               while (index < last) {
                 int index2 = tmpStr.tqfind(' ', index);
                 short tmpMonth = tmpStr.mid(index, (index2-index)).toShort();
                 index = index2 + 1;
                 anEvent->recurrence()->addYearlyMonth( tmpMonth );
               } // while != #
             }
             break;

        case Recurrence::rYearlyDay:
             anEvent->recurrence()->setYearly( rFreq );

             if( index == last ) {
               // e.g. YD1 #0
               short tmpDay = anEvent->dtStart().date().dayOfYear();
               anEvent->recurrence()->addYearlyDay( tmpDay );
             }
             else {
               // e.g. YD1 123 #0
               while (index < last) {
                 int index2 = tmpStr.tqfind(' ', index);
                 short tmpDay = tmpStr.mid(index, (index2-index)).toShort();
                 index = index2+1;
                 anEvent->recurrence()->addYearlyDay( tmpDay );
               } // while != #
             }
             break;

        default: break;
      }

      // find the last field, which is either the duration or the end date
      index = last;
      if ( tmpStr.mid(index,1) == "#") {
        // Nr of occurrences
        index++;
        int rDuration = tmpStr.mid(index, tmpStr.length()-index).toInt();
        if ( rDuration > 0 )
          anEvent->recurrence()->setDuration( rDuration );
      } else if ( tmpStr.tqfind('T', index) != -1 ) {
        TQDate rEndDate = (ISOToTQDateTime(tmpStr.mid(index, tmpStr.length()-index))).date();
        anEvent->recurrence()->setEndDateTime( rEndDate );
      }
// anEvent->recurrence()->dump();

    } else {
      kdDebug(5800) << "we don't understand this type of recurrence!" << endl;
    } // if known recurrence type
  } // repeats


  // recurrence exceptions
  if ((vo = isAPropertyOf(vevent, VCExDateProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    TQStringList exDates = TQStringList::split(",",s);
    TQStringList::ConstIterator it;
    for(it = exDates.begin(); it != exDates.end(); ++it ) {
      anEvent->recurrence()->addExDate(ISOToTQDate(*it));
    }
    deleteStr(s);
  }

  // summary
  if ((vo = isAPropertyOf(vevent, VCSummaryProp))) {
    s = fakeCString(vObjectUStringZValue(vo));
    anEvent->setSummary(TQString::fromLocal8Bit(s));
    deleteStr(s);
  }

  // description
  if ((vo = isAPropertyOf(vevent, VCDescriptionProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    if (!anEvent->description().isEmpty()) {
      anEvent->setDescription(anEvent->description() + "\n" +
                              TQString::fromLocal8Bit(s));
    } else {
      anEvent->setDescription(TQString::fromLocal8Bit(s));
    }
    deleteStr(s);
  }

  // location
  if ((vo = isAPropertyOf(vevent, VCLocationProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    anEvent->setLocation( TQString::fromLocal8Bit(s) );
    deleteStr(s);
  }

  // some stupid vCal exporters ignore the standard and use Description
  // instead of Summary for the default field.  Correct for this.
  if (anEvent->summary().isEmpty() &&
      !(anEvent->description().isEmpty())) {
    TQString tmpStr = anEvent->description().simplifyWhiteSpace();
    anEvent->setDescription("");
    anEvent->setSummary(tmpStr);
  }

#if 0
  // status
  if ((vo = isAPropertyOf(vevent, VCStatusProp)) != 0) {
    TQString tmpStr(s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
// TODO: Define Event status
//    anEvent->setqStatus(tmpStr);
  }
  else
//    anEvent->setqStatus("NEEDS ACTION");
#endif

  // secrecy
  int secrecy = Incidence::SecrecyPublic;
  if ((vo = isAPropertyOf(vevent, VCClassProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    if (strcmp(s,"PRIVATE") == 0) {
      secrecy = Incidence::SecrecyPrivate;
    } else if (strcmp(s,"CONFIDENTIAL") == 0) {
      secrecy = Incidence::SecrecyConfidential;
    }
    deleteStr(s);
  }
  anEvent->setSecrecy(secrecy);

  // categories
  if ((vo = isAPropertyOf(vevent, VCCategoriesProp)) != 0) {
    s = fakeCString(vObjectUStringZValue(vo));
    TQString categories = TQString::fromLocal8Bit(s);
    deleteStr(s);
    TQStringList tmpStrList = TQStringList::split( ',', categories );
    anEvent->setCategories(tmpStrList);
  }

  // attachments
  initPropIterator(&voi, vevent);
  while (moreIteration(&voi)) {
    vo = nextVObject(&voi);
    if (strcmp(vObjectName(vo), VCAttachProp) == 0) {
      s = fakeCString(vObjectUStringZValue(vo));
      anEvent->addAttachment(new Attachment(TQString(s)));
      deleteStr(s);
    }
  }

  // resources
  if ((vo = isAPropertyOf(vevent, VCResourcesProp)) != 0) {
    TQString resources = (s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
    TQStringList tmpStrList = TQStringList::split( ';', resources );
    anEvent->setResources(tmpStrList);
  }

  /* alarm stuff */
  if ((vo = isAPropertyOf(vevent, VCDAlarmProp))) {
    Alarm* alarm = anEvent->newAlarm();
    VObject *a;
    if ((a = isAPropertyOf(vo, VCRunTimeProp))) {
      alarm->setTime(ISOToTQDateTime(s = fakeCString(vObjectUStringZValue(a))));
      deleteStr(s);
    }
    alarm->setEnabled(true);
    if ((vo = isAPropertyOf(vevent, VCPAlarmProp))) {
      if ((a = isAPropertyOf(vo, VCProcedureNameProp))) {
        s = fakeCString(vObjectUStringZValue(a));
        alarm->setProcedureAlarm(TQFile::decodeName(s));
        deleteStr(s);
      }
    }
    if ((vo = isAPropertyOf(vevent, VCAAlarmProp))) {
      if ((a = isAPropertyOf(vo, VCAudioContentProp))) {
        s = fakeCString(vObjectUStringZValue(a));
        alarm->setAudioAlarm(TQFile::decodeName(s));
        deleteStr(s);
      }
    }
  }

  // priority
  if ((vo = isAPropertyOf(vevent, VCPriorityProp))) {
    anEvent->setPriority(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }

  // transparency
  if ((vo = isAPropertyOf(vevent, VCTranspProp)) != 0) {
    int i = atoi(s = fakeCString(vObjectUStringZValue(vo)));
    anEvent->setTransparency( i == 1 ? Event::Transparent : Event::Opaque );
    deleteStr(s);
  }

  // related event
  if ((vo = isAPropertyOf(vevent, VCRelatedToProp)) != 0) {
    anEvent->setRelatedToUid(s = fakeCString(vObjectUStringZValue(vo)));
    deleteStr(s);
    mEventsRelate.append(anEvent);
  }

  /* PILOT SYNC STUFF */
  if ((vo = isAPropertyOf(vevent, KPilotIdProp))) {
    anEvent->setPilotId(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setPilotId(0);

  if ((vo = isAPropertyOf(vevent, KPiloStatusProp))) {
    anEvent->setSynctqStatus(atoi(s = fakeCString(vObjectUStringZValue(vo))));
    deleteStr(s);
  }
  else
    anEvent->setSynctqStatus(Event::SYNCMOD);

  return anEvent;
}


TQString VCalFormat::qDateToISO(const TQDate &qd)
{
  TQString tmpStr;

  Q_ASSERT(qd.isValid());

  tmpStr.sprintf("%.2d%.2d%.2d",
                 qd.year(), qd.month(), qd.day());
  return tmpStr;

}

/* Return the offset of the named zone as seconds. tt is a time
   indicating the date for which you want the offset */
int vcaltime_utc_offset( TQDateTime ictt, TQString tzid )
{
  // libical-0.23 stuff:
  //  struct icaltimetype tt = icaltime_from_timet( ictt.toTime_t(), false );
  //  return icaltime_utc_offset( tt, tzid.latin1() );
  int daylight;
  struct icaltimetype tt = icaltime_from_timet( ictt.toTime_t(), false );
  //source says this is DEPRECATED, but it doesn't say what to use instead
  //how to handle failure from icaltimezone_get_builtin_timezone_from_tzid()?
  return icaltimezone_get_utc_offset(
    icaltimezone_get_builtin_timezone( tzid.latin1() ),
    &tt, &daylight );
}

TQString VCalFormat::qDateTimeToISO(const TQDateTime &qdt, bool zulu)
{
  TQString tmpStr;

  Q_ASSERT(qdt.date().isValid());
  Q_ASSERT(qdt.time().isValid());
  if (zulu) {
    TQDateTime tmpDT(qdt);
    // correct to GMT:
    tmpDT = tmpDT.addSecs(-vcaltime_utc_offset( tmpDT, mCalendar->timeZoneId()));
    tmpStr.sprintf( "%.2d%.2d%.2dT%.2d%.2d%.2dZ",
                    tmpDT.date().year(), tmpDT.date().month(),
                    tmpDT.date().day(), tmpDT.time().hour(),
                    tmpDT.time().minute(), tmpDT.time().second());
  } else {
    tmpStr.sprintf( "%.2d%.2d%.2dT%.2d%.2d%.2d",
                    qdt.date().year(), qdt.date().month(),
                    qdt.date().day(), qdt.time().hour(),
                    qdt.time().minute(), qdt.time().second());
  }
  return tmpStr;
}

TQDateTime VCalFormat::ISOToTQDateTime(const TQString & dtStr)
{
  TQDate tmpDate;
  TQTime tmpTime;
  TQString tmpStr;
  int year, month, day, hour, minute, second;

  tmpStr = dtStr;
  year = tmpStr.left(4).toInt();
  month = tmpStr.mid(4,2).toInt();
  day = tmpStr.mid(6,2).toInt();
  hour = tmpStr.mid(9,2).toInt();
  minute = tmpStr.mid(11,2).toInt();
  second = tmpStr.mid(13,2).toInt();
  tmpDate.setYMD(year, month, day);
  tmpTime.setHMS(hour, minute, second);

  Q_ASSERT(tmpDate.isValid());
  Q_ASSERT(tmpTime.isValid());
  TQDateTime tmpDT(tmpDate, tmpTime);
  // correct for GMT if string is in Zulu format
  if (dtStr.at(dtStr.length()-1) == 'Z') {
    tmpDT = tmpDT.addSecs(vcaltime_utc_offset( tmpDT, mCalendar->timeZoneId()));
  }
  return tmpDT;
}

TQDate VCalFormat::ISOToTQDate(const TQString &dateStr)
{
  int year, month, day;

  year = dateStr.left(4).toInt();
  month = dateStr.mid(4,2).toInt();
  day = dateStr.mid(6,2).toInt();

  return(TQDate(year, month, day));
}

// take a raw vcalendar (i.e. from a file on disk, clipboard, etc. etc.
// and break it down from it's tree-like format into the dictionary format
// that is used internally in the VCalFormat.
void VCalFormat::populate(VObject *vcal)
{
  // this function will populate the caldict dictionary and other event
  // lists. It turns vevents into Events and then inserts them.

  VObjectIterator i;
  VObject *curVO, *curVOProp;
  Event *anEvent;

  if ((curVO = isAPropertyOf(vcal, ICMethodProp)) != 0) {
    char *methodType = 0;
    methodType = fakeCString(vObjectUStringZValue(curVO));
    kdDebug(5800) << "This calendar is an iTIP transaction of type '"
              << methodType << "'" << endl;
    deleteStr(methodType);
  }

  // warn the user that we might have trouble reading non-known calendar.
  if ((curVO = isAPropertyOf(vcal, VCProdIdProp)) != 0) {
    char *s = fakeCString(vObjectUStringZValue(curVO));
    if (strcmp(productId().local8Bit(), s) != 0)
      kdDebug(5800) << "This vCalendar file was not created by KOrganizer "
                   "or any other product we support. Loading anyway..." << endl;
    mLoadedProductId = s;
    deleteStr(s);
  }

  // warn the user we might have trouble reading this unknown version.
  if ((curVO = isAPropertyOf(vcal, VCVersionProp)) != 0) {
    char *s = fakeCString(vObjectUStringZValue(curVO));
    if (strcmp(_VCAL_VERSION, s) != 0)
      kdDebug(5800) << "This vCalendar file has version " << s
                << "We only support " << _VCAL_VERSION << endl;
    deleteStr(s);
  }

#if 0
  // set the time zone (this is a property of the view, so just discard!)
  if ((curVO = isAPropertyOf(vcal, VCTimeZoneProp)) != 0) {
    char *s = fakeCString(vObjectUStringZValue(curVO));
    mCalendar->setTimeZone(s);
    deleteStr(s);
  }
#endif

  // Store all events with a relatedTo property in a list for post-processing
  mEventsRelate.clear();
  mTodosRelate.clear();

  initPropIterator(&i, vcal);

  // go through all the vobjects in the vcal
  while (moreIteration(&i)) {
    curVO = nextVObject(&i);

    /************************************************************************/

    // now, check to see that the object is an event or todo.
    if (strcmp(vObjectName(curVO), VCEventProp) == 0) {

      if ((curVOProp = isAPropertyOf(curVO, KPiloStatusProp)) != 0) {
        char *s;
        s = fakeCString(vObjectUStringZValue(curVOProp));
        // check to see if event was deleted by the kpilot conduit
        if (atoi(s) == Event::SYNCDEL) {
          deleteStr(s);
          kdDebug(5800) << "skipping pilot-deleted event" << endl;
          goto SKIP;
        }
        deleteStr(s);
      }

      // this code checks to see if we are trying to read in an event
      // that we already find to be in the calendar.  If we find this
      // to be the case, we skip the event.
      if ((curVOProp = isAPropertyOf(curVO, VCUniqueStringProp)) != 0) {
        char *s = fakeCString(vObjectUStringZValue(curVOProp));
        TQString tmpStr(s);
        deleteStr(s);

        if (mCalendar->incidence(tmpStr)) {
          goto SKIP;
        }
      }

      if ((!(curVOProp = isAPropertyOf(curVO, VCDTstartProp))) &&
          (!(curVOProp = isAPropertyOf(curVO, VCDTendProp)))) {
        kdDebug(5800) << "found a VEvent with no DTSTART and no DTEND! Skipping..." << endl;
        goto SKIP;
      }

      anEvent = VEventToEvent(curVO);
      // we now use addEvent instead of insertEvent so that the
      // signal/slot get connected.
      if (anEvent) {
              if ( !anEvent->dtStart().isValid() || !anEvent->dtEnd().isValid() ) {
          kdDebug(5800) << "VCalFormat::populate(): Event has invalid dates."
                    << endl;
        } else {
          mCalendar->addEvent(anEvent);
              }
      } else {
        // some sort of error must have occurred while in translation.
        goto SKIP;
      }
    } else if (strcmp(vObjectName(curVO), VCTodoProp) == 0) {
      Todo *aTodo = VTodoToEvent(curVO);
      mCalendar->addTodo(aTodo);
    } else if ((strcmp(vObjectName(curVO), VCVersionProp) == 0) ||
               (strcmp(vObjectName(curVO), VCProdIdProp) == 0) ||
               (strcmp(vObjectName(curVO), VCTimeZoneProp) == 0)) {
      // do nothing, we know these properties and we want to skip them.
      // we have either already processed them or are ignoring them.
      ;
    } else {
      kdDebug(5800) << "Ignoring unknown vObject \"" << vObjectName(curVO) << "\"" << endl;
    }
  SKIP:
    ;
  } // while

  // Post-Process list of events with relations, put Event objects in relation
  Event::List::ConstIterator eIt;
  for ( eIt = mEventsRelate.begin(); eIt != mEventsRelate.end(); ++eIt ) {
    (*eIt)->setRelatedTo( mCalendar->incidence( (*eIt)->relatedToUid() ) );
  }
  Todo::List::ConstIterator tIt;
  for ( tIt = mTodosRelate.begin(); tIt != mTodosRelate.end(); ++tIt ) {
    (*tIt)->setRelatedTo( mCalendar->incidence( (*tIt)->relatedToUid() ) );
   }
}

const char *VCalFormat::dayFromNum(int day)
{
  const char *days[7] = { "MO ", "TU ", "WE ", "TH ", "FR ", "SA ", "SU " };

  return days[day];
}

int VCalFormat::numFromDay(const TQString &day)
{
  if (day == "MO ") return 0;
  if (day == "TU ") return 1;
  if (day == "WE ") return 2;
  if (day == "TH ") return 3;
  if (day == "FR ") return 4;
  if (day == "SA ") return 5;
  if (day == "SU ") return 6;

  return -1; // something bad happened. :)
}

Attendee::PartStat VCalFormat::readtqStatus(const char *s) const
{
  TQString statStr = s;
  statStr = statStr.upper();
  Attendee::PartStat status;

  if (statStr == "X-ACTION")
    status = Attendee::NeedsAction;
  else if (statStr == "NEEDS ACTION")
    status = Attendee::NeedsAction;
  else if (statStr== "ACCEPTED")
    status = Attendee::Accepted;
  else if (statStr== "SENT")
    status = Attendee::NeedsAction;
  else if (statStr== "TENTATIVE")
    status = Attendee::Tentative;
  else if (statStr== "CONFIRMED")
    status = Attendee::Accepted;
  else if (statStr== "DECLINED")
    status = Attendee::Declined;
  else if (statStr== "COMPLETED")
    status = Attendee::Completed;
  else if (statStr== "DELEGATED")
    status = Attendee::Delegated;
  else {
    kdDebug(5800) << "error setting attendee mtqStatus, unknown mtqStatus!" << endl;
    status = Attendee::NeedsAction;
  }

  return status;
}

TQCString VCalFormat::writetqStatus(Attendee::PartStat status) const
{
  switch(status) {
    default:
    case Attendee::NeedsAction:
      return "NEEDS ACTION";
      break;
    case Attendee::Accepted:
      return "ACCEPTED";
      break;
    case Attendee::Declined:
      return "DECLINED";
      break;
    case Attendee::Tentative:
      return "TENTATIVE";
      break;
    case Attendee::Delegated:
      return "DELEGATED";
      break;
    case Attendee::Completed:
      return "COMPLETED";
      break;
    case Attendee::InProcess:
      return "NEEDS ACTION";
      break;
  }
}