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