64ae8a6142e910935051fda76b70f636ce4c9c36
[pspp] / src / data / ods-reader.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "libpspp/message.h"
20 #include "libpspp/misc.h"
21 #include "libpspp/assertion.h"
22
23 #include "data/data-in.h"
24
25 #include "gl/c-strtod.h"
26 #include "gl/minmax.h"
27
28 #include "gettext.h"
29 #define _(msgid) gettext (msgid)
30 #define N_(msgid) (msgid)
31
32 #include "ods-reader.h"
33 #include "spreadsheet-reader.h"
34
35 #if !ODF_READ_SUPPORT
36
37 struct casereader *
38 ods_open_reader (const struct spreadsheet_read_options *opts, 
39                  struct dictionary **dict)
40 {
41   msg (ME, _("Support for %s files was not compiled into this installation of PSPP"), "OpenDocument");
42
43   return NULL;
44 }
45
46 #else
47
48 #include "libpspp/zip-reader.h"
49
50
51 #include <assert.h>
52 #include <stdbool.h>
53 #include <errno.h>
54 #include <libxml/xmlreader.h>
55 #include <zlib.h>
56
57 #include "data/format.h"
58 #include "data/case.h"
59 #include "data/casereader-provider.h"
60 #include "data/dictionary.h"
61 #include "data/identifier.h"
62 #include "data/value.h"
63 #include "data/variable.h"
64 #include "libpspp/i18n.h"
65 #include "libpspp/str.h"
66
67 #include "gl/xalloc.h"
68
69 static void ods_file_casereader_destroy (struct casereader *, void *);
70 static struct ccase *ods_file_casereader_read (struct casereader *, void *);
71
72
73 static const struct casereader_class ods_file_casereader_class =
74   {
75     ods_file_casereader_read,
76     ods_file_casereader_destroy,
77     NULL,
78     NULL,
79   };
80
81 struct sheet_detail
82 {
83   /* The name of the sheet (utf8 encoding) */
84   char *name;
85
86   int start_col;
87   int stop_col;
88   int start_row;
89   int stop_row;
90 };
91
92
93 enum reader_state
94   {
95     STATE_INIT = 0,        /* Initial state */
96     STATE_SPREADSHEET,     /* Found the start of the spreadsheet doc */
97     STATE_TABLE,           /* Found the sheet that we actually want */
98     STATE_ROW,             /* Found the start of the cell array */
99     STATE_CELL,            /* Found a cell */
100     STATE_CELL_CONTENT     /* Found a the text within a cell */
101   };
102
103 struct state_data
104 {
105   xmlTextReaderPtr xtr;
106   int node_type;
107   enum reader_state state;
108   int row;
109   int col;
110   int current_sheet;
111   xmlChar *current_sheet_name;
112
113   int col_span;
114 };
115
116 static void
117 state_data_destroy (struct state_data *sd)
118 {
119   xmlFree (sd->current_sheet_name);
120   sd->current_sheet_name = NULL;
121
122   xmlFreeTextReader (sd->xtr);
123   sd->xtr = NULL;
124 }
125
126 struct ods_reader
127 {
128   struct spreadsheet spreadsheet;
129   struct zip_reader *zreader;
130
131   int target_sheet_index;
132   xmlChar *target_sheet_name;
133   
134   /* State data for the meta data */
135   struct state_data msd;
136
137   /* State data for the reader */
138   struct state_data rsd;
139
140   int start_row;
141   int start_col;
142   int stop_row;
143   int stop_col;
144
145   struct sheet_detail *sheets;
146   int n_allocated_sheets;
147
148   struct caseproto *proto;
149   struct dictionary *dict;
150   struct ccase *first_case;
151   bool used_first_case;
152   bool read_names;
153
154   struct string ods_errs;
155
156   struct string zip_errs;
157 };
158
159 void
160 ods_unref (struct spreadsheet *s)
161 {
162   struct ods_reader *r = (struct ods_reader *) s;
163
164   if (--s->ref_cnt == 0)
165     {
166       int i;
167
168       state_data_destroy (&r->msd);
169       for (i = 0; i < r->n_allocated_sheets; ++i)
170         {
171           xmlFree (r->sheets[i].name);
172         }
173         
174       zip_reader_destroy (r->zreader);
175       free (r->sheets);
176
177       free (s->file_name);
178         
179       free (r);
180     }
181 }
182
183
184
185 static bool
186 reading_target_sheet (const struct ods_reader *r, const struct state_data *msd)
187 {
188   if (r->target_sheet_name != NULL)
189     {
190       if ( 0 == xmlStrcmp (r->target_sheet_name, msd->current_sheet_name))
191         return true;
192     }
193   
194   if (r->target_sheet_index == msd->current_sheet + 1)
195     return true;
196
197   return false;
198 }
199
200
201 static void process_node (struct ods_reader *or, struct state_data *r);
202
203
204 const char *
205 ods_get_sheet_name (struct spreadsheet *s, int n)
206 {
207   struct ods_reader *r = (struct ods_reader *) s;
208   struct state_data *or = &r->msd;
209
210   assert (n < s->n_sheets);
211
212   while ( 
213           (r->n_allocated_sheets <= n)
214           || or->state != STATE_SPREADSHEET
215           )
216     {
217       int ret = xmlTextReaderRead (or->xtr);
218       if ( ret != 1)
219         break;
220
221       process_node (r, or);
222     }
223
224   return r->sheets[n].name;
225 }
226
227 char *
228 ods_get_sheet_range (struct spreadsheet *s, int n)
229 {
230   struct ods_reader *r = (struct ods_reader *) s;
231   struct state_data *or = &r->msd;
232   
233   assert (n < s->n_sheets);
234
235   while ( 
236           (r->n_allocated_sheets <= n)
237           || (r->sheets[n].stop_row == -1) 
238           || or->state != STATE_SPREADSHEET
239           )
240     {
241       int ret = xmlTextReaderRead (or->xtr);
242       if ( ret != 1)
243         break;
244
245       process_node (r, or);
246     }
247
248   return create_cell_range (
249                           r->sheets[n].start_col,
250                           r->sheets[n].start_row,
251                           r->sheets[n].stop_col,
252                           r->sheets[n].stop_row);
253 }
254
255
256 static void
257 ods_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
258 {
259   struct ods_reader *r = r_;
260   if ( r == NULL)
261     return ;
262
263   state_data_destroy (&r->rsd);
264
265   if ( ! ds_is_empty (&r->ods_errs))
266     msg (ME, "%s", ds_cstr (&r->ods_errs));
267
268   ds_destroy (&r->ods_errs);
269
270   if ( r->first_case && ! r->used_first_case )
271     case_unref (r->first_case);
272
273
274   caseproto_unref (r->proto);
275   r->proto = NULL;
276
277   xmlFree (r->target_sheet_name);
278   r->target_sheet_name = NULL;
279
280
281   ods_unref (&r->spreadsheet);
282 }
283
284
285
286
287
288 static void
289 process_node (struct ods_reader *or, struct state_data *r)
290 {
291   xmlChar *name = xmlTextReaderName (r->xtr);
292   if (name == NULL)
293     name = xmlStrdup (_xml ("--"));
294
295
296   r->node_type = xmlTextReaderNodeType (r->xtr);
297
298   switch (r->state)
299     {
300     case STATE_INIT:
301       if (0 == xmlStrcasecmp (name, _xml("office:spreadsheet")) &&
302           XML_READER_TYPE_ELEMENT  == r->node_type)
303         {
304           r->state = STATE_SPREADSHEET;
305           r->current_sheet = -1;
306           r->current_sheet_name = NULL;
307         }
308       break;
309     case STATE_SPREADSHEET:
310       if (0 == xmlStrcasecmp (name, _xml("table:table"))
311           && 
312           (XML_READER_TYPE_ELEMENT == r->node_type))
313         {
314           xmlFree (r->current_sheet_name);
315           r->current_sheet_name = xmlTextReaderGetAttribute (r->xtr, _xml ("table:name"));
316
317           ++r->current_sheet;
318
319           if (r->current_sheet >= or->n_allocated_sheets)
320             {
321               assert (r->current_sheet == or->n_allocated_sheets);
322               or->sheets = xrealloc (or->sheets, sizeof (*or->sheets) * ++or->n_allocated_sheets);
323               or->sheets[or->n_allocated_sheets - 1].start_col = -1;
324               or->sheets[or->n_allocated_sheets - 1].stop_col = -1;
325               or->sheets[or->n_allocated_sheets - 1].start_row = -1;
326               or->sheets[or->n_allocated_sheets - 1].stop_row = -1;
327               or->sheets[or->n_allocated_sheets - 1].name = CHAR_CAST (char *, xmlStrdup (r->current_sheet_name));
328             }
329
330           r->col = 0;
331           r->row = 0;
332
333           r->state = STATE_TABLE;
334         }
335       else if (0 == xmlStrcasecmp (name, _xml("office:spreadsheet")) &&
336                XML_READER_TYPE_ELEMENT  == r->node_type)
337         {
338           r->state = STATE_INIT;
339         }
340       break;
341     case STATE_TABLE:
342       if (0 == xmlStrcasecmp (name, _xml("table:table-row")) && 
343           (XML_READER_TYPE_ELEMENT  == r->node_type))
344         {
345           xmlChar *value =
346             xmlTextReaderGetAttribute (r->xtr,
347                                        _xml ("table:number-rows-repeated"));
348           
349           int row_span = value ? _xmlchar_to_int (value) : 1;
350
351           r->row += row_span;
352           r->col = 0;
353           
354           if (! xmlTextReaderIsEmptyElement (r->xtr))
355             r->state = STATE_ROW;
356
357           xmlFree (value);
358         }
359       else if (0 == xmlStrcasecmp (name, _xml("table:table")) && 
360                (XML_READER_TYPE_END_ELEMENT  == r->node_type))
361         {
362           r->state = STATE_SPREADSHEET;
363         }
364       break;
365     case STATE_ROW:
366       if ( (0 == xmlStrcasecmp (name, _xml ("table:table-cell")))
367            && 
368            (XML_READER_TYPE_ELEMENT  == r->node_type))
369         {
370           xmlChar *value =
371             xmlTextReaderGetAttribute (r->xtr,
372                                        _xml ("table:number-columns-repeated"));
373           
374           r->col_span = value ? _xmlchar_to_int (value) : 1;
375           r->col += r->col_span;
376
377           if (! xmlTextReaderIsEmptyElement (r->xtr))
378             r->state = STATE_CELL;
379
380           xmlFree (value);
381         }
382       else if ( (0 == xmlStrcasecmp (name, _xml ("table:table-row")))
383                 &&
384                 (XML_READER_TYPE_END_ELEMENT  == r->node_type))
385         {
386           r->state = STATE_TABLE;
387         }
388       break;
389     case STATE_CELL:
390       if ( (0 == xmlStrcasecmp (name, _xml("text:p")))
391             &&
392            ( XML_READER_TYPE_ELEMENT  == r->node_type))
393         {
394           if (! xmlTextReaderIsEmptyElement (r->xtr))
395             r->state = STATE_CELL_CONTENT;
396         }
397       else if
398         ( (0 == xmlStrcasecmp (name, _xml("table:table-cell")))
399           &&
400           (XML_READER_TYPE_END_ELEMENT  == r->node_type)
401           )
402         {
403           r->state = STATE_ROW;
404         }
405       break;
406     case STATE_CELL_CONTENT:
407       assert (r->current_sheet >= 0);
408       assert (r->current_sheet < or->n_allocated_sheets);
409
410       if (or->sheets[r->current_sheet].start_row == -1)
411         or->sheets[r->current_sheet].start_row = r->row - 1;
412
413       if ( 
414           (or->sheets[r->current_sheet].start_col == -1)
415           ||
416           (or->sheets[r->current_sheet].start_col >= r->col - 1)
417            )
418         or->sheets[r->current_sheet].start_col = r->col - 1;
419
420       or->sheets[r->current_sheet].stop_row = r->row - 1;
421
422       if ( or->sheets[r->current_sheet].stop_col <  r->col - 1)
423         or->sheets[r->current_sheet].stop_col = r->col - 1;
424
425       if (XML_READER_TYPE_END_ELEMENT  == r->node_type)
426         r->state = STATE_CELL;
427       break;
428     default:
429       NOT_REACHED ();
430       break;
431     };
432
433   xmlFree (name);
434 }
435
436 /* 
437    A struct containing the parameters of a cell's value 
438    parsed from the xml
439 */
440 struct xml_value
441 {
442   xmlChar *type;
443   xmlChar *value;
444   xmlChar *text;
445 };
446
447 struct var_spec
448 {
449   char *name;
450   struct xml_value firstval;
451 };
452
453
454 /* Determine the width that a xmv should probably have */
455 static int
456 xmv_to_width (const struct xml_value *xmv, int fallback)
457 {
458   int width = SPREADSHEET_DEFAULT_WIDTH;
459
460   /* Non-strings always have zero width */
461   if (xmv->type != NULL && 0 != xmlStrcmp (xmv->type, _xml("string")))
462     return 0;
463
464   if ( fallback != -1)
465     return fallback;
466
467   if ( xmv->value )
468     width = ROUND_UP (xmlStrlen (xmv->value),
469                       SPREADSHEET_DEFAULT_WIDTH);
470   else if ( xmv->text)
471     width = ROUND_UP (xmlStrlen (xmv->text),
472                       SPREADSHEET_DEFAULT_WIDTH);
473
474   return width;
475 }
476
477 /*
478    Sets the VAR of case C, to the value corresponding to the xml data
479  */
480 static void
481 convert_xml_to_value (struct ccase *c, const struct variable *var,
482                       const struct xml_value *xmv, int col, int row)
483 {
484   union value *v = case_data_rw (c, var);
485
486   if (xmv->value == NULL && xmv->text == NULL)
487     value_set_missing (v, var_get_width (var));
488   else if ( var_is_alpha (var))
489     /* Use the text field, because it seems that there is no
490        value field for strings */
491     value_copy_str_rpad (v, var_get_width (var), xmv->text, ' ');
492   else
493     {
494       const struct fmt_spec *fmt = var_get_write_format (var);
495       enum fmt_category fc  = fmt_get_category (fmt->type);
496
497       assert ( fc != FMT_CAT_STRING);
498
499       if ( 0 == xmlStrcmp (xmv->type, _xml("float")))
500         {
501           v->f = c_strtod (CHAR_CAST (const char *, xmv->value), NULL);
502         }
503       else
504         {
505           const char *text = xmv->value ?
506             CHAR_CAST (const char *, xmv->value) : CHAR_CAST (const char *, xmv->text);
507
508           char *m = data_in (ss_cstr (text), "UTF-8",
509                          fmt->type,
510                          v,
511                          var_get_width (var),
512                          "UTF-8");
513
514           if (m)
515             {
516               char buf [FMT_STRING_LEN_MAX + 1];
517               char *cell = create_cell_ref (col, row);
518
519               msg (MW, _("Cannot convert the value in the spreadsheet cell %s to format (%s): %s"), 
520                    cell, fmt_to_string (fmt, buf), m);
521               free (cell);
522             }
523           free (m);
524         }
525     }
526 }
527
528
529 /* Try to find out how many sheets there are in the "workbook" */
530 static int
531 get_sheet_count (struct zip_reader *zreader)
532 {
533   xmlTextReaderPtr mxtr;
534   struct zip_member *meta = NULL;
535   meta = zip_member_open (zreader, "meta.xml");
536
537   if ( meta == NULL)
538     return -1;
539
540   mxtr = xmlReaderForIO ((xmlInputReadCallback) zip_member_read,
541                          (xmlInputCloseCallback) NULL,
542                          meta,   NULL, NULL, 0);
543
544   while (1 == xmlTextReaderRead (mxtr))
545     {
546       xmlChar *name = xmlTextReaderName (mxtr);
547       if ( 0 == xmlStrcmp (name, _xml("meta:document-statistic")))
548         {
549           xmlChar *attr = xmlTextReaderGetAttribute (mxtr, _xml ("meta:table-count"));
550
551           if ( attr != NULL)
552             {
553               int s = _xmlchar_to_int (attr);
554               xmlFreeTextReader (mxtr);
555               xmlFree (name);
556               xmlFree (attr);      
557               return s;
558             }
559           xmlFree (attr);      
560         }
561       xmlFree (name);      
562     }
563
564   xmlFreeTextReader (mxtr);
565   return -1;
566 }
567
568 static void
569 ods_error_handler (void *ctx, const char *mesg,
570                         UNUSED xmlParserSeverities sev, xmlTextReaderLocatorPtr loc)
571 {
572   struct ods_reader *r = ctx;
573        
574   msg (MW, _("There was a problem whilst reading the %s file `%s' (near line %d): `%s'"),
575        "ODF",
576        r->spreadsheet.file_name,
577        xmlTextReaderLocatorLineNumber (loc),
578        mesg);
579 }
580
581
582 static xmlTextReaderPtr
583 init_reader (struct ods_reader *r, bool report_errors)
584 {
585   struct zip_member *content = zip_member_open (r->zreader, "content.xml");
586   xmlTextReaderPtr xtr;
587
588   if ( content == NULL)
589     return NULL;
590
591   xtr = xmlReaderForIO ((xmlInputReadCallback) zip_member_read,
592                         (xmlInputCloseCallback) NULL,
593                         content,   NULL, NULL,
594                         report_errors ? 0 : (XML_PARSE_NOERROR | XML_PARSE_NOWARNING) );
595
596   if ( xtr == NULL)
597     return false;
598
599
600   r->spreadsheet.type = SPREADSHEET_ODS;
601
602   if (report_errors) 
603     xmlTextReaderSetErrorHandler (xtr, ods_error_handler, r);
604
605   return xtr;
606 }
607
608
609
610 struct spreadsheet *
611 ods_probe (const char *filename, bool report_errors)
612 {
613   int sheet_count;
614   struct ods_reader *r = xzalloc (sizeof *r);
615   xmlTextReaderPtr xtr;  
616   struct zip_reader *zr;
617
618   ds_init_empty (&r->zip_errs);
619
620   zr = zip_reader_create (filename, &r->zip_errs);
621
622   if (zr == NULL)
623     {
624       if (report_errors)
625         {
626           msg (ME, _("Cannot open %s as a OpenDocument file: %s"),
627                filename, ds_cstr (&r->zip_errs));
628         }
629       ds_destroy (&r->zip_errs);
630       free (r);
631       return NULL;
632     }
633
634   sheet_count = get_sheet_count (zr);
635
636   r->zreader = zr;
637   r->spreadsheet.ref_cnt = 1;
638
639   xtr = init_reader (r, report_errors);
640   if (xtr == NULL)
641     {
642       goto error;
643     }
644   r->msd.xtr = xtr;
645   r->msd.row = 0;
646   r->msd.col = 0;
647   r->msd.current_sheet = 0;
648   r->msd.state = STATE_INIT;
649
650
651   r->spreadsheet.n_sheets = sheet_count;
652   r->n_allocated_sheets = 0;
653   r->sheets = NULL;
654
655   r->spreadsheet.file_name = strdup (filename);
656   return &r->spreadsheet;
657
658  error:
659   ds_destroy (&r->zip_errs);
660   zip_reader_destroy (r->zreader);
661   free (r);
662   return NULL;
663 }
664
665 struct casereader *
666 ods_make_reader (struct spreadsheet *spreadsheet, 
667                  const struct spreadsheet_read_options *opts)
668 {
669   intf ret = 0;
670   xmlChar *type = NULL;
671   unsigned long int vstart = 0;
672   casenumber n_cases = CASENUMBER_MAX;
673   int i;
674   struct var_spec *var_spec = NULL;
675   int n_var_specs = 0;
676   xmlTextReaderPtr xtr;
677
678   struct ods_reader *r = (struct ods_reader *) spreadsheet;
679   xmlChar *val_string = NULL;
680
681   assert (r);
682   r->read_names = opts->read_names;
683   ds_init_empty (&r->ods_errs);
684   ++r->spreadsheet.ref_cnt;
685
686   xtr = init_reader (r, true);
687   if ( xtr == NULL)
688     goto error;
689
690   r->rsd.xtr = xtr;
691   r->rsd.row = 0;
692   r->rsd.col = 0;
693   r->rsd.current_sheet = 0;
694   r->rsd.state = STATE_INIT;
695
696   r->used_first_case = false;
697   r->first_case = NULL;
698
699   if (opts->cell_range)
700     {
701       if ( ! convert_cell_ref (opts->cell_range,
702                                &r->start_col, &r->start_row,
703                                &r->stop_col, &r->stop_row))
704         {
705           msg (SE, _("Invalid cell range `%s'"),
706                opts->cell_range);
707           goto error;
708         }
709     }
710   else
711     {
712       r->start_col = 0;
713       r->start_row = 0;
714       r->stop_col = -1;
715       r->stop_row = -1;
716     }
717
718   r->target_sheet_name = xmlStrdup (BAD_CAST opts->sheet_name);
719   r->target_sheet_index = opts->sheet_index;
720
721   /* Advance to the start of the cells for the target sheet */
722   while ( ! reading_target_sheet (r, &r->rsd)  
723           || r->rsd.state != STATE_ROW || r->rsd.row <= r->start_row )
724     {
725       if (1 != (ret = xmlTextReaderRead (r->rsd.xtr)))
726            break;
727
728       process_node (r, &r->rsd);
729     }
730
731   if (ret < 1)
732     {
733       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
734            spreadsheet->file_name);
735       goto error;
736     }
737
738   if ( opts->read_names)
739     {
740       while (1 == xmlTextReaderRead (r->rsd.xtr))
741         {
742           int idx;
743
744           process_node (r, &r->rsd);
745
746           /* If the row is finished then stop for now */
747           if (r->rsd.state == STATE_TABLE && r->rsd.row > r->start_row)
748             break;
749
750           idx = r->rsd.col - r->start_col -1 ;
751
752           if ( idx < 0)
753             continue;
754
755           if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
756             continue;
757
758           if (r->rsd.state == STATE_CELL_CONTENT 
759               &&
760               XML_READER_TYPE_TEXT  == r->rsd.node_type)
761             {
762               xmlChar *value = xmlTextReaderValue (r->rsd.xtr);
763
764               if ( idx >= n_var_specs)
765                 {
766                   var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
767
768                   /* xrealloc (unlike realloc) doesn't initialise its memory to 0 */
769                   memset (var_spec + n_var_specs,
770                           0, 
771                           (idx - n_var_specs + 1) * sizeof (*var_spec));
772                   n_var_specs = idx + 1;
773                 }
774               var_spec[idx].firstval.text = 0;
775               var_spec[idx].firstval.value = 0;
776               var_spec[idx].firstval.type = 0;
777
778               var_spec [idx].name = strdup (CHAR_CAST (const char *, value));
779
780               xmlFree (value);
781             }
782         }
783     }
784
785   /* Read in the first row of data */
786   while (1 == xmlTextReaderRead (r->rsd.xtr))
787     {
788       int idx;
789       process_node (r, &r->rsd);
790
791       if ( ! reading_target_sheet (r, &r->rsd) )
792         break;
793
794       /* If the row is finished then stop for now */
795       if (r->rsd.state == STATE_TABLE &&
796           r->rsd.row > r->start_row + (opts->read_names ? 1 : 0))
797         break;
798
799       idx = r->rsd.col - r->start_col - 1;
800       if (idx < 0)
801         continue;
802
803       if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
804         continue;
805
806       if ( r->rsd.state == STATE_CELL &&
807            XML_READER_TYPE_ELEMENT  == r->rsd.node_type)
808         {
809           type = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value-type"));
810           val_string = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value"));
811         }
812
813       if ( r->rsd.state == STATE_CELL_CONTENT &&
814            XML_READER_TYPE_TEXT  == r->rsd.node_type)
815         {
816           if (idx >= n_var_specs)
817             {
818               var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
819               memset (var_spec + n_var_specs,
820                       0, 
821                       (idx - n_var_specs + 1) * sizeof (*var_spec));
822
823               var_spec [idx].name = NULL;
824               n_var_specs = idx + 1;
825             }
826
827           var_spec [idx].firstval.type = type;
828           var_spec [idx].firstval.text = xmlTextReaderValue (r->rsd.xtr);
829           var_spec [idx].firstval.value = val_string;
830
831           val_string = NULL;
832           type = NULL;
833         }
834     }
835
836
837   /* Create the dictionary and populate it */
838   r->spreadsheet.dict = r->dict = dict_create (
839     CHAR_CAST (const char *, xmlTextReaderConstEncoding (r->rsd.xtr)));
840
841   for (i = 0; i < n_var_specs ; ++i )
842     {
843       struct fmt_spec fmt;
844       struct variable *var = NULL;
845       char *name = dict_make_unique_var_name (r->dict, var_spec[i].name, &vstart);
846       int width  = xmv_to_width (&var_spec[i].firstval, opts->asw);
847       dict_create_var (r->dict, name, width);
848       free (name);
849
850       var = dict_get_var (r->dict, i);
851
852       if ( 0 == xmlStrcmp (var_spec[i].firstval.type, _xml("date")))
853         {
854           fmt.type = FMT_DATE;
855           fmt.d = 0;
856           fmt.w = 20;
857         }
858       else
859         fmt = fmt_default_for_width (width);
860
861       var_set_both_formats (var, &fmt);
862     }
863
864   if ( n_var_specs ==  0 )
865     {
866       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
867            spreadsheet->file_name);
868       goto error;
869     }
870
871   /* Create the first case, and cache it */
872   r->proto = caseproto_ref (dict_get_proto (r->dict));
873   r->first_case = case_create (r->proto);
874   case_set_missing (r->first_case);
875
876   for (i = 0 ; i < n_var_specs; ++i)
877     {
878       const struct variable *var = dict_get_var (r->dict, i);
879
880       convert_xml_to_value (r->first_case, var,  &var_spec[i].firstval,
881                             r->rsd.col - n_var_specs + i,
882                             r->rsd.row - 1);
883     }
884
885   /* Read in the first row of data */
886   while (1 == xmlTextReaderRead (r->rsd.xtr))
887     {
888       process_node (r, &r->rsd);
889
890       if (r->rsd.state == STATE_ROW)
891         break;
892     }
893
894
895   for ( i = 0 ; i < n_var_specs ; ++i )
896     {
897       free (var_spec[i].firstval.type);
898       free (var_spec[i].firstval.value);
899       free (var_spec[i].firstval.text);
900       free (var_spec[i].name);
901     }
902
903   free (var_spec);
904
905
906   return casereader_create_sequential
907     (NULL,
908      r->proto,
909      n_cases,
910      &ods_file_casereader_class, r);
911
912  error:
913   
914   for ( i = 0 ; i < n_var_specs ; ++i )
915     {
916       free (var_spec[i].firstval.type);
917       free (var_spec[i].firstval.value);
918       free (var_spec[i].firstval.text);
919       free (var_spec[i].name);
920     }
921
922   free (var_spec);
923
924   dict_destroy (r->spreadsheet.dict);
925   r->spreadsheet.dict = NULL;
926   ods_file_casereader_destroy (NULL, r);
927
928   return NULL;
929 }
930
931
932 /* Reads and returns one case from READER's file.  Returns a null
933    pointer on failure. */
934 static struct ccase *
935 ods_file_casereader_read (struct casereader *reader UNUSED, void *r_)
936 {
937   struct ccase *c = NULL;
938   struct ods_reader *r = r_;
939
940   xmlChar *val_string = NULL;
941   xmlChar *type = NULL;
942
943   if (!r->used_first_case)
944     {
945       r->used_first_case = true;
946       return r->first_case;
947     }
948
949
950   /* Advance to the start of a row. (If there is one) */
951   while (r->rsd.state != STATE_ROW 
952          && 1 == xmlTextReaderRead (r->rsd.xtr)
953          )
954     {
955       process_node (r, &r->rsd);
956     }
957
958
959   if ( ! reading_target_sheet (r, &r->rsd)  
960        ||  r->rsd.state < STATE_TABLE
961        ||  (r->stop_row != -1 && r->rsd.row > r->stop_row + 1)
962        )
963     {
964       return NULL;
965     }
966
967   c = case_create (r->proto);
968   case_set_missing (c);
969   
970   while (1 == xmlTextReaderRead (r->rsd.xtr))
971     {
972       process_node (r, &r->rsd);
973
974       if ( r->stop_row != -1 && r->rsd.row > r->stop_row + 1)
975         break;
976
977       if (r->rsd.state == STATE_CELL &&
978            r->rsd.node_type == XML_READER_TYPE_ELEMENT)
979         {
980           type = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value-type"));
981           val_string = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value"));
982         }
983
984       if (r->rsd.state == STATE_CELL_CONTENT && 
985            r->rsd.node_type == XML_READER_TYPE_TEXT)
986         {
987           int col;
988           struct xml_value *xmv = xzalloc (sizeof *xmv);
989           xmv->text = xmlTextReaderValue (r->rsd.xtr);
990           xmv->value = val_string;       
991           val_string = NULL;
992           xmv->type = type;
993           type = NULL;
994
995           for (col = 0; col < r->rsd.col_span; ++col)
996             {
997               const struct variable *var;
998               const int idx = r->rsd.col - col - r->start_col - 1;
999               if (idx < 0)
1000                 continue;
1001               if (r->stop_col != -1 && idx > r->stop_col - r->start_col )
1002                 break;
1003               if (idx >= dict_get_var_cnt (r->dict))
1004                 break;
1005
1006               var = dict_get_var (r->dict, idx);
1007               convert_xml_to_value (c, var, xmv, idx + r->start_col, r->rsd.row - 1);
1008             }
1009
1010           xmlFree (xmv->text);
1011           xmlFree (xmv->value);
1012           xmlFree (xmv->type);
1013           free (xmv);
1014         }
1015       if ( r->rsd.state <= STATE_TABLE)
1016         break;
1017     }
1018
1019   xmlFree (type);
1020   xmlFree (val_string);
1021   
1022   return c;
1023 }
1024 #endif