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