1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2007, 2009, 2011 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* FIXME: error checking. */
18 /* FIXME: merge pattern should be improved, this one causes a
19 performance regression. */
22 #include "math/merge.h"
24 #include "data/case.h"
25 #include "data/casereader.h"
26 #include "data/casewriter.h"
27 #include "data/subcase.h"
28 #include "libpspp/array.h"
29 #include "libpspp/assertion.h"
30 #include "libpspp/taint.h"
32 #include "gl/xalloc.h"
34 #define MAX_MERGE_ORDER 7
38 struct casereader *reader;
44 struct subcase ordering;
45 struct merge_input inputs[MAX_MERGE_ORDER];
47 struct caseproto *proto;
50 static void do_merge (struct merge *m);
53 merge_create (const struct subcase *ordering, const struct caseproto *proto)
55 struct merge *m = xmalloc (sizeof *m);
56 subcase_clone (&m->ordering, ordering);
58 m->proto = caseproto_ref (proto);
63 merge_destroy (struct merge *m)
69 subcase_destroy (&m->ordering);
70 for (i = 0; i < m->input_cnt; i++)
71 casereader_destroy (m->inputs[i].reader);
72 caseproto_unref (m->proto);
78 merge_append (struct merge *m, struct casereader *r)
80 r = casereader_rename (r);
81 m->inputs[m->input_cnt++].reader = r;
82 if (m->input_cnt >= MAX_MERGE_ORDER)
87 merge_make_reader (struct merge *m)
94 if (m->input_cnt == 1)
96 r = m->inputs[0].reader;
99 else if (m->input_cnt == 0)
101 struct casewriter *writer = mem_writer_create (m->proto);
102 r = casewriter_make_reader (writer);
111 read_input_case (struct merge *m, size_t idx)
113 struct merge_input *i = &m->inputs[idx];
115 i->c = casereader_read (i->reader);
120 casereader_destroy (i->reader);
121 remove_element (m->inputs, m->input_cnt, sizeof *m->inputs, idx);
128 do_merge (struct merge *m)
130 struct casewriter *w;
133 assert (m->input_cnt > 1);
135 w = tmpfile_writer_create (m->proto);
136 for (i = 0; i < m->input_cnt; i++)
137 taint_propagate (casereader_get_taint (m->inputs[i].reader),
138 casewriter_get_taint (w));
140 for (i = 0; i < m->input_cnt; )
141 if (read_input_case (m, i))
143 while (m->input_cnt > 0)
148 for (i = 1; i < m->input_cnt; i++)
149 if (subcase_compare_3way (&m->ordering, m->inputs[i].c,
150 &m->ordering, m->inputs[min].c) < 0)
153 casewriter_write (w, m->inputs[min].c);
154 read_input_case (m, min);
158 m->inputs[0].reader = casewriter_make_reader (w);