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