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