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