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