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