Fewer memory 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 static struct ccase *ods_file_casereader_read (struct casereader *, void *);
71 static struct casereader *ods_file_casereader_clone (struct casereader *, void *);
72
73
74 static const struct casereader_class ods_file_casereader_class =
75   {
76     ods_file_casereader_read,
77     ods_file_casereader_destroy,
78     ods_file_casereader_clone,
79     NULL,
80   };
81
82 struct sheet_detail
83 {
84   /* The name of the sheet (utf8 encoding) */
85   char *name;
86
87   int start_col;
88   int stop_col;
89   int start_row;
90   int stop_row;
91 };
92
93
94 enum reader_state
95   {
96     STATE_INIT = 0,        /* Initial state */
97     STATE_SPREADSHEET,     /* Found the start of the spreadsheet doc */
98     STATE_TABLE,           /* Found the sheet that we actually want */
99     STATE_ROW,             /* Found the start of the cell array */
100     STATE_CELL,            /* Found a cell */
101     STATE_CELL_CONTENT     /* Found a the text within a cell */
102   };
103
104 struct ods_reader
105 {
106   struct spreadsheet spreadsheet;
107   struct zip_reader *zreader;
108   xmlTextReaderPtr xtr;
109   int ref_cnt;
110
111   enum reader_state state;
112   int row;
113   int col;
114   int node_type;
115   int current_sheet;
116   xmlChar *current_sheet_name;
117
118   xmlChar *target_sheet_name;
119   int target_sheet_index;
120
121
122   int start_row;
123   int start_col;
124   int stop_row;
125   int stop_col;
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 void
142 ods_destroy (struct spreadsheet *s)
143 {
144   struct ods_reader *r = s;
145   if (--r->ref_cnt == 0)
146     {
147       int i;
148
149       for (i = 0; i < r->n_allocated_sheets; ++i)
150         {
151           xmlFree (r->sheets[i].name);
152         }
153
154       zip_reader_destroy (r->zreader);
155       free (r->sheets);
156       free (r);
157     }
158 }
159
160
161
162 static bool
163 reading_target_sheet (const struct ods_reader *r)
164 {
165   if (r->target_sheet_name != NULL)
166     {
167       if ( 0 == xmlStrcmp (r->target_sheet_name, r->current_sheet_name))
168         return true;
169     }
170   
171   if (r->target_sheet_index == r->current_sheet + 1)
172     return true;
173
174   return false;
175 }
176
177
178 static void process_node (struct ods_reader *r);
179
180
181 const char *
182 ods_get_sheet_name (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->state != STATE_SPREADSHEET
191           )
192     {
193       int ret = xmlTextReaderRead (or->xtr);
194       if ( ret != 1)
195         break;
196
197       process_node (or);
198     }
199
200   return or->sheets[n].name;
201 }
202
203 char *
204 ods_get_sheet_range (struct spreadsheet *s, int n)
205 {
206   struct ods_reader *or = (struct ods_reader *) s;
207   
208   assert (n < s->n_sheets);
209
210   while ( 
211           (or->n_allocated_sheets <= n)
212           || (or->sheets[n].stop_row == -1) 
213           || or->state != STATE_SPREADSHEET
214           )
215     {
216       int ret = xmlTextReaderRead (or->xtr);
217       if ( ret != 1)
218         break;
219
220       process_node (or);
221     }
222
223   return create_cell_ref (
224                           or->sheets[n].start_col,
225                           or->sheets[n].start_row,
226                           or->sheets[n].stop_col,
227                           or->sheets[n].stop_row);
228 }
229
230
231 static struct casereader *
232 ods_file_casereader_clone (struct casereader *r_, void *s)
233 {
234   struct ods_reader *r = r_;
235
236   printf ("%s:%d CLONE reffing %p %d\n", __FILE__, __LINE__, s, r->ref_cnt);
237   
238   return r_;
239 }
240
241 static void
242 ods_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
243 {
244   struct ods_reader *r = r_;
245   if ( r == NULL)
246     return ;
247
248   if (r->xtr)
249     xmlFreeTextReader (r->xtr);
250   r->xtr = NULL;
251
252   if ( ! ds_is_empty (&r->ods_errs))
253     msg (ME, "%s", ds_cstr (&r->ods_errs));
254
255   ds_destroy (&r->ods_errs);
256
257   if ( ! r->used_first_case )
258     case_unref (r->first_case);
259
260   caseproto_unref (r->proto);
261
262   xmlFree (r->current_sheet_name);
263   xmlFree (r->target_sheet_name);
264
265   ods_destroy (r);
266 }
267
268
269
270
271
272 static void
273 process_node (struct ods_reader *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 >= r->n_allocated_sheets)
304             {
305               assert (r->current_sheet == r->n_allocated_sheets);
306               r->sheets = xrealloc (r->sheets, sizeof (*r->sheets) * ++r->n_allocated_sheets);
307               r->sheets[r->n_allocated_sheets - 1].start_col = -1;
308               r->sheets[r->n_allocated_sheets - 1].stop_col = -1;
309               r->sheets[r->n_allocated_sheets - 1].start_row = -1;
310               r->sheets[r->n_allocated_sheets - 1].stop_row = -1;
311               r->sheets[r->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 < r->n_allocated_sheets);
393
394       if (r->sheets[r->current_sheet].start_row == -1)
395         r->sheets[r->current_sheet].start_row = r->row - 1;
396
397       if ( 
398           (r->sheets[r->current_sheet].start_col == -1)
399           ||
400           (r->sheets[r->current_sheet].start_col >= r->col - 1)
401            )
402         r->sheets[r->current_sheet].start_col = r->col - 1;
403
404       r->sheets[r->current_sheet].stop_row = r->row - 1;
405
406       if ( r->sheets[r->current_sheet].stop_col <  r->col - 1)
407         r->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           free (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 bool
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 false;
564
565   if (r->xtr)
566     xmlFreeTextReader (r->xtr);
567
568   zip_member_ref (content);
569   xtr = xmlReaderForIO ((xmlInputReadCallback) zip_member_read,
570                         (xmlInputCloseCallback) zip_member_finish,
571                         content,   NULL, NULL,
572                         report_errors ? 0 : (XML_PARSE_NOERROR | XML_PARSE_NOWARNING) );
573
574   if ( xtr == NULL)
575     return false;
576
577   r->xtr = xtr;
578   r->spreadsheet.type = SPREADSHEET_ODS;
579   r->row = 0;
580   r->col = 0;
581   r->current_sheet = 0;
582   r->state = STATE_INIT;
583
584   if (report_errors) 
585     xmlTextReaderSetErrorHandler (xtr, ods_error_handler, r);
586
587   return true;
588 }
589
590
591 struct spreadsheet *
592 ods_probe (const char *filename, bool report_errors)
593 {
594   struct ods_reader *r;
595   struct string errs = DS_EMPTY_INITIALIZER;
596   int sheet_count;
597   struct zip_reader *zr = zip_reader_create (filename, &errs);
598
599   if (zr == NULL)
600     {
601       if (report_errors)
602         {
603           msg (ME, _("Cannot open %s as a OpenDocument file: %s"),
604                filename, ds_cstr (&errs));
605         }
606       return NULL;
607     }
608
609   sheet_count = get_sheet_count (zr);
610
611   r = xzalloc (sizeof *r);
612   r->zreader = zr;
613   r->ref_cnt = 1;
614
615   if (! init_reader (r, report_errors))
616     {
617       goto error;
618     }
619
620   r->spreadsheet.n_sheets = sheet_count;
621   r->n_allocated_sheets = 0;
622   r->sheets = NULL;
623
624   ds_destroy (&errs);
625
626   r->spreadsheet.file_name = filename;
627   return &r->spreadsheet;
628
629  error:
630   zip_reader_destroy (r->zreader);
631   ds_destroy (&errs);
632   free (r);
633   return NULL;
634 }
635
636 struct casereader *
637 ods_make_reader (struct spreadsheet *spreadsheet, 
638                  const struct spreadsheet_read_options *opts)
639 {
640   intf ret = 0;
641   xmlChar *type = NULL;
642   unsigned long int vstart = 0;
643   casenumber n_cases = CASENUMBER_MAX;
644   int i;
645   struct var_spec *var_spec = NULL;
646   int n_var_specs = 0;
647
648   struct ods_reader *r = (struct ods_reader *) spreadsheet;
649   xmlChar *val_string = NULL;
650
651   assert (r);
652   r->read_names = opts->read_names;
653   ds_init_empty (&r->ods_errs);
654   ++r->ref_cnt;
655
656   if ( !init_reader (r, true))
657     goto error;
658
659   if (opts->cell_range)
660     {
661       if ( ! convert_cell_ref (opts->cell_range,
662                                &r->start_col, &r->start_row,
663                                &r->stop_col, &r->stop_row))
664         {
665           msg (SE, _("Invalid cell range `%s'"),
666                opts->cell_range);
667           goto error;
668         }
669     }
670   else
671     {
672       r->start_col = 0;
673       r->start_row = 0;
674       r->stop_col = -1;
675       r->stop_row = -1;
676     }
677
678   r->state = STATE_INIT;
679   r->target_sheet_name = xmlStrdup (BAD_CAST opts->sheet_name);
680   r->target_sheet_index = opts->sheet_index;
681   r->row = r->col = 0;
682
683
684   /* Advance to the start of the cells for the target sheet */
685   while ( ! reading_target_sheet (r)  
686           || r->state != STATE_ROW || r->row <= r->start_row )
687     {
688       if (1 != (ret = xmlTextReaderRead (r->xtr)))
689            break;
690
691       process_node (r);
692     }
693
694   if (ret < 1)
695     {
696       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
697            spreadsheet->file_name);
698       goto error;
699     }
700
701   if ( opts->read_names)
702     {
703       while (1 == (ret = xmlTextReaderRead (r->xtr)))
704         {
705           int idx;
706
707           process_node (r);
708
709           /* If the row is finished then stop for now */
710           if (r->state == STATE_TABLE && r->row > r->start_row)
711             break;
712
713           idx = r->col - r->start_col -1 ;
714
715           if ( idx < 0)
716             continue;
717
718           if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
719             continue;
720
721           if (r->state == STATE_CELL_CONTENT 
722               &&
723               XML_READER_TYPE_TEXT  == r->node_type)
724             {
725               xmlChar *value = xmlTextReaderValue (r->xtr);
726
727               if ( idx >= n_var_specs)
728                 {
729                   var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
730
731                   /* xrealloc (unlike realloc) doesn't initialise its memory to 0 */
732                   memset (var_spec + n_var_specs,
733                           0, 
734                           (idx - n_var_specs + 1) * sizeof (*var_spec));
735                   n_var_specs = idx + 1;
736                 }
737               var_spec[idx].firstval.text = 0;
738               var_spec[idx].firstval.value = 0;
739               var_spec[idx].firstval.type = 0;
740
741               var_spec [idx].name = strdup (CHAR_CAST (const char *, value));
742
743               xmlFree (value);
744             }
745         }
746     }
747
748   /* Read in the first row of data */
749   while (1 == xmlTextReaderRead (r->xtr))
750     {
751       int idx;
752       process_node (r);
753
754       if ( ! reading_target_sheet (r) )
755         break;
756
757       /* If the row is finished then stop for now */
758       if (r->state == STATE_TABLE &&
759           r->row > r->start_row + (opts->read_names ? 1 : 0))
760         break;
761
762       idx = r->col - r->start_col - 1;
763       if (idx < 0)
764         continue;
765
766       if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
767         continue;
768
769       if ( r->state == STATE_CELL &&
770            XML_READER_TYPE_ELEMENT  == r->node_type)
771         {
772           type = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value-type"));
773           val_string = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value"));
774         }
775
776       if ( r->state == STATE_CELL_CONTENT &&
777            XML_READER_TYPE_TEXT  == r->node_type)
778         {
779           if (idx >= n_var_specs)
780             {
781               var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
782               memset (var_spec + n_var_specs,
783                       0, 
784                       (idx - n_var_specs + 1) * sizeof (*var_spec));
785
786               var_spec [idx].name = NULL;
787               n_var_specs = idx + 1;
788             }
789
790           var_spec [idx].firstval.type = type;
791           var_spec [idx].firstval.text = xmlTextReaderValue (r->xtr);
792           var_spec [idx].firstval.value = val_string;
793
794           val_string = NULL;
795           type = NULL;
796         }
797     }
798
799
800   /* Create the dictionary and populate it */
801   r->spreadsheet.dict = r->dict = dict_create (
802     CHAR_CAST (const char *, xmlTextReaderConstEncoding (r->xtr)));
803
804   for (i = 0; i < n_var_specs ; ++i )
805     {
806       struct fmt_spec fmt;
807       struct variable *var = NULL;
808       char *name = dict_make_unique_var_name (r->dict, var_spec[i].name, &vstart);
809       int width  = xmv_to_width (&var_spec[i].firstval, opts->asw);
810       dict_create_var (r->dict, name, width);
811       free (name);
812
813       var = dict_get_var (r->dict, i);
814
815       if ( 0 == xmlStrcmp (var_spec[i].firstval.type, _xml("date")))
816         {
817           fmt.type = FMT_DATE;
818           fmt.d = 0;
819           fmt.w = 20;
820         }
821       else
822         fmt = fmt_default_for_width (width);
823
824       var_set_both_formats (var, &fmt);
825     }
826
827   /* Create the first case, and cache it */
828   r->used_first_case = false;
829
830   if ( n_var_specs ==  0 )
831     {
832       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
833            spreadsheet->file_name);
834       goto error;
835     }
836
837   r->proto = caseproto_ref (dict_get_proto (r->dict));
838   r->first_case = case_create (r->proto);
839   case_set_missing (r->first_case);
840
841   for (i = 0 ; i < n_var_specs; ++i)
842     {
843       const struct variable *var = dict_get_var (r->dict, i);
844
845       convert_xml_to_value (r->first_case, var,  &var_spec[i].firstval);
846     }
847
848   /* Read in the first row of data */
849   while (1 == xmlTextReaderRead (r->xtr))
850     {
851       process_node (r);
852
853       if (r->state == STATE_ROW)
854         break;
855     }
856
857
858   for ( i = 0 ; i < n_var_specs ; ++i )
859     {
860       free (var_spec[i].firstval.type);
861       free (var_spec[i].firstval.value);
862       free (var_spec[i].firstval.text);
863       free (var_spec[i].name);
864     }
865
866   free (var_spec);
867
868
869   return casereader_create_sequential
870     (NULL,
871      r->proto,
872      n_cases,
873      &ods_file_casereader_class, r);
874
875  error:
876   
877 #if 0
878   for ( i = 0 ; i < n_var_specs ; ++i )
879     {
880       free (var_spec[i].firstval.type);
881       free (var_spec[i].firstval.value);
882       free (var_spec[i].firstval.text);
883       free (var_spec[i].name);
884     }
885
886   free (var_spec);
887
888   dict_destroy (r->spreadsheet.dict);
889   r->spreadsheet.dict = NULL;
890 #endif
891   ods_file_casereader_destroy (NULL, r);
892
893
894   return NULL;
895 }
896
897
898 /* Reads and returns one case from READER's file.  Returns a null
899    pointer on failure. */
900 static struct ccase *
901 ods_file_casereader_read (struct casereader *reader UNUSED, void *r_)
902 {
903   struct ccase *c = NULL;
904   xmlChar *val_string = NULL;
905   xmlChar *type = NULL;
906   struct ods_reader *r = r_;
907
908   if (!r->used_first_case)
909     {
910       r->used_first_case = true;
911       return r->first_case;
912     }
913
914
915   /* Advance to the start of a row. (If there is one) */
916   while (r->state != STATE_ROW 
917          && 1 == xmlTextReaderRead (r->xtr)
918          )
919     {
920       process_node (r);
921     }
922
923
924   if ( ! reading_target_sheet (r)  
925        ||  r->state < STATE_TABLE
926        ||  (r->stop_row != -1 && r->row > r->stop_row + 1)
927        )
928     {
929       return NULL;
930     }
931
932   c = case_create (r->proto);
933   case_set_missing (c);
934   
935   while (1 == xmlTextReaderRead (r->xtr))
936     {
937       process_node (r);
938
939       if ( r->stop_row != -1 && r->row > r->stop_row + 1)
940         break;
941
942       if (r->state == STATE_CELL &&
943            r->node_type == XML_READER_TYPE_ELEMENT)
944         {
945           type = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value-type"));
946           val_string = xmlTextReaderGetAttribute (r->xtr, _xml ("office:value"));
947         }
948
949       if (r->state == STATE_CELL_CONTENT && 
950            r->node_type == XML_READER_TYPE_TEXT)
951         {
952           int col;
953           struct xml_value *xmv = xzalloc (sizeof *xmv);
954           xmv->text = xmlTextReaderValue (r->xtr);
955           xmv->value = val_string;       
956           xmv->type = type;
957           val_string = NULL;
958
959           for (col = 0; col < r->col_span; ++col)
960             {
961               const struct variable *var;
962               const int idx = r->col - col - r->start_col - 1;
963               if (idx < 0)
964                 continue;
965               if (r->stop_col != -1 && idx > r->stop_col - r->start_col )
966                 break;
967               if (idx >= dict_get_var_cnt (r->dict))
968                 break;
969
970               var = dict_get_var (r->dict, idx);
971               convert_xml_to_value (c, var, xmv);
972             }
973
974           xmlFree (xmv->text);
975           xmlFree (xmv->value);
976           xmlFree (xmv->type);
977           free (xmv);
978         }
979       if ( r->state <= STATE_TABLE)
980         break;
981     }
982
983   return c;
984 }
985 #endif