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