~ubuntu-branches/ubuntu/lucid/igraph/lucid

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
/* -*- mode: C -*-  */
/* 
   IGraph R package.
   Copyright (C) 2006 Gabor Csardi <csardi@rmki.kfki.hu>
   MTA RMKI, Konkoly-Thege Miklos st. 29-33, Budapest 1121, Hungary
   
   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., 51 Franklin Street, Fifth Floor, Boston, MA 
   02110-1301 USA

*/

#include "igraph.h"
#include "config.h"
#include "igraph_math.h"

#include <ctype.h>		/* isspace */
#include <math.h>               /* isnan */
#include <string.h>
#include "memory.h"
#include <stdarg.h> 		/* va_start & co */

#if HAVE_LIBXML == 1
#include <libxml/encoding.h>
#include <libxml/parser.h>


xmlEntity blankEntityStruct = {
#ifndef XML_WITHOUT_CORBA
  0,
#endif
  XML_ENTITY_DECL,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  XML_EXTERNAL_GENERAL_PARSED_ENTITY,
  0,
  0,
  0,
  0
};

xmlEntityPtr blankEntity = &blankEntityStruct;

/* TODO: proper error handling */

typedef struct igraph_i_graphml_attribute_record_t {
  const char *id;         	/* GraphML id */
  enum { I_GRAPHML_BOOLEAN, I_GRAPHML_INTEGER, I_GRAPHML_LONG,
	 I_GRAPHML_FLOAT, I_GRAPHML_DOUBLE, I_GRAPHML_STRING,
	 I_GRAPHML_UNKNOWN_TYPE } type;	/* GraphML type */
  igraph_i_attribute_record_t record;
} igraph_i_graphml_attribute_record_t;

struct igraph_i_graphml_parser_state {
  enum { START, INSIDE_GRAPHML, INSIDE_GRAPH, INSIDE_NODE, INSIDE_EDGE,
      INSIDE_KEY, INSIDE_DEFAULT, INSIDE_DATA, FINISH, UNKNOWN, ERROR } st;
  igraph_t *g;
  igraph_trie_t node_trie;
  igraph_strvector_t edgeids;
  igraph_vector_t edgelist;
  unsigned int prev_state;
  unsigned int unknown_depth;
  int index;
  igraph_bool_t successful, edges_directed, destroyed;
  igraph_trie_t v_names;
  igraph_vector_ptr_t v_attrs;
  igraph_trie_t e_names;
  igraph_vector_ptr_t e_attrs;
  igraph_trie_t g_names;
  igraph_vector_ptr_t g_attrs;
  xmlChar *data_key;
  igraph_attribute_elemtype_t data_type;
  char *error_message;
  char *data_char;
};

void igraph_i_graphml_destroy_state(struct igraph_i_graphml_parser_state* state) {
  long int i;

  if (state->destroyed) return;
  state->destroyed=1;

  /* this is the easy part */
  igraph_trie_destroy(&state->node_trie);
  igraph_strvector_destroy(&state->edgeids);
  igraph_trie_destroy(&state->v_names);
  igraph_trie_destroy(&state->e_names);
  igraph_trie_destroy(&state->g_names);
  igraph_vector_destroy(&state->edgelist);
   
  if (state->error_message) { free(state->error_message); }
  if (state->data_key) { free(state->data_key); }
  if (state->data_char) { free(state->data_char); }
  
  for (i=0; i<igraph_vector_ptr_size(&state->v_attrs); i++) {
    igraph_i_graphml_attribute_record_t *rec=VECTOR(state->v_attrs)[i];
    if (rec->record.type==IGRAPH_ATTRIBUTE_NUMERIC) {
      if (rec->record.value != 0) {
	igraph_vector_destroy((igraph_vector_t*)rec->record.value);
	igraph_Free(rec->record.value);
      }
    } else if (rec->record.type==IGRAPH_ATTRIBUTE_STRING) {
      if (rec->record.value != 0) {
	igraph_strvector_destroy((igraph_strvector_t*)rec->record.value);
	igraph_Free(rec->record.value);
      }
    }
    if (rec->id != 0) igraph_Free(rec->id);
    if (rec->record.name != 0) igraph_Free(rec->record.name);
    igraph_Free(rec);
  }	 

  for (i=0; i<igraph_vector_ptr_size(&state->e_attrs); i++) {
    igraph_i_graphml_attribute_record_t *rec=VECTOR(state->e_attrs)[i];
    if (rec->record.type==IGRAPH_ATTRIBUTE_NUMERIC) {
      if (rec->record.value != 0) {
	igraph_vector_destroy((igraph_vector_t*)rec->record.value);
	igraph_Free(rec->record.value);
      }
    } else if (rec->record.type==IGRAPH_ATTRIBUTE_STRING) {
      if (rec->record.value != 0) {
	igraph_strvector_destroy((igraph_strvector_t*)rec->record.value);
	igraph_Free(rec->record.value);
      }
    }
    if (rec->id != 0) igraph_Free(rec->id);
    if (rec->record.name != 0) igraph_Free(rec->record.name);
    igraph_Free(rec);
  }

  for (i=0; i<igraph_vector_ptr_size(&state->g_attrs); i++) {
    igraph_i_graphml_attribute_record_t *rec=VECTOR(state->g_attrs)[i];
    if (rec->record.type==IGRAPH_ATTRIBUTE_NUMERIC) {
      if (rec->record.value != 0) {
	igraph_vector_destroy((igraph_vector_t*)rec->record.value);
	igraph_Free(rec->record.value);
      }
    } else if (rec->record.type==IGRAPH_ATTRIBUTE_STRING) {
      if (rec->record.value != 0) {
	igraph_strvector_destroy((igraph_strvector_t*)rec->record.value);
	igraph_Free(rec->record.value);
      }
    }
    if (rec->id != 0) igraph_Free(rec->id);
    if (rec->record.name != 0) igraph_Free(rec->record.name);
    igraph_Free(rec);
  }

  igraph_vector_ptr_destroy(&state->v_attrs);
  igraph_vector_ptr_destroy(&state->e_attrs);
  igraph_vector_ptr_destroy(&state->g_attrs);
  
  IGRAPH_FINALLY_CLEAN(1);
}

void igraph_i_graphml_sax_handler_error(void *state0, const char* msg, ...) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  va_list ap;
  
  va_start(ap, msg);
  
  if (state->error_message == 0)
    state->error_message=igraph_Calloc(4096, char);
   
  state->successful=0;
  state->st=ERROR;
  vsnprintf(state->error_message, 4096, msg, ap);
   
  va_end(ap);
}

xmlEntityPtr igraph_i_graphml_sax_handler_get_entity(void *state0,
						     const xmlChar* name) {
  xmlEntityPtr predef = xmlGetPredefinedEntity(name);
  if (predef != NULL) return predef;
  IGRAPH_WARNING("unknown XML entity found\n");
  return blankEntity;
}

void igraph_i_graphml_handle_unknown_start_tag(struct igraph_i_graphml_parser_state *state) {
  if (state->st != UNKNOWN) {
    state->prev_state=state->st;
    state->st=UNKNOWN;
    state->unknown_depth=1;
  } else state->unknown_depth++;
}

void igraph_i_graphml_sax_handler_start_document(void *state0) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  int ret;
  
  state->st=START;
  state->successful=1;
  state->edges_directed=0;
  state->destroyed=0;
  state->data_key=0;
  state->error_message=0;
  state->data_char=0;
  
  ret=igraph_vector_ptr_init(&state->v_attrs, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_vector_ptr_destroy, &state->v_attrs);
  ret=igraph_vector_ptr_init(&state->e_attrs, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_vector_ptr_destroy, &state->e_attrs);
  ret=igraph_vector_ptr_init(&state->g_attrs, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_vector_ptr_destroy, &state->g_attrs);
  ret=igraph_vector_init(&state->edgelist, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_vector_destroy, &state->edgelist);
  ret=igraph_trie_init(&state->node_trie, 1);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_trie_destroy, &state->node_trie);
  ret=igraph_strvector_init(&state->edgeids, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_strvector_destroy, &state->edgeids);
  ret=igraph_trie_init(&state->v_names, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_trie_destroy, &state->v_names);
  ret=igraph_trie_init(&state->e_names, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_trie_destroy, &state->e_names);
  ret=igraph_trie_init(&state->g_names, 0);
  if (ret) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_trie_destroy, &state->g_names);
  
  IGRAPH_FINALLY_CLEAN(9);
  IGRAPH_FINALLY(igraph_i_graphml_destroy_state, state);
}

void igraph_i_graphml_sax_handler_end_document(void *state0) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  long i, l;
  int r;
  igraph_i_attribute_record_t idrec, eidrec;
  const char *idstr="id";
  igraph_bool_t already_has_vertex_id=0, already_has_edge_id=0;

  if (!state->successful) return;

  if (state->index<0) {

    igraph_vector_ptr_t vattr, eattr, gattr;
    long int esize=igraph_vector_ptr_size(&state->e_attrs);
    const void **tmp;
    r=igraph_vector_ptr_init(&vattr, 
			     igraph_vector_ptr_size(&state->v_attrs)+1);
    if (r) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    IGRAPH_FINALLY(igraph_vector_ptr_destroy, &vattr);
    if (igraph_strvector_size(&state->edgeids) != 0) {
      esize++;      
    }
    r=igraph_vector_ptr_init(&eattr, esize);
    if (r) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    IGRAPH_FINALLY(igraph_vector_ptr_destroy, &eattr);
    r=igraph_vector_ptr_init(&gattr, igraph_vector_ptr_size(&state->g_attrs));
    if (r) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    IGRAPH_FINALLY(igraph_vector_ptr_destroy, &gattr);

    for (i=0; i<igraph_vector_ptr_size(&state->v_attrs); i++) {
      igraph_i_graphml_attribute_record_t *graphmlrec=
	VECTOR(state->v_attrs)[i];
      igraph_i_attribute_record_t *rec=&graphmlrec->record;

      /* Check that the name of the vertex attribute is not 'id'.
	 If it is then we cannot the complimentary 'id' attribute. */
      if (! strcmp(rec->name, idstr)) {
	already_has_vertex_id=1;
      }

      if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_vector_t *vec=(igraph_vector_t*)rec->value;
	long int origsize=igraph_vector_size(vec);
	long int nodes=igraph_trie_size(&state->node_trie);
	igraph_vector_resize(vec, nodes);
	for (l=origsize; l<nodes; l++) {
	  VECTOR(*vec)[l]=IGRAPH_NAN;
	}
      } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) {
	igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value;
	long int origsize=igraph_strvector_size(strvec);
	long int nodes=igraph_trie_size(&state->node_trie);
	igraph_strvector_resize(strvec, nodes);
	for (l=origsize; l<nodes; l++) {
	  igraph_strvector_set(strvec, l, "");
	}
      }
      VECTOR(vattr)[i]=rec;
    }
    if (!already_has_vertex_id) {
      idrec.name=idstr;
      idrec.type=IGRAPH_ATTRIBUTE_STRING;
      tmp=&idrec.value;
      igraph_trie_getkeys(&state->node_trie, (const igraph_strvector_t **)tmp);
      VECTOR(vattr)[i]=&idrec;
    } else {
      igraph_vector_ptr_pop_back(&vattr);
      IGRAPH_WARNING("Could not add vertex ids, "
		     "there is already an 'id' vertex attribute");
    }

    for (i=0; i<igraph_vector_ptr_size(&state->e_attrs); i++) {
      igraph_i_graphml_attribute_record_t *graphmlrec=
	VECTOR(state->e_attrs)[i];
      igraph_i_attribute_record_t *rec=&graphmlrec->record;

      if (! strcmp(rec->name, idstr)) {
	already_has_edge_id=1;
      }

      if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_vector_t *vec=(igraph_vector_t*)rec->value;
	long int origsize=igraph_vector_size(vec);
	long int edges=igraph_vector_size(&state->edgelist)/2;
	igraph_vector_resize(vec, edges);
	for (l=origsize; l<edges; l++) {
	  VECTOR(*vec)[l]=IGRAPH_NAN;
	}
      } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) {
	igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value;
	long int origsize=igraph_strvector_size(strvec);
	long int edges=igraph_vector_size(&state->edgelist)/2;
	igraph_strvector_resize(strvec, edges);
	for (l=origsize; l<edges; l++) {
	  igraph_strvector_set(strvec, l, "");
	}
      }
      VECTOR(eattr)[i]=rec;
    }
    if (igraph_strvector_size(&state->edgeids) != 0) {
      if (!already_has_edge_id) {
	long int origsize=igraph_strvector_size(&state->edgeids);
	eidrec.name=idstr;
	eidrec.type=IGRAPH_ATTRIBUTE_STRING;
	igraph_strvector_resize(&state->edgeids, 
				igraph_vector_size(&state->edgelist)/2);
	for (; origsize < igraph_strvector_size(&state->edgeids); origsize++) {
	  igraph_strvector_set(&state->edgeids, origsize, "");
	}
	eidrec.value=&state->edgeids;
	VECTOR(eattr)[(long int)igraph_vector_ptr_size(&eattr)-1]=&eidrec;
      } else {
	igraph_vector_ptr_pop_back(&eattr);
	IGRAPH_WARNING("Could not add edge ids, "
		       "there is already an 'id' edge attribute");
      }
    }

    for (i=0; i<igraph_vector_ptr_size(&state->g_attrs); i++) {
      igraph_i_graphml_attribute_record_t *graphmlrec=
	VECTOR(state->g_attrs)[i];
      igraph_i_attribute_record_t *rec=&graphmlrec->record;
      if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_vector_t *vec=(igraph_vector_t*)rec->value;
	long int origsize=igraph_vector_size(vec);
	igraph_vector_resize(vec, 1);
	for (l=origsize; l<1; l++) {
	  VECTOR(*vec)[l]=IGRAPH_NAN;
	}
      } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) {
	igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value;
	long int origsize=igraph_strvector_size(strvec);
	igraph_strvector_resize(strvec, 1);
	for (l=origsize; l<1; l++) {
	  igraph_strvector_set(strvec, l, "");
	}
      }
      VECTOR(gattr)[i]=rec;
    }
    
    igraph_empty_attrs(state->g, 0, state->edges_directed, &gattr);
    igraph_add_vertices(state->g, igraph_trie_size(&state->node_trie),
			&vattr);
    igraph_add_edges(state->g, &state->edgelist, &eattr);

    igraph_vector_ptr_destroy(&vattr);
    igraph_vector_ptr_destroy(&eattr);
    igraph_vector_ptr_destroy(&gattr);
    IGRAPH_FINALLY_CLEAN(3);     
  }

  igraph_i_graphml_destroy_state(state);
}

#define toXmlChar(a)   (BAD_CAST(a))
#define fromXmlChar(a) ((char *)(a)) /* not the most elegant way... */

void igraph_i_graphml_add_attribute_key(const xmlChar** attrs, 
					struct igraph_i_graphml_parser_state *state) {
  xmlChar **it;
  igraph_trie_t *trie=0;
  igraph_vector_ptr_t *ptrvector=0;
  long int id;
  int ret;
  igraph_i_graphml_attribute_record_t *rec=
    igraph_Calloc(1, igraph_i_graphml_attribute_record_t);

  if (!state->successful) return;
   
   if (rec==0) { 
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, 
		 IGRAPH_ENOMEM);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  IGRAPH_FINALLY(igraph_free, rec);
  for (it=(xmlChar**)attrs; *it; it+=2) {
    if (xmlStrEqual(*it, toXmlChar("id"))) {
      const char *id=(const char*)(*(it+1));
      rec->id=strdup(id);
    } else if (xmlStrEqual(*it, toXmlChar("attr.name"))) {
      const char *name=fromXmlChar(*(it+1));
      rec->record.name=strdup(name);
    } else if (xmlStrEqual(*it, toXmlChar("attr.type"))) {
      if (xmlStrEqual(*(it+1), (xmlChar*)"boolean")) { 
	rec->type=I_GRAPHML_BOOLEAN;
	rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC;	    
      } else if (xmlStrEqual(*(it+1), toXmlChar("string"))) {
	rec->type=I_GRAPHML_STRING;
	rec->record.type=IGRAPH_ATTRIBUTE_STRING;
      } else if (xmlStrEqual(*(it+1), toXmlChar("float"))) { 
	rec->type=I_GRAPHML_FLOAT;
	rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC;
      } else if (xmlStrEqual(*(it+1), toXmlChar("double"))) { 
	rec->type=I_GRAPHML_DOUBLE;
	rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC;
      } else if (xmlStrEqual(*(it+1), toXmlChar("int"))) {
	rec->type=I_GRAPHML_INTEGER;
	rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC;
      } else if (xmlStrEqual(*(it+1), toXmlChar("long"))) {
	rec->type=I_GRAPHML_LONG;
	rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC;
      } else {
	igraph_error("Cannot parse GraphML file, unknown attribute type", 
		     __FILE__, __LINE__, IGRAPH_PARSEERROR);
        igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file, unknown attribute type");
        return;
      }
    } else if (xmlStrEqual(*it, toXmlChar("for"))) {
      /* graph, vertex or edge attribute? */
      if (xmlStrEqual(*(it+1), toXmlChar("graph"))) { 
	trie=&state->g_names;
	ptrvector=&state->g_attrs;
      } else if (xmlStrEqual(*(it+1), toXmlChar("node"))) {
	trie=&state->v_names;
	ptrvector=&state->v_attrs;
      } else if (xmlStrEqual(*(it+1), toXmlChar("edge"))) {
	trie=&state->e_names;
	ptrvector=&state->e_attrs;
      } else {
	igraph_error("Cannot parse GraphML file, unknown attribute type",
		     __FILE__, __LINE__, IGRAPH_PARSEERROR);
        igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file, unknown attribute type");
        return;
      }
    }
  }

  if (trie == 0 && state->successful) {
    igraph_error("Cannot parse GraphML file, missing 'for' attribute", __FILE__, __LINE__, IGRAPH_PARSEERROR);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file, missing 'for' attribute");
    return;
  }
	
  /* add to trie, attribues */
  igraph_trie_get(trie, rec->id, &id);
  if (id != igraph_trie_size(trie)-1) {
    igraph_error("Cannot parse GraphML file, duplicate attribute", 
		 __FILE__, __LINE__, IGRAPH_PARSEERROR);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file, duplicate attribute");
    return;
  }
  ret=igraph_vector_ptr_push_back(ptrvector, rec);
  if (ret) {
    igraph_error("Cannot read GraphML file", __FILE__, __LINE__, ret);
    igraph_i_graphml_sax_handler_error(state, "Cannot read GraphML file");
    return;
  }

  /* create the attribute values */
  switch (rec->record.type) {
    igraph_vector_t *vec;
    igraph_strvector_t *strvec;
  case IGRAPH_ATTRIBUTE_NUMERIC:
    vec=igraph_Calloc(1, igraph_vector_t);
    if (vec==0) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__,
		   IGRAPH_ENOMEM);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    rec->record.value=vec;
    igraph_vector_init(vec, 0);    
    break;
  case IGRAPH_ATTRIBUTE_STRING:
    strvec=igraph_Calloc(1, igraph_strvector_t);
    if (strvec==0) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, 
		   IGRAPH_ENOMEM);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    rec->record.value=strvec;
    igraph_strvector_init(strvec, 0);
    break;
  default: break;
  }

  IGRAPH_FINALLY_CLEAN(1);	/* rec */
}

void igraph_i_graphml_attribute_data_setup(struct igraph_i_graphml_parser_state *state,
					   const xmlChar **attrs,
					   igraph_attribute_elemtype_t type) {
  xmlChar **it;
  for (it=(xmlChar**)attrs; *it; it+=2) {
    if (xmlStrEqual(*it, toXmlChar("key"))) {
      if (state->data_key) {
	free(state->data_key);
      }
      state->data_key=xmlStrdup(*(it+1));
      if (state->data_char) {
        free(state->data_char);
      }
      state->data_char=0;
      state->data_type=type;
    } else {
      /* ignore */
    }
  }
}

void igraph_i_graphml_attribute_data_add(struct igraph_i_graphml_parser_state *state,
					 const xmlChar *data, int len) {
  long int data_char_new_start=0;

  if (!state->successful) return;

  if (state->data_char) {
    data_char_new_start=strlen(state->data_char);
    state->data_char=igraph_Realloc(state->data_char, data_char_new_start+len+1, char);
  } else {
    state->data_char=igraph_Calloc(len+1, char);
  }
  if (state->data_char==0) {
    igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, 
		 IGRAPH_ENOMEM);
    igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
    return;
  }
  memcpy(state->data_char+data_char_new_start, data, len*sizeof(xmlChar));
  state->data_char[data_char_new_start+len]='\0';
}

void igraph_i_graphml_attribute_data_finish(struct igraph_i_graphml_parser_state *state) {
  const char *key=fromXmlChar(state->data_key);
  igraph_attribute_elemtype_t type=state->data_type;
  igraph_trie_t *trie=0;
  igraph_vector_ptr_t *ptrvector=0;
  igraph_i_graphml_attribute_record_t *graphmlrec;
  igraph_i_attribute_record_t *rec;
  long int recid, id=0;
  int ret;
  
  switch (type) {
  case IGRAPH_ATTRIBUTE_GRAPH:
    trie=&state->g_names;
    ptrvector=&state->g_attrs;
    id=0;
    break;
  case IGRAPH_ATTRIBUTE_VERTEX:
    trie=&state->v_names;
    ptrvector=&state->v_attrs;
    id=igraph_trie_size(&state->node_trie)-1; /* hack */
    break;
  case IGRAPH_ATTRIBUTE_EDGE:
    trie=&state->e_names;
    ptrvector=&state->e_attrs;
    id=igraph_vector_size(&state->edgelist)/2-1; /* hack */
    break;
  default:
    /* impossible */
    break;
  }
  
  igraph_trie_check(trie, key, &recid);
  if (recid < 0) {
    /* no such attribute key, issue a warning */
    IGRAPH_WARNING("unknown attribute key in GraphML file, ignoring attribute");
    igraph_Free(state->data_char);
    return;
  }
   
  graphmlrec=VECTOR(*ptrvector)[recid];
  rec=&graphmlrec->record;

  switch (rec->type) {
    igraph_vector_t *vec;
    igraph_strvector_t *strvec;
    igraph_real_t num;
    long int s, i;
  case IGRAPH_ATTRIBUTE_NUMERIC:
    vec=(igraph_vector_t *)rec->value;
    s=igraph_vector_size(vec);
    if (id >= s) {
      ret=igraph_vector_resize(vec, id+1);
      if (ret) {
	igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
        igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
        return;
      }
      for (i=s; i<id; i++) {
	VECTOR(*vec)[i]=IGRAPH_NAN;
      }
    }
    if (state->data_char)
      sscanf(state->data_char, "%lf", &num);
    else
      num=0;
    VECTOR(*vec)[id]=num;
    break;
  case IGRAPH_ATTRIBUTE_STRING:
    strvec=(igraph_strvector_t *)rec->value;
    s=igraph_strvector_size(strvec);
    if (id >= s) {
      ret=igraph_strvector_resize(strvec, id+1);
      if (ret) {
	igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
        igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
        return;
      }
      for (i=s;i<id;i++) {
	igraph_strvector_set(strvec, i, "");
      }
    }
    if (state->data_char)
      ret=igraph_strvector_set(strvec, id, (char*)state->data_char);
    else
      ret=igraph_strvector_set(strvec, id, "");
    if (ret) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, ret);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    break;
  default:
    break;
  }

  if (state->data_char) igraph_Free(state->data_char);
}

void igraph_i_graphml_sax_handler_start_element(void *state0,
						const xmlChar* name,
						const xmlChar** attrs) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  xmlChar** it;
  long int id1, id2;
  unsigned short int directed;

  switch (state->st) {
  case START:
    /* If we are in the START state and received a graphml tag,
     * change to INSIDE_GRAPHML state. Otherwise, change to UNKNOWN. */
    if (xmlStrEqual(name, toXmlChar("graphml")))
      state->st=INSIDE_GRAPHML;
    else
      igraph_i_graphml_handle_unknown_start_tag(state);
    break;
    
  case INSIDE_GRAPHML:
    /* If we are in the INSIDE_GRAPHML state and received a graph tag,
     * change to INSIDE_GRAPH state if the state->index counter reached
     * zero (this is to handle multiple graphs in the same file).
     * Otherwise, change to UNKNOWN. */
    if (xmlStrEqual(name, toXmlChar("graph"))) {
      if (state->index==0) {
	state->st=INSIDE_GRAPH;
	for (it=(xmlChar**)attrs; *it; it+=2) {
	  if (xmlStrEqual(*it, toXmlChar("edgedefault"))) {
	    if (xmlStrEqual(*(it+1), toXmlChar("directed"))) state->edges_directed=1;
	    else if (xmlStrEqual(*(it+1), toXmlChar("undirected"))) state->edges_directed=0;
	  }
	}
      }
      state->index--;
    } else if (xmlStrEqual(name, toXmlChar("key"))) {
      igraph_i_graphml_add_attribute_key(attrs, state);
      state->st=INSIDE_KEY;
    } else
      igraph_i_graphml_handle_unknown_start_tag(state);
    break;

  case INSIDE_KEY:
    /* If we are in the INSIDE_KEY state, check for default tag */
    if (xmlStrEqual(name, toXmlChar("default"))) state->st=INSIDE_DEFAULT;
    else igraph_i_graphml_handle_unknown_start_tag(state);
    break;

  case INSIDE_DEFAULT:
    /* If we are in the INSIDE_DEFAULT state, every further tag will be unknown */
    igraph_i_graphml_handle_unknown_start_tag(state);
    break;
    
  case INSIDE_GRAPH:
    /* If we are in the INSIDE_GRAPH state, check for node and edge tags */
    if (xmlStrEqual(name, toXmlChar("edge"))) {
      id1=-1; id2=-1; directed=state->edges_directed;
      for (it=(xmlChar**)attrs; *it; it+=2) {
	if (xmlStrEqual(*it, toXmlChar("source"))) {
	  igraph_trie_get(&state->node_trie, fromXmlChar(*(it+1)), &id1);
	}
	if (xmlStrEqual(*it, toXmlChar("target"))) {
	  igraph_trie_get(&state->node_trie, fromXmlChar(*(it+1)), &id2);
	}
	if (xmlStrEqual(*it, toXmlChar("id"))) {
	  long int edges=igraph_vector_size(&state->edgelist)/2+1;
	  long int origsize=igraph_strvector_size(&state->edgeids);
	  igraph_strvector_resize(&state->edgeids, edges);
	  for (;origsize < edges-1; origsize++) {
	    igraph_strvector_set(&state->edgeids, origsize, "");
	  }
	  igraph_strvector_set(&state->edgeids, edges-1, fromXmlChar(*(it+1)));
	}
      }
      if (id1>=0 && id2>=0) {
	igraph_vector_push_back(&state->edgelist, id1);
	igraph_vector_push_back(&state->edgelist, id2);
      } else {
	igraph_i_graphml_sax_handler_error(state, "Edge with missing source or target encountered");
	return;
      }
      state->st=INSIDE_EDGE;
    } else if (xmlStrEqual(name, toXmlChar("node"))) {
      for (it=(xmlChar**)attrs; *it; it+=2) {
	if (xmlStrEqual(*it, toXmlChar("id"))) {
	  it++;
	  igraph_trie_get(&state->node_trie, fromXmlChar(*it), &id1);
	  break;
	}
      }
      state->st=INSIDE_NODE;
    } else if (xmlStrEqual(name, toXmlChar("data"))) {
      igraph_i_graphml_attribute_data_setup(state, attrs, IGRAPH_ATTRIBUTE_GRAPH);
      state->prev_state=state->st;
      state->st=INSIDE_DATA;
    } else
      igraph_i_graphml_handle_unknown_start_tag(state);
    break;
    
  case INSIDE_NODE:
    if (xmlStrEqual(name, toXmlChar("data"))) {
      igraph_i_graphml_attribute_data_setup(state, attrs,
					    IGRAPH_ATTRIBUTE_VERTEX);
      state->prev_state=state->st;
      state->st=INSIDE_DATA;
    }
    break;
    
  case INSIDE_EDGE:
    if (xmlStrEqual(name, toXmlChar("data"))) {
      igraph_i_graphml_attribute_data_setup(state, attrs, 
					    IGRAPH_ATTRIBUTE_EDGE);
      state->prev_state=state->st;
      state->st=INSIDE_DATA;
    }
    break;
    
  default:
    break;
  }
}

void igraph_i_graphml_sax_handler_end_element(void *state0,
						const xmlChar* name) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  
  switch (state->st) {
  case INSIDE_GRAPHML:
    state->st=FINISH;
    break;
    
  case INSIDE_GRAPH:
    state->st=INSIDE_GRAPHML;
    break;
    
  case INSIDE_KEY:
    state->st=INSIDE_GRAPHML;
    break;

  case INSIDE_DEFAULT:
    state->st=INSIDE_KEY;
    break;
    
  case INSIDE_NODE:
    state->st=INSIDE_GRAPH;
    break;
    
  case INSIDE_EDGE:
    state->st=INSIDE_GRAPH;
    break;

  case INSIDE_DATA:
    igraph_i_graphml_attribute_data_finish(state);
    state->st=state->prev_state;
    break;
    
  case UNKNOWN:
    state->unknown_depth--;
    if (!state->unknown_depth) state->st=state->prev_state;
    break;
    
  default:
    break;
  }
}

void igraph_i_graphml_sax_handler_chars(void* state0, const xmlChar* ch, int len) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  
  switch (state->st) {
  case INSIDE_KEY:
  case INSIDE_DEFAULT:
    break;
    
  case INSIDE_DATA:
    igraph_i_graphml_attribute_data_add(state, ch, len);
    break;
    
  default:
    /* just ignore it */
    break;
  }
}

static xmlSAXHandler igraph_i_graphml_sax_handler={
  NULL, NULL, NULL, NULL, NULL,
    igraph_i_graphml_sax_handler_get_entity,
    NULL, NULL, NULL, NULL, NULL, NULL,
    igraph_i_graphml_sax_handler_start_document,
    igraph_i_graphml_sax_handler_end_document,
    igraph_i_graphml_sax_handler_start_element,
    igraph_i_graphml_sax_handler_end_element,
    NULL,
    igraph_i_graphml_sax_handler_chars,
    NULL, NULL, NULL,
    igraph_i_graphml_sax_handler_error,
    igraph_i_graphml_sax_handler_error,
    igraph_i_graphml_sax_handler_error,
};

#endif

int igraph_i_xml_escape(char* src, char** dest) {
  long int destlen=0;
  char *s, *d;
  for (s=src; *s; s++, destlen++) {
    if (*s == '&') destlen += 4;
    else if (*s == '<') destlen += 3;
    else if (*s == '>') destlen += 3;
    else if (*s == '"') destlen += 5;
    else if (*s == '\'') destlen += 5;
  }
  *dest=igraph_Calloc(destlen+1, char);
  if (!*dest) IGRAPH_ERROR("Not enough memory", IGRAPH_ENOMEM);
  for (s=src, d=*dest; *s; s++, d++) {
    switch (*s) {
    case '&':
      strcpy(d, "&amp;"); d+=4; break;
    case '<':
      strcpy(d, "&lt;"); d+=3; break;
    case '>':
      strcpy(d, "&gt;"); d+=3; break;
    case '"':
      strcpy(d, "&quot;"); d+=5; break;
    case '\'':
      strcpy(d, "&apos;"); d+=5; break;
    default:
      *d = *s;
    }
  }
  *d=0;
  return 0;
}

/**
 * \ingroup loadsave
 * \function igraph_read_graph_graphml
 * \brief Reads a graph from a GraphML file.
 * 
 * </para><para>
 * GraphML is an XML-based file format for representing various types of
 * graphs. Currently only the most basic import functionality is implemented
 * in igraph: it can read GraphML files without nested graphs and hyperedges.
 * Attributes of the graph are loaded only if an attribute interface
 * is attached, ie. if you use igraph from R or Python.
 * \param graph Pointer to an uninitialized graph object.
 * \param instream A stream, it should be readable.
 * \param index If the GraphML file contains more than one graph, the one
 *              specified by this index will be loaded. Indices start from
 *              zero, so supply zero here if your GraphML file contains only
 *              a single graph.
 * 
 * \return Error code:
 *         \c IGRAPH_PARSEERROR: if there is a
 *         problem reading the file, or the file is syntactically
 *         incorrect.
 *         \c IGRAPH_UNIMPLEMENTED: the GraphML functionality was disabled
 *         at compile-time
 */
int igraph_read_graph_graphml(igraph_t *graph, FILE *instream,
			      int index) {

#if HAVE_LIBXML == 1
  xmlParserCtxtPtr ctxt;
  struct igraph_i_graphml_parser_state state;
  int res;
  char buffer[4096];

  if (index<0)
    IGRAPH_ERROR("Graph index must be non-negative", IGRAPH_EINVAL);
  
  /* Create a progressive parser context */
  state.g=graph;
  state.index=index<0?0:index;
  res=fread(buffer, 1, 4096, instream);
  ctxt=xmlCreatePushParserCtxt(&igraph_i_graphml_sax_handler,
			       &state,
			       buffer,
			       res,
			       NULL);
/*   ctxt=xmlCreateIOParserCtxt(&igraph_i_graphml_sax_handler, &state, */
/* 			     igraph_i_libxml2_read_callback, */
/* 			     igraph_i_libxml2_close_callback, */
/* 			     instream, XML_CHAR_ENCODING_NONE); */
  if (ctxt==NULL)
    IGRAPH_ERROR("Can't create progressive parser context", IGRAPH_PARSEERROR);

  /* Parse the file */
  while ((res=fread(buffer, 1, 4096, instream))>0) {
    xmlParseChunk(ctxt, buffer, res, 0);
    if (!state.successful) break;
  }
  xmlParseChunk(ctxt, buffer, res, 1);
  
  /* Free the context */
  xmlFreeParserCtxt(ctxt);
  if (!state.successful) {
    if (state.error_message != 0)
      IGRAPH_ERROR(state.error_message, IGRAPH_PARSEERROR);
    else
      IGRAPH_ERROR("Malformed GraphML file", IGRAPH_PARSEERROR);
  }
  if (state.index>=0)
    IGRAPH_ERROR("Graph index was too large", IGRAPH_EINVAL);
  
  return 0;
#else
  IGRAPH_ERROR("GraphML support is disabled", IGRAPH_UNIMPLEMENTED);
#endif
}

/**
 * \ingroup loadsave
 * \function igraph_write_graph_graphml
 * \brief Writes the graph to a file in GraphML format
 *
 * </para><para>
 * GraphML is an XML-based file format for representing various types of
 * graphs. See the GraphML Primer (http://graphml.graphdrawing.org/primer/graphml-primer.html)
 * for detailed format description.
 * 
 * \param graph The graph to write. 
 * \param outstream The stream object to write to, it should be
 *        writable.
 * \return Error code:
 *         \c IGRAPH_EFILE if there is an error
 *         writing the file. 
 *
 * Time complexity: O(|V|+|E|) otherwise. All
 * file operations are expected to have time complexity 
 * O(1). 
 */
int igraph_write_graph_graphml(const igraph_t *graph, FILE *outstream) {
  int ret;
  igraph_integer_t l, vc;
  igraph_eit_t it;
  igraph_strvector_t gnames, vnames, enames;
  igraph_vector_t gtypes, vtypes, etypes;
  long int i;
  igraph_vector_t numv;
  igraph_strvector_t strv;
  
  ret=fprintf(outstream, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  ret=fprintf(outstream, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  ret=fprintf(outstream, "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  ret=fprintf(outstream, "         xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  ret=fprintf(outstream, "         http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  ret=fprintf(outstream, "<!-- Created by igraph -->\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);

  /* dump the <key> elements if any */

  IGRAPH_VECTOR_INIT_FINALLY(&numv, 1);
  IGRAPH_STRVECTOR_INIT_FINALLY(&strv, 1);
  
  IGRAPH_STRVECTOR_INIT_FINALLY(&gnames, 0);
  IGRAPH_STRVECTOR_INIT_FINALLY(&vnames, 0);
  IGRAPH_STRVECTOR_INIT_FINALLY(&enames, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&gtypes, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&vtypes, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&etypes, 0);
  igraph_i_attribute_get_info(graph,
			      &gnames, &gtypes,
			      &vnames, &vtypes,
			      &enames, &etypes);
  
  /* graph attributes */
  for (i=0; i<igraph_vector_size(&gtypes); i++) {
    char *name, *name_escaped;
    igraph_strvector_get(&gnames, i, &name);
    IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
    if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
      ret=fprintf(outstream, "  <key id=\"%s\" for=\"graph\" attr.name=\"%s\" attr.type=\"string\"/>\n", name_escaped, name_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);      
    } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
      ret=fprintf(outstream, "  <key id=\"%s\" for=\"graph\" attr.name=\"%s\" attr.type=\"double\"/>\n", name_escaped, name_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);            
    }
    igraph_Free(name_escaped);
  }

  /* vertex attributes */
  for (i=0; i<igraph_vector_size(&vtypes); i++) {
    char *name, *name_escaped;
    igraph_strvector_get(&vnames, i, &name);
    IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
    if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
      ret=fprintf(outstream, "  <key id=\"%s\" for=\"node\" attr.name=\"%s\" attr.type=\"string\"/>\n", name_escaped, name_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);      
    } else if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
      ret=fprintf(outstream, "  <key id=\"%s\" for=\"node\" attr.name=\"%s\" attr.type=\"double\"/>\n", name_escaped, name_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);            
    }
    igraph_Free(name_escaped);
  }

  /* edge attributes */
  for (i=0; i<igraph_vector_size(&etypes); i++) {
    char *name, *name_escaped;
    igraph_strvector_get(&enames, i, &name);
    IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
    if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
      ret=fprintf(outstream, "  <key id=\"%s\" for=\"edge\" attr.name=\"%s\" attr.type=\"string\"/>\n", name_escaped, name_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
    } else if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
      ret=fprintf(outstream, "  <key id=\"%s\" for=\"edge\" attr.name=\"%s\" attr.type=\"double\"/>\n", name_escaped, name_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
    }
    igraph_Free(name_escaped);
  }

  ret=fprintf(outstream, "  <graph id=\"G\" edgedefault=\"%s\">\n", (igraph_is_directed(graph)?"directed":"undirected"));
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);

  /* Write the graph atributes before anything else */
  
  for (i=0; i<igraph_vector_size(&gtypes); i++) {
    char *name, *name_escaped;
    if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
      igraph_strvector_get(&gnames, i, &name);
      igraph_i_attribute_get_numeric_graph_attr(graph, name, &numv);
      if (!isnan(VECTOR(numv)[0])) {
	IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
	ret=fprintf(outstream, "    <data key=\"%s\">%g</data>\n",
		    name_escaped, VECTOR(numv)[0]);
	igraph_Free(name_escaped);
	if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
      }
    } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
      char *s, *s_escaped;
      igraph_strvector_get(&gnames, i, &name);
      IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
      ret=fprintf(outstream, "    <data key=\"%s\">", name_escaped);
      igraph_Free(name_escaped);
      igraph_i_attribute_get_string_graph_attr(graph, name, &strv);
      igraph_strvector_get(&strv, 0, &s);
      IGRAPH_CHECK(igraph_i_xml_escape(s, &s_escaped));
      ret=fprintf(outstream, "%s", s_escaped);
      igraph_Free(s_escaped);
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
      ret=fprintf(outstream, "</data>\n");
      if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
    }
  }
    
  /* Let's dump the nodes first */
  vc=igraph_vcount(graph);
  for (l=0; l<vc; l++) {
    char *name, *name_escaped;
    ret=fprintf(outstream, "    <node id=\"n%ld\">\n", (long)l);

    if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
    
    for (i=0; i<igraph_vector_size(&vtypes); i++) {
      if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_strvector_get(&vnames, i, &name);
	igraph_i_attribute_get_numeric_vertex_attr(graph, name,
						   igraph_vss_1(l), &numv);
	if (!isnan(VECTOR(numv)[0])) {
	  IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
	  ret=fprintf(outstream, "      <data key=\"%s\">%g</data>\n",
		      name_escaped, VECTOR(numv)[0]);
	  igraph_Free(name_escaped);
	  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
	}
      } else if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
	char *s, *s_escaped;
	igraph_strvector_get(&vnames, i, &name);
	IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
	ret=fprintf(outstream, "      <data key=\"%s\">", name_escaped);
	igraph_Free(name_escaped);
	igraph_i_attribute_get_string_vertex_attr(graph, name,
						  igraph_vss_1(l), &strv);
	igraph_strvector_get(&strv, 0, &s);
	IGRAPH_CHECK(igraph_i_xml_escape(s, &s_escaped));
	ret=fprintf(outstream, "%s", s_escaped);
	igraph_Free(s_escaped);
	if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
	ret=fprintf(outstream, "</data>\n");
	if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
      }
    }

    ret=fprintf(outstream, "    </node>\n");
    if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);    
  }
  
  /* Now the edges */
  IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(0), &it));
  IGRAPH_FINALLY(igraph_eit_destroy, &it);
  while (!IGRAPH_EIT_END(it)) {
    igraph_integer_t from, to;
    char *name, *name_escaped;
    long int edge=IGRAPH_EIT_GET(it);
    igraph_edge(graph, edge, &from, &to);
    ret=fprintf(outstream, "    <edge source=\"n%ld\" target=\"n%ld\">\n", 
		(long int)from, (long int)to);
    if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);

    for (i=0; i<igraph_vector_size(&etypes); i++) {
      if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_strvector_get(&enames, i, &name);
	igraph_i_attribute_get_numeric_edge_attr(graph, name,
						 igraph_ess_1(edge), &numv);
	if (!isnan(VECTOR(numv)[0])) {
	  IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
	  ret=fprintf(outstream, "      <data key=\"%s\">%g</data>\n",
		      name_escaped, VECTOR(numv)[0]);
	  igraph_Free(name_escaped);
	  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
	}
	if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);      
      } else if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_STRING) {
	char *s, *s_escaped;
	igraph_strvector_get(&enames, i, &name);
	IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped));
	ret=fprintf(outstream, "      <data key=\"%s\">", name_escaped);
	igraph_Free(name_escaped);
	igraph_i_attribute_get_string_edge_attr(graph, name,
						igraph_ess_1(edge), &strv);
	igraph_strvector_get(&strv, 0, &s);
	IGRAPH_CHECK(igraph_i_xml_escape(s, &s_escaped));
	ret=fprintf(outstream, "%s", s_escaped);
	igraph_Free(s_escaped);
	if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
	ret=fprintf(outstream, "</data>\n");
	if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
      }
    }

    ret=fprintf(outstream, "    </edge>\n");
    if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
    IGRAPH_EIT_NEXT(it);
  }
  igraph_eit_destroy(&it);
  IGRAPH_FINALLY_CLEAN(1);
  
  ret=fprintf(outstream, "  </graph>\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  fprintf(outstream, "</graphml>\n");
  if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE);
  
  igraph_strvector_destroy(&gnames);
  igraph_strvector_destroy(&vnames);
  igraph_strvector_destroy(&enames);
  igraph_vector_destroy(&gtypes);
  igraph_vector_destroy(&vtypes);
  igraph_vector_destroy(&etypes);
  igraph_vector_destroy(&numv);
  igraph_strvector_destroy(&strv);
  IGRAPH_FINALLY_CLEAN(8);

  return 0;
}