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