File: nrrdfile.c

package info (click to toggle)
gwyddion 2.62-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 51,952 kB
  • sloc: ansic: 398,486; python: 7,877; sh: 5,492; makefile: 4,723; xml: 3,883; cpp: 1,969; pascal: 418; perl: 154; ruby: 130
file content (1656 lines) | stat: -rw-r--r-- 54,129 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
/*
 *  $Id: nrrdfile.c 25069 2022-10-05 14:03:46Z yeti-dn $
 *  Copyright (C) 2011-2019 David Necas (Yeti).
 *  E-mail: yeti@gwyddion.net.
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 *  License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
 *  later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 *  details.
 *
 *  You should have received a copy of the GNU General Public License along with this program; if not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/**
 * [FILE-MAGIC-FREEDESKTOP]
 * <mime-type type="application/x-nearly-raw-raster-data">
 *   <comment>Nearly raw raster data (NRRD)</comment>
 *   <magic priority="80">
 *     <match type="string" offset="0" value="NRRD000"/>
 *   </magic>
 *   <glob pattern="*.nrrd"/>
 *   <glob pattern="*.NRRD"/>
 * </mime-type>
 **/

/**
 * [FILE-MAGIC-FILEMAGIC]
 * # Nearly raw raster data
 * # Metaformat, see http://teem.sourceforge.net/nrrd/format.html
 * 0 string NRRD000 Nearly Raw Raster Data
 * >&0 regex [0-9]+ version %s
 * >&0 search/200 data\ file:\x20 text header for
 * >>&0 regex [^\x0d\x0a]+ %s
 **/

/**
 * [FILE-MAGIC-USERGUIDE]
 * Nearly raw raster data (NRRD)
 * .nrrd
 * Read[1] Export[2] Volume
 * [1] Not all variants are implemented.
 * [2] Data are exported in a fixed attached native-endian float point format.
 **/

#include "config.h"
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>

#ifdef HAVE_ZLIB
#include <zlib.h>
#endif

#ifdef HAVE_BZIP2
#include <bzlib.h>
#endif

#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwymath.h>
#include <libgwyddion/gwyutils.h>
#include <libgwymodule/gwymodule-file.h>
#include <libprocess/datafield.h>
#include <app/data-browser.h>
#include <app/gwymoduleutils-file.h>

#include "err.h"
#include "get.h"

#define MAGIC "NRRD000"
#define MAGIC_SIZE (sizeof(MAGIC) - 1)

#define EXTENSION ".nrrd"

typedef enum {
    NRRD_TYPE_UNKNOWN = -1,
    /* Importable types start from 0 */
    NRRD_TYPE_SINT8,
    NRRD_TYPE_UINT8,
    NRRD_TYPE_SINT16,
    NRRD_TYPE_UINT16,
    NRRD_TYPE_SINT32,
    NRRD_TYPE_UINT32,
    NRRD_TYPE_SINT64,
    NRRD_TYPE_UINT64,
    NRRD_TYPE_FLOAT,
    NRRD_TYPE_DOUBLE,
    /* Non-importable types */
    NRRD_TYPE_BLOCK,
} NRRDDataType;

typedef enum {
    NRRD_ENCODING_UNKNOWN = -1,
    NRRD_ENCODING_RAW,
    NRRD_ENCODING_TEXT,
    NRRD_ENCODING_HEX,
    NRRD_ENCODING_GZIP,
    NRRD_ENCODING_BZIP2,
} NRRDEncoding;

static gboolean      module_register     (void);
static gint          nrrdfile_detect     (const GwyFileDetectInfo *fileinfo,
                                          gboolean only_name);
static GwyContainer* nrrdfile_load       (const gchar *filename,
                                          GwyRunType mode,
                                          GError **error);
static gboolean      nrrdfile_export     (GwyContainer *data,
                                          const gchar *filename,
                                          GwyRunType mode,
                                          GError **error);
static void          normalise_field_name(gchar *name);
static void          unescape_field_value(gchar *value);
static NRRDDataType  parse_data_type     (const gchar *value);
static NRRDEncoding  parse_encoding      (const gchar *value);
static gboolean      find_gwy_data_type  (NRRDDataType datatype,
                                          NRRDEncoding encoding,
                                          const gchar *endian,
                                          GwyRawDataType *rawdatatype,
                                          GwyByteOrder *byteorder,
                                          GError **error);
static guchar*       load_detached_file  (const gchar *datafile,
                                          gsize *size,
                                          gboolean gzcompressed,
                                          gboolean bz2compressed,
                                          GError **error);
static guint         pick_channel_axis   (guint dimension,
                                          const guint *sizes,
                                          gchar **kinds);
static gconstpointer get_raw_data_pointer(gconstpointer base,
                                          gsize *size,
                                          gsize nitems,
                                          GwyRawDataType datatype,
                                          GwyByteOrder *byteorder,
                                          NRRDEncoding encoding,
                                          gssize lineskip,
                                          gssize byteskip,
                                          GSList **buffers_to_free,
                                          GError **error);
static GwyDataField* read_raw_data_field (guint xres,
                                          guint yres,
                                          gint stride,
                                          guint rowstride,
                                          GwyRawDataType rawdatatype,
                                          GwyByteOrder byteorder,
                                          GHashTable *fields,
                                          const guchar *data);
static GwyBrick*     read_raw_brick      (guint xres,
                                          guint yres,
                                          guint zres,
                                          GwyRawDataType rawdatatype,
                                          GwyByteOrder byteorder,
                                          GHashTable *fields,
                                          const guchar *data);
static GwyContainer* nrrd_make_meta      (GHashTable *keyvalue);
static gboolean      parse_uint_vector   (const gchar *value,
                                          guint n,
                                          ...);
static gboolean      parse_float_vector  (const gchar *value,
                                          guint n,
                                          ...);
static gboolean      parse_string_vector (const gchar *value,
                                          guint n,
                                          ...);
static gchar**       split_per_axis_field(const gchar *value,
                                          const gchar *name,
                                          guint nitems,
                                          gboolean quoted,
                                          GError **error);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Imports and exports nearly raw raster data (NRRD) files."),
    "Yeti <yeti@gwyddion.net>",
    "0.9",
    "David Nečas (Yeti)",
    "2011",
};

GWY_MODULE_QUERY(module_info)

static gboolean
module_register(void)
{
    gwy_file_func_register("nrrdfile",
                           N_("Nearly raw raster data (NRRD) files (.nrrd)"),
                           (GwyFileDetectFunc)&nrrdfile_detect,
                           (GwyFileLoadFunc)&nrrdfile_load,
                           NULL,
                           (GwyFileSaveFunc)&nrrdfile_export);

    return TRUE;
}

static gint
nrrdfile_detect(const GwyFileDetectInfo *fileinfo,
                gboolean only_name)
{
    if (only_name)
        return g_str_has_suffix(fileinfo->name_lowercase, EXTENSION) ? 20 : 0;

    // Weed out files that do not pretend to be Windows bitmaps quickly.
    if (fileinfo->buffer_len >= MAGIC_SIZE + 3
        && memcmp(fileinfo->head, MAGIC, MAGIC_SIZE) == 0
        && g_ascii_isdigit(fileinfo->head[MAGIC_SIZE])
        && (fileinfo->head[MAGIC_SIZE+1] == '\n'
            || (fileinfo->head[MAGIC_SIZE+1] == '\r' && fileinfo->head[MAGIC_SIZE+2] == '\n')))
        return 100;

    return 0;
}

static inline gboolean
nrrd_encoding_is_compressed(NRRDEncoding encoding)
{
    return encoding == NRRD_ENCODING_GZIP || encoding == NRRD_ENCODING_BZIP2;
}

static GwyContainer*
nrrdfile_load(const gchar *filename,
              G_GNUC_UNUSED GwyRunType mode,
              GError **error)
{
    GwyContainer *meta = NULL, *container = NULL;
    GHashTable *hash, *fields = NULL, *keyvalue = NULL;
    GwyDataField *dfield = NULL;
    GSList *l, *buffers_to_free = NULL;
    guchar *buffer = NULL, *data_buffer = NULL, *header_end;
    const guchar *data_start;
    gsize data_size, size = 0;
    GError *err = NULL;
    guint sizes[3] = { 1, 1, 1 };
    G_GNUC_UNUSED guint version;
    guint dimension, xres = 0, yres = 0, zres = 0, nchannels = 0, stride = 0, rowstride = 0, fieldstride = 0,
          chanaxis, xaxis, yaxis, header_size, i;
    gchar *value, *vkeyvalue, *vfield, *p, *line, *datafile = NULL;
    gchar **kinds = NULL;
    gboolean unix_eol, detached_header = FALSE;
    guchar first_byte = 0;
    gssize byteskip = 0, lineskip = 0;
    NRRDDataType data_type;
    NRRDEncoding encoding;
    GwyRawDataType rawdatatype;
    GwyByteOrder byteorder;

    if (!g_file_get_contents(filename, (gchar**)&buffer, &size, &err)) {
        err_GET_FILE_CONTENTS(error, &err);
        return NULL;
    }
    buffers_to_free = g_slist_append(buffers_to_free, buffer);

    if (size < MAGIC_SIZE + 3) {
        err_TOO_SHORT(error);
        goto fail;
    }
    if (memcmp(buffer, MAGIC, MAGIC_SIZE) != 0
        || !g_ascii_isdigit(buffer[MAGIC_SIZE])
        || (buffer[MAGIC_SIZE+1] != '\n' && (buffer[MAGIC_SIZE+1] != '\r' || buffer[MAGIC_SIZE+2] != '\n'))) {
        err_FILE_TYPE(error, "NRRD");
        goto fail;
    }

    version = buffer[MAGIC_SIZE] - '0';
    unix_eol = (buffer[MAGIC_SIZE+1] == '\n');
    header_end = gwy_memmem(buffer, size, unix_eol ? "\n\n" : "\r\n\r\n", unix_eol ? 2 : 4);
    if (header_end) {
        header_size = header_end - buffer + (unix_eol ? 2 : 4);
        first_byte = buffer[header_size];
        buffer[header_size] = '\0';
    }
    else {
        header_size = size;
        detached_header = TRUE;
    }

    fields = g_hash_table_new(g_str_hash, g_str_equal);
    keyvalue = g_hash_table_new(g_str_hash, g_str_equal);
    p = buffer + (MAGIC_SIZE + 2 + !unix_eol);
    for (line = gwy_str_next_line(&p); line; line = gwy_str_next_line(&p)) {
        g_strstrip(line);
        if (!line[0])
            break;
        if (line[0] == '#')
            continue;

        /* Fields and key-values are almost the same for us.  But do not put them to one hash table as we do not want
         * key-values to override fields. */
        vfield = strstr(line, ": ");
        vkeyvalue = strstr(line, ":=");
        if (vfield) {
            hash = (vkeyvalue && vkeyvalue < vfield) ? keyvalue : fields;
            value = (vkeyvalue && vkeyvalue < vfield) ? vkeyvalue : vfield;
        }
        else {
            hash = vkeyvalue ? keyvalue : NULL;
            value = vkeyvalue ? vkeyvalue : NULL;
        }
        if (!hash) {
            g_warning("Neither field nor key-value separator found on line: %s", line);
            continue;
        }

        *value = '\0';
        value += 2;
        g_strchomp(line);
        g_strchug(value);
        if (hash == fields)
            normalise_field_name(line);
        unescape_field_value(value);
        gwy_debug("<%s> = <%s> (%s)", line, value, hash == fields ? "F" : "KV");
        g_hash_table_insert(hash, line, value);
    }
    if (!detached_header)
        buffer[header_size] = first_byte;

    datafile = g_hash_table_lookup(fields, "datafile");
    if (detached_header && !datafile) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Detached header does not refer to any data file."));
        goto fail;
    }

    if (!require_keys(fields, error, "dimension", "encoding", "sizes", "type", NULL))
        goto fail;

    if ((data_type = parse_data_type(g_hash_table_lookup(fields, "type"))) == (NRRDDataType)-1) {
        err_UNSUPPORTED(error, "type");
        goto fail;
    }
    if ((encoding = parse_encoding(g_hash_table_lookup(fields, "encoding"))) == (NRRDEncoding)-1) {
        err_UNSUPPORTED(error, "encoding");
        goto fail;
    }
    gwy_debug("data_type: %u, encoding: %u", data_type, encoding);

    /* TODO: Read 1D data as a graph. */
    if (sscanf(g_hash_table_lookup(fields, "dimension"), "%u", &dimension) != 1) {
        err_INVALID(error, "dimension");
        goto fail;
    }
    if (dimension != 2 && dimension != 3) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Only two- and three-dimensional data are supported."));
        goto fail;
    }
    if (!parse_uint_vector(g_hash_table_lookup(fields, "sizes"), dimension, &sizes[0], &sizes[1], &sizes[2])) {
        err_INVALID(error, "sizes");
        goto fail;
    }
    gwy_debug("sizes: %u, %u, %u", sizes[0], sizes[1], sizes[2]);
    if (err_DIMENSION(error, sizes[0])
        || err_DIMENSION(error, sizes[1])
        || (dimension == 3 && err_DIMENSION(error, sizes[2])))
        goto fail;

    if ((value = g_hash_table_lookup(fields, "lineskip")))
        lineskip = atol(value);
    if ((value = g_hash_table_lookup(fields, "byteskip")))
        byteskip = atol(value);

    if (lineskip && nrrd_encoding_is_compressed(encoding)) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Non-zero lineskip is supported only for uncompressed files."));
        goto fail;
    }

    if (!find_gwy_data_type(data_type, encoding, g_hash_table_lookup(fields, "endian"),
                            &rawdatatype, &byteorder, error))
        goto fail;

    if ((value = g_hash_table_lookup(fields, "kinds")))
        kinds = split_per_axis_field(value, "kinds", dimension, TRUE, NULL);

    if (datafile) {
        gchar *datafilepath;

        if (g_path_is_absolute(datafile))
            datafilepath = g_strdup(datafile);
        else {
            gchar *dirname = g_path_get_dirname(filename);
            datafilepath = g_build_filename(dirname, datafile, NULL);
            g_free(dirname);
        }

        data_buffer = load_detached_file(datafilepath, &data_size,
                                         encoding == NRRD_ENCODING_GZIP, encoding == NRRD_ENCODING_BZIP2,
                                         error);
        g_free(datafilepath);
        if (!data_buffer)
            goto fail;

        buffers_to_free = g_slist_append(buffers_to_free, data_buffer);
        if (nrrd_encoding_is_compressed(encoding))
            encoding = NRRD_ENCODING_RAW;
    }
    else {
        if (nrrd_encoding_is_compressed(encoding)) {
            g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                        _("Compression is supported only for detached files."));
            goto fail;
        }
        data_buffer = buffer + header_size;
        data_size = size - header_size;
    }

    chanaxis = pick_channel_axis(dimension, sizes, kinds);
    if (chanaxis == G_MAXUINT) {
        gwy_debug("after much deliberation, we decided it's volume data");
        xres = sizes[0];
        yres = sizes[1];
        zres = sizes[2];
    }
    else {
        gwy_debug("we picked %u as the channel axis", chanaxis);
        nchannels = sizes[chanaxis];
        if (chanaxis == 0) {
            xaxis = 1;
            yaxis = 2;
            stride = nchannels;
            rowstride = nchannels*sizes[xaxis];
            fieldstride = 1;
        }
        else if (chanaxis == 1) {
            xaxis = 0;
            yaxis = 2;
            stride = 1;
            rowstride = nchannels*sizes[xaxis];
            fieldstride = sizes[xaxis];
        }
        else if (chanaxis == 2) {
            xaxis = 0;
            yaxis = 1;
            stride = 1;
            rowstride = sizes[xaxis];
            fieldstride = sizes[xaxis]*sizes[yaxis];
        }
        else {
            g_assert_not_reached();
        }
        xres = sizes[xaxis];
        yres = sizes[yaxis];
        gwy_debug("xres: %u, yres: %u, nchannels: %u", xres, yres, nchannels);
        gwy_debug("stride: %u, rowstride: %u, fieldstride: %u", stride, rowstride, fieldstride);
    }

    if (!(data_start = get_raw_data_pointer(data_buffer, &data_size, sizes[0]*sizes[1]*sizes[2],
                                            rawdatatype, &byteorder, encoding, lineskip, byteskip,
                                            &buffers_to_free, error)))
        goto fail;

    container = gwy_container_new();
    meta = nrrd_make_meta(keyvalue);

    if (chanaxis == G_MAXUINT) {
        GwyBrick *brick = read_raw_brick(xres, yres, zres, rawdatatype, byteorder, fields, data_start);

        gwy_container_set_object(container, gwy_app_get_brick_key_for_id(0), brick);
        g_object_unref(brick);

        if ((value = g_hash_table_lookup(fields, "content")))
            gwy_container_set_const_string(container, gwy_app_get_brick_title_key_for_id(0), value);
        if (meta)
            gwy_container_set_object(container, gwy_app_get_brick_meta_key_for_id(0), meta);
    }
    else {
        for (i = 0; i < nchannels; i++) {
            const guchar *chandata = data_start + i*fieldstride*gwy_raw_data_size(rawdatatype);

            dfield = read_raw_data_field(xres, yres, stride, rowstride, rawdatatype, byteorder, fields, chandata);
            gwy_container_set_object(container, gwy_app_get_data_key_for_id(i), dfield);
            g_object_unref(dfield);

            if ((value = g_hash_table_lookup(fields, "content")))
                gwy_container_set_string(container, gwy_app_get_data_title_key_for_id(i), g_strdup(value));
            if (meta) {
                GwyContainer *chanmeta = gwy_container_duplicate(meta);

                gwy_container_set_object(container, gwy_app_get_data_meta_key_for_id(i), chanmeta);
                g_object_unref(chanmeta);
            }
            gwy_file_channel_import_log_add(container, i, NULL, filename);
        }
    }

fail:
    GWY_OBJECT_UNREF(meta);
    for (l = buffers_to_free; l; l = g_slist_next(l))
        g_free(l->data);
    g_slist_free(buffers_to_free);
    g_strfreev(kinds);
    if (fields)
        g_hash_table_destroy(fields);
    if (keyvalue)
        g_hash_table_destroy(keyvalue);

    return container;
}

static void
normalise_field_name(gchar *name)
{
    guint i, j;

    /* Get rid of non-alnum characters, e.g. "sample units" → "sampleunits" and convert alphabetic characters to
     * lowercase. */
    for (i = j = 0; name[i]; i++) {
        if (g_ascii_isalnum(name[i])) {
            name[j++] = g_ascii_tolower(name[i]);
        }
    }
    name[j] = '\0';

    if (gwy_strequal(name, "centerings"))
        strcpy(name, "centers");
}

static void
unescape_field_value(gchar *value)
{
    guint i, j;

    if (!strchr(value, '\\'))
        return;

    for (i = j = 0; value[i]; i++, j++) {
        if (value[i] == '\\') {
            if (value[i+1] == '\\') {
                value[j] = '\\';
                i++;
            }
            else if (value[i+1] == 'n') {
                value[j] = '\n';
                i++;
            }
            else {
                g_warning("Undefined escape sequence \\%c found.", value[i+1]);
            }
        }
        value[j] = value[i];
    }
    value[j] = '\0';
}

static NRRDDataType
parse_data_type(const gchar *value)
{
    GwyEnum data_types[] = {
        { "signed char",            NRRD_TYPE_SINT8,  },
        { "int8",                   NRRD_TYPE_SINT8,  },
        { "int8_t",                 NRRD_TYPE_SINT8,  },
        { "unsigned char",          NRRD_TYPE_UINT8,  },
        { "uchar",                  NRRD_TYPE_UINT8,  },
        { "uint8",                  NRRD_TYPE_UINT8,  },
        { "uint8_t",                NRRD_TYPE_UINT8,  },
        { "short",                  NRRD_TYPE_SINT16, },
        { "short int",              NRRD_TYPE_SINT16, },
        { "signed short",           NRRD_TYPE_SINT16, },
        { "signed short int",       NRRD_TYPE_SINT16, },
        { "int16",                  NRRD_TYPE_SINT16, },
        { "int16_t",                NRRD_TYPE_SINT16, },
        { "ushort",                 NRRD_TYPE_UINT16, },
        { "unsigned short",         NRRD_TYPE_UINT16, },
        { "unsigned short int",     NRRD_TYPE_UINT16, },
        { "uint16",                 NRRD_TYPE_UINT16, },
        { "uint16_t",               NRRD_TYPE_UINT16, },
        { "int",                    NRRD_TYPE_SINT32, },
        { "signed int",             NRRD_TYPE_SINT32, },
        { "int32",                  NRRD_TYPE_SINT32, },
        { "int32_t",                NRRD_TYPE_SINT32, },
        { "uint",                   NRRD_TYPE_UINT32, },
        { "unsigned int",           NRRD_TYPE_UINT32, },
        { "uint32",                 NRRD_TYPE_UINT32, },
        { "uint32_t",               NRRD_TYPE_UINT32, },
        { "longlong",               NRRD_TYPE_SINT64, },
        { "long long",              NRRD_TYPE_SINT64, },
        { "long long int",          NRRD_TYPE_SINT64, },
        { "signed long long",       NRRD_TYPE_SINT64, },
        { "signed long long int",   NRRD_TYPE_SINT64, },
        { "int64",                  NRRD_TYPE_SINT64, },
        { "int64_t",                NRRD_TYPE_SINT64, },
        { "ulonglong",              NRRD_TYPE_UINT64, },
        { "unsigned long long",     NRRD_TYPE_UINT64, },
        { "unsigned long long int", NRRD_TYPE_UINT64, },
        { "uint64",                 NRRD_TYPE_UINT64, },
        { "uint64_t",               NRRD_TYPE_UINT64, },
        { "float",                  NRRD_TYPE_FLOAT,  },
        { "double",                 NRRD_TYPE_DOUBLE, },
        { "block",                  NRRD_TYPE_BLOCK,  },
    };

    gchar *s;
    NRRDDataType data_type;

    if (!value)
        return NRRD_TYPE_UNKNOWN;

    s = g_ascii_strdown(value, -1);
    data_type = gwy_string_to_enum(s, data_types, G_N_ELEMENTS(data_types));
    g_free(s);

    return data_type;
}

static NRRDEncoding
parse_encoding(const gchar *value)
{
    GwyEnum encodings[] = {
        { "raw",   NRRD_ENCODING_RAW,   },
        { "text",  NRRD_ENCODING_TEXT,  },
        { "txt",   NRRD_ENCODING_TEXT,  },
        { "ascii", NRRD_ENCODING_TEXT,  },
        { "hex",   NRRD_ENCODING_HEX,   },
        { "gzip",  NRRD_ENCODING_GZIP,  },
        { "gz",    NRRD_ENCODING_GZIP,  },
        { "bzip2", NRRD_ENCODING_BZIP2, },
        { "bz2",   NRRD_ENCODING_BZIP2, },
    };

    NRRDEncoding encoding;
    gchar *s;

    if (!value)
        return NRRD_ENCODING_UNKNOWN;

    s = g_ascii_strdown(value, -1);
    encoding = gwy_string_to_enum(s, encodings, G_N_ELEMENTS(encodings));
    g_free(s);

    return encoding;
}

static gboolean
find_gwy_data_type(NRRDDataType datatype, NRRDEncoding encoding,
                   const gchar *endian,
                   GwyRawDataType *rawdatatype, GwyByteOrder *byteorder,
                   GError **error)
{
    static const GwyRawDataType types[] = {
        GWY_RAW_DATA_SINT8,
        GWY_RAW_DATA_UINT8,
        GWY_RAW_DATA_SINT16,
        GWY_RAW_DATA_UINT16,
        GWY_RAW_DATA_SINT32,
        GWY_RAW_DATA_UINT32,
        GWY_RAW_DATA_SINT64,
        GWY_RAW_DATA_UINT64,
        GWY_RAW_DATA_FLOAT,
        GWY_RAW_DATA_DOUBLE,
    };

    if (datatype > NRRD_TYPE_DOUBLE) {
        err_UNSUPPORTED(error, "type");
        return FALSE;
    }

    *rawdatatype = types[datatype];
    *byteorder = GWY_BYTE_ORDER_NATIVE;
    if (encoding != NRRD_ENCODING_TEXT && gwy_raw_data_size(*rawdatatype) > 1) {
        if (!endian) {
            err_MISSING_FIELD(error, "endian");
            return FALSE;
        }

        if (g_ascii_strcasecmp(endian, "little") == 0)
            *byteorder = GWY_BYTE_ORDER_LITTLE_ENDIAN;
        else if (g_ascii_strcasecmp(endian, "big") == 0)
            *byteorder = GWY_BYTE_ORDER_BIG_ENDIAN;
        else {
            err_INVALID(error, "endian");
            return FALSE;
        }
    }

    return TRUE;
}

/* TODO: Someday we may read split files here. */
/* XXX: Numbered split files (with a printf-like format) are a risk. */
static guchar*
load_detached_file(const gchar *datafile,
                   gsize *size,
                   gboolean gzcompressed,
                   gboolean bz2compressed,
                   GError **error)
{
    GError *err = NULL;
    gchar *buffer = NULL;

    gwy_debug("Loading detached <%s>", datafile);
    if (datafile) {
        if (strchr(datafile, ' ') || gwy_strequal(datafile, "LIST")) {
            g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                        _("Split detached data files are not supported."));
            return NULL;
        }
    }

    if (gzcompressed) {
#ifdef HAVE_ZLIB
        gzFile cfile = gzopen(datafile, "rb");
        gsize prevsize, toread;
        gssize readbytes;

        if (!cfile) {
            err_OPEN_READ(error);
            return NULL;
        }

        *size = 0;
        do {
            prevsize = *size;
            *size = MAX(2*prevsize, 4096);
            buffer = g_realloc(buffer, *size);
            toread = *size - prevsize;
        } while ((readbytes = gzread(cfile, buffer + prevsize, toread)) == toread);

        if (readbytes < 0) {
            gint errcode;
            const gchar *message = gzerror(cfile, &errcode);

            if (errcode == Z_ERRNO)
                err_READ(error);
            else {
                g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                            _("Cannot read from file: %s."), message);
            }
            gzclose(cfile);
            g_free(buffer);
            return NULL;
        }

        gzclose(cfile);
        *size = prevsize + readbytes;
        gwy_debug("decompressed size: %lu", (gulong)*size);
#else
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_SPECIFIC,
                    _("Cannot decompress gzip-encoded data.  Zlib support was not built in."));
#endif
    }
    else if (bz2compressed) {
#ifdef HAVE_BZIP2
        BZFILE *cfile = BZ2_bzopen(datafile, "rb");
        gsize prevsize, toread;
        gssize readbytes;

        if (!cfile) {
            err_OPEN_READ(error);
            return NULL;
        }

        *size = 0;
        do {
            prevsize = *size;
            *size = MAX(2*prevsize, 4096);
            buffer = g_realloc(buffer, *size);
            toread = *size - prevsize;
        } while ((readbytes = BZ2_bzread(cfile, buffer + prevsize, toread)) == toread);

        if (readbytes < 0) {
            gint errcode;
            const gchar *message = BZ2_bzerror(cfile, &errcode);

            if (errcode == BZ_IO_ERROR)  /* XXX: Is this right? */
                err_READ(error);
            else {
                g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                            _("Cannot read from file: %s."), message);
            }
            BZ2_bzclose(cfile);
            g_free(buffer);
            return NULL;
        }

        BZ2_bzclose(cfile);
        *size = prevsize + readbytes;
        gwy_debug("decompressed size: %lu", (gulong)*size);
#else
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_SPECIFIC,
                    _("Cannot decompress bzip2-encoded data.  Bzip2 support was not built in."));
#endif
    }
    else {
        if (!g_file_get_contents(datafile, &buffer, size, &err)) {
            err_GET_FILE_CONTENTS(error, &err);
            return NULL;
        }
        gwy_debug("file size: %lu", (gulong)*size);
    }

    return buffer;
}

static guint
pick_channel_axis(guint dimension,
                  const guint *sizes,
                  gchar **kinds)
{
    guint xdomain = TRUE, ydomain = TRUE, zdomain = TRUE;
    guint m;

    if (dimension == 2)
        return 2;

    g_return_val_if_fail(dimension == 3, 0);

    if (kinds) {
        normalise_field_name(kinds[0]);
        xdomain = gwy_stramong(kinds[0], "domain", "space", "time", NULL);

        normalise_field_name(kinds[1]);
        ydomain = gwy_stramong(kinds[1], "domain", "space", "time", NULL);

        normalise_field_name(kinds[2]);
        zdomain = gwy_stramong(kinds[2], "domain", "space", "time", NULL);
    }

    /* Pick the axis in which the size 1, preferrably of non-domain kind and
     * first or last. */
    if (sizes[2] == 1 && !zdomain)
        return 2;
    if (sizes[0] == 1 && !xdomain)
        return 0;
    if (sizes[1] == 1 && !ydomain)
        return 0;
    if (xdomain && ydomain && !zdomain)
        return 2;
    if (!xdomain && ydomain && zdomain)
        return 0;
    if (xdomain && !ydomain && zdomain)
        return 1;
    if (sizes[2] == 1)
        return 2;
    if (sizes[0] == 1)
        return 0;
    if (sizes[1] == 1)
        return 0;

    /* If that fails try the axis much smaller than the other two. */
    if (sizes[2] <= (m = MIN(sizes[0], sizes[1]))) {
        if (sizes[2] < 5 || sizes[2]*sizes[2] < m)
            return 2;
    }
    if (sizes[0] <= (m = MIN(sizes[1], sizes[2]))) {
        if (sizes[0] < 5 || sizes[0]*sizes[0] < m)
            return 0;
    }
    if (sizes[1] <= (m = MIN(sizes[0], sizes[2]))) {
        if (sizes[1] < 5 || sizes[1]*sizes[1] < m)
            return 1;
    }

    /* Import as volume data */
    return G_MAXUINT;
}

static guchar*
decode_hex(const guchar *encoded,
           gsize nitems,
           GwyRawDataType rawdatatype,
           gsize *decsize,
           GError **error)
{
    static const gint16 hex[] = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
         0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    };

    gsize dsize = gwy_raw_data_size(rawdatatype)*nitems;
    guchar *decoded = g_new(guchar, dsize);
    const guchar *p = encoded;
    gsize i;

    for (i = nitems; i; i--, decoded++) {
        gint hi, lo;

        do {
            p++;
        } while (*p && (hi = hex[*p]) == -1);
        if (!*p)
            goto fail;

        do {
            p++;
        } while (*p && (lo = hex[*p]) == -1);
        if (!*p)
            goto fail;

        *decoded = hi*16 + lo;
    }

    *decsize = dsize;
    return decoded;

fail:
    g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                _("Hex data contain fewer values (%u) than corresponds to the sizes (%u)."),
                (guint)(nitems-i), (guint)nitems);

    g_free(decoded);
    return NULL;
}

/* Handle also ASCII encoding as another representation of raw encoding to unify all encodings. */
static guchar*
decode_text(const gchar *encoded,
            gsize nitems,
            GwyRawDataType rawdatatype,
            gsize *decsize,
            GError **error)
{
    gsize dsize = gwy_raw_data_size(rawdatatype)*nitems;
    guchar *decoded = g_new(guchar, dsize);
    const gchar *p = encoded;
    gchar *end;
    gsize i;

    if (rawdatatype == GWY_RAW_DATA_SINT8) {
        gint8 *s8 = (gint8*)decoded;
        for (i = nitems; i; i--, s8++) {
            *s8 = (gint8)g_ascii_strtoll(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_UINT8) {
        guint8 *u8 = (guint8*)decoded;
        for (i = nitems; i; i--, u8++) {
            *u8 = (guint8)g_ascii_strtoull(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_SINT16) {
        gint16 *s16 = (gint16*)decoded;
        for (i = nitems; i; i--, s16++) {
            *s16 = (gint16)g_ascii_strtoll(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_UINT16) {
        guint16 *u16 = (guint16*)decoded;
        for (i = nitems; i; i--, u16++) {
            *u16 = (guint16)g_ascii_strtoull(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_SINT32) {
        gint32 *s32 = (gint32*)decoded;
        for (i = nitems; i; i--, s32++) {
            *s32 = (gint32)g_ascii_strtoll(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_UINT32) {
        guint32 *u32 = (guint32*)decoded;
        for (i = nitems; i; i--, u32++) {
            *u32 = (guint32)g_ascii_strtoull(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_SINT64) {
        gint64 *s64 = (gint64*)decoded;
        for (i = nitems; i; i--, s64++) {
            *s64 = g_ascii_strtoll(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_UINT64) {
        guint64 *u64 = (guint64*)decoded;
        for (i = nitems; i; i--, u64++) {
            *u64 = g_ascii_strtoull(p, &end, 10);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_FLOAT) {
        gfloat *f32 = (gfloat*)decoded;
        for (i = nitems; i; i--, f32++) {
            *f32 = (gfloat)g_ascii_strtod(p, &end);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else if (rawdatatype == GWY_RAW_DATA_DOUBLE) {
        gdouble *d64 = (gdouble*)decoded;
        for (i = nitems; i; i--, d64++) {
            *d64 = g_ascii_strtod(p, &end);
            if (end == p)
                goto fail;
            p = end;
        }
    }
    else {
        g_return_val_if_reached(NULL);
    }

    *decsize = dsize;
    return decoded;

fail:
    if (!*p) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Text data contain fewer values (%u) than corresponds to the sizes (%u)."),
                    (guint)(nitems-i), (guint)nitems);
    }
    else {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Garbage after data sample #%u."),
                    (guint)(nitems-i));
    }

    g_free(decoded);
    return NULL;
}

/*
 * The sequence of actions must be:
 * 1. line skipping
 * 2. decompression (decoding)
 * 3. byte skipping
 *
 * However, we treat text and hex as decoding steps.  On the other hand, the format uses actual gzip-compressed data,
 * not just zlib-deflated and to use gzopen() we need the compressed data as a detached file.  Fortunately, this seems
 * to be the common case.
 */
static gconstpointer
get_raw_data_pointer(gconstpointer base,
                     gsize *size,
                     gsize nitems,
                     GwyRawDataType rawdatatype,
                     GwyByteOrder *byteorder,
                     NRRDEncoding encoding,
                     gssize lineskip,
                     gssize byteskip,
                     GSList **buffers_to_free,
                     GError **error)
{
    gsize expected_size;
    gboolean binary = TRUE;
    gssize i;

    if (byteskip < -1) {
        err_INVALID(error, "byteskip");
        return NULL;
    }
    /* Do not bother skipping lines at the begining if we look from the end. */
    if (byteskip == -1)
        lineskip = 0;

    if (lineskip < 0) {
        err_INVALID(error, "lineskip");
        return NULL;
    }

    if (byteskip == -1 && (encoding == NRRD_ENCODING_TEXT || encoding == NRRD_ENCODING_HEX)) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Field byteskip cannot be -1 for text encodings."));
        return NULL;
    }

    /* Line skipping */
    for (i = 0; i < lineskip; i++) {
        const guchar *p = memchr(base, '\n', *size);

        if (!p) {
            g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                        _("Field lineskip specifies more lines than there are in the file."));
            return NULL;
        }
        p++;
        *size -= p - (const guchar*)base;
        base = p;
    }

    /* Decompression */
    if (encoding == NRRD_ENCODING_RAW) {
        /* Nothing to do. */
    }
    else if (encoding == NRRD_ENCODING_TEXT || encoding == NRRD_ENCODING_HEX) {
        /* Decoded later. */
        binary = FALSE;
    }
    else {
        err_UNSUPPORTED(error, "encoding");
        return NULL;
    }

    /* Byte skipping and final size validation for binary formats. */
    if (byteskip <= 0)
        expected_size = gwy_raw_data_size(rawdatatype)*nitems;
    else
        expected_size = gwy_raw_data_size(rawdatatype)*nitems + byteskip;

    if (binary) {
        if (err_SIZE_MISMATCH(error, expected_size, *size, FALSE))
            return NULL;

        if (byteskip == -1)
            return (gconstpointer)((const gchar*)base + *size - expected_size);
        else
            return (gconstpointer)((const gchar*)base + byteskip);
    }

    /* Decoding for text formats. */
    g_assert(byteskip >= 0);   /* This must hold if we got here. */
    if (byteskip > *size) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Field byteskip specifies more bytes than there are in the file."));
        return NULL;
    }
    base = (gconstpointer)((const gchar*)base + byteskip);
    *size -= byteskip;

    /* Buffers are always nul-terminated, passing the encoded size is not necessary. */
    if (encoding == NRRD_ENCODING_HEX)
        base = decode_hex(base, nitems, rawdatatype, size, error);
    else if (encoding == NRRD_ENCODING_TEXT) {
        /* Text data are always created (‘decoded’) in the native byte order. */
        base = decode_text(base, nitems, rawdatatype, size, error);
        *byteorder = GWY_BYTE_ORDER_NATIVE;
    }
    else {
        g_assert_not_reached();
    }

    if (base)
        *buffers_to_free = g_slist_append(*buffers_to_free, (gpointer)base);

    return base;
}

static GwyDataField*
read_raw_data_field(guint xres, guint yres,
                    gint stride, guint rowstride,
                    GwyRawDataType rawdatatype, GwyByteOrder byteorder,
                    GHashTable *fields,
                    const guchar *data)
{
    GwyDataField *dfield;
    GwySIUnit *siunitz = NULL, *siunitxy = NULL;
    gdouble dx = 1.0, dy = 1.0, q = 1.0, z0 = 0.0, xoff = 0.0, yoff = 0.0;
    gdouble *d;
    gint power10;
    gchar *value;
    guint i;

    if ((value = g_hash_table_lookup(fields, "oldmin")))
        z0 = g_ascii_strtod(value, NULL);

    if ((value = g_hash_table_lookup(fields, "oldmax")))
        q = g_ascii_strtod(value, NULL) - z0;

    /* FIXME: This is probably wrong if dimensions == 3 && chanaxis != 2. */
    if ((value = g_hash_table_lookup(fields, "spacings"))
        && parse_float_vector(value, 2, &dx, &dy)) {
        if (!((dx = fabs(dx)) > 0)) {
            g_warning("Real x step is 0.0, fixing to 1.0");
            dx = 1.0;
        }
        if (!((dy = fabs(dy)) > 0)) {
            g_warning("Real y step is 0.0, fixing to 1.0");
            dy = 1.0;
        }
    }

    /* FIXME: This is probably wrong if dimensions == 3 && chanaxis != 2. */
    if ((value = g_hash_table_lookup(fields, "axismins")))
        parse_float_vector(value, 2, &xoff, &yoff);

    /* Prefer axismaxs if both spacings and axismaxs are given. */
    /* FIXME: This is probably wrong if dimensions == 3 && chanaxis != 2. */
    if ((value = g_hash_table_lookup(fields, "axismaxs"))
        && parse_float_vector(value, 2, &dx, &dy)) {
        dx = (dx - xoff)/xres;
        dy = (dy - xoff)/xres;
        if (!((dx = fabs(dx)) > 0)) {
            g_warning("Real x step is 0.0, fixing to 1.0");
            dx = 1.0;
        }
        if (!((dy = fabs(dy)) > 0)) {
            g_warning("Real y step is 0.0, fixing to 1.0");
            dy = 1.0;
        }
    }

    if ((value = g_hash_table_lookup(fields, "sampleunits"))) {
        gchar *unitz;
        if (parse_string_vector(value, 1, &unitz)) {
            siunitz = gwy_si_unit_new_parse(unitz, &power10);
            q *= pow10(power10);
            z0 *= pow10(power10);
            g_free(unitz);
        }
    }

    if ((value = g_hash_table_lookup(fields, "units"))) {
        gchar *unitx, *unity;
        if (parse_string_vector(value, 2, &unitx, &unity)) {
            if (!gwy_strequal(unitx, unity))
                g_warning("X and Y units differ, using X");
            siunitxy = gwy_si_unit_new_parse(unitx, &power10);
            dx *= pow10(power10);
            dy *= pow10(power10);
            g_free(unitx);
            g_free(unity);
        }
    }

    rowstride *= gwy_raw_data_size(rawdatatype);
    dfield = gwy_data_field_new(xres, yres, xres*dx, yres*dy, FALSE);
    gwy_data_field_set_xoffset(dfield, xoff);
    gwy_data_field_set_yoffset(dfield, yoff);
    d = gwy_data_field_get_data(dfield);
    for (i = 0; i < yres; i++)
        gwy_convert_raw_data(data + i*rowstride, xres, stride, rawdatatype, byteorder, d + i*xres, q, z0);

    if (siunitxy) {
        gwy_si_unit_assign(gwy_data_field_get_si_unit_xy(dfield), siunitxy);
        g_object_unref(siunitxy);
    }
    if (siunitz) {
        gwy_si_unit_assign(gwy_data_field_get_si_unit_z(dfield), siunitz);
        g_object_unref(siunitz);
    }

    return dfield;
}

static GwyBrick*
read_raw_brick(guint xres, guint yres, guint zres,
               GwyRawDataType rawdatatype, GwyByteOrder byteorder,
               GHashTable *fields,
               const guchar *data)
{
    GwyBrick *brick;
    GwySIUnit *siunitz = NULL, *siunitx = NULL, *siunity = NULL, *siunitw = NULL;
    gdouble dx = 1.0, dy = 1.0, dz = 1.0, q = 1.0, w0 = 0.0, xoff = 0.0, yoff = 0.0, zoff = 0.0;
    gdouble *d;
    gint power10;
    gchar *value;

    if ((value = g_hash_table_lookup(fields, "oldmin")))
        w0 = g_ascii_strtod(value, NULL);

    if ((value = g_hash_table_lookup(fields, "oldmax")))
        q = g_ascii_strtod(value, NULL) - w0;

    if ((value = g_hash_table_lookup(fields, "spacings"))
        && parse_float_vector(value, 3, &dx, &dy, &dz)) {
        if (!((dx = fabs(dx)) > 0)) {
            g_warning("Real x step is 0.0, fixing to 1.0");
            dx = 1.0;
        }
        if (!((dy = fabs(dy)) > 0)) {
            g_warning("Real y step is 0.0, fixing to 1.0");
            dy = 1.0;
        }
        if (!((dz = fabs(dz)) > 0)) {
            g_warning("Real z step is 0.0, fixing to 1.0");
            dz = 1.0;
        }
    }

    if ((value = g_hash_table_lookup(fields, "axismins")))
        parse_float_vector(value, 3, &xoff, &yoff, &zoff);

    /* Prefer axismaxs if both spacings and axismaxs are given. */
    if ((value = g_hash_table_lookup(fields, "axismaxs"))
        && parse_float_vector(value, 3, &dx, &dy, &dz)) {
        dx = (dx - xoff)/xres;
        dy = (dy - xoff)/xres;
        dz = (dz - zoff)/zres;
        if (!((dx = fabs(dx)) > 0)) {
            g_warning("Real x step is 0.0, fixing to 1.0");
            dx = 1.0;
        }
        if (!((dy = fabs(dy)) > 0)) {
            g_warning("Real y step is 0.0, fixing to 1.0");
            dy = 1.0;
        }
        if (!((dz = fabs(dz)) > 0)) {
            g_warning("Real z step is 0.0, fixing to 1.0");
            dz = 1.0;
        }
    }

    if ((value = g_hash_table_lookup(fields, "sampleunits"))) {
        gchar *unitw;
        if (parse_string_vector(value, 1, &unitw)) {
            siunitw = gwy_si_unit_new_parse(unitw, &power10);
            q *= pow10(power10);
            w0 *= pow10(power10);
            g_free(unitw);
        }
    }

    if ((value = g_hash_table_lookup(fields, "units"))) {
        gchar *unitx, *unity, *unitz;
        if (parse_string_vector(value, 3, &unitx, &unity, &unitz)) {
            siunitx = gwy_si_unit_new_parse(unitx, &power10);
            dx *= pow10(power10);
            siunity = gwy_si_unit_new_parse(unity, &power10);
            dy *= pow10(power10);
            siunitz = gwy_si_unit_new_parse(unitz, &power10);
            dz *= pow10(power10);
            g_free(unitx);
            g_free(unity);
            g_free(unitz);
        }
    }

    brick = gwy_brick_new(xres, yres, zres, xres*dx, yres*dy, zres*dz, FALSE);
    gwy_brick_set_xoffset(brick, xoff);
    gwy_brick_set_yoffset(brick, yoff);
    gwy_brick_set_zoffset(brick, zoff);
    d = gwy_brick_get_data(brick);
    gwy_convert_raw_data(data, xres*yres*zres, 1, rawdatatype, byteorder, d, q, w0);

    if (siunitx) {
        gwy_si_unit_assign(gwy_brick_get_si_unit_x(brick), siunitx);
        g_object_unref(siunitx);
    }
    if (siunity) {
        gwy_si_unit_assign(gwy_brick_get_si_unit_y(brick), siunity);
        g_object_unref(siunity);
    }
    if (siunitz) {
        gwy_si_unit_assign(gwy_brick_get_si_unit_z(brick), siunitz);
        g_object_unref(siunitz);
    }
    if (siunitw) {
        gwy_si_unit_assign(gwy_brick_get_si_unit_w(brick), siunitw);
        g_object_unref(siunitw);
    }

    return brick;
}

static void
add_meta(gpointer key, gpointer value, gpointer user_data)
{
    const gchar *strkey = (const gchar*)key;
    const gchar *strvalue = (const gchar*)value;
    GwyContainer *meta = (GwyContainer*)user_data;

    gwy_container_set_string_by_name(meta, strkey, g_strdup(strvalue));
}

static GwyContainer*
nrrd_make_meta(GHashTable *keyvalue)
{
    GwyContainer *meta = gwy_container_new();

    g_hash_table_foreach(keyvalue, add_meta, meta);
    if (gwy_container_get_n_items(meta))
        return meta;
    g_object_unref(meta);

    return NULL;
}

static gboolean
parse_uint_vector(const gchar *value,
                  guint n,
                  ...)
{
    guint *values;
    va_list ap;
    gchar *end;
    guint i;

    values = g_new(guint, n);

    for (i = 0; i < n; i++) {
        values[i] = g_ascii_strtoull(value, &end, 10);
        if (end == value) {
            g_free(values);
            return FALSE;
        }
        value = end;
    }

    /* Guarantee that we don't touch args pointers if we don't return TRUE. */
    va_start(ap, n);
    for (i = 0; i < n; i++) {
        guint *u = va_arg(ap, guint*);
        *u = values[i];
    }
    va_end(ap);

    g_free(values);

    return TRUE;
}

static gboolean
parse_float_vector(const gchar *value,
                   guint n,
                   ...)
{
    gdouble *values;
    va_list ap;
    gchar *end;
    guint i;

    values = g_new(gdouble, n);

    for (i = 0; i < n; i++) {
        values[i] = g_ascii_strtod(value, &end);
        if (end == value || gwy_isnan(values[i]) || gwy_isinf(values[i])) {
            return FALSE;
        }
        value = end;
    }

    /* Guarantee that we don't touch args pointers if we don't return TRUE. */
    va_start(ap, n);
    for (i = 0; i < n; i++) {
        gdouble *d = va_arg(ap, gdouble*);
        *d = values[i];
    }
    va_end(ap);

    g_free(values);

    return TRUE;
}

static gboolean
parse_string_vector(const gchar *value,
                    guint n,
                    ...)
{
    gchar **values;
    va_list ap;
    guint i;

    values = g_new0(gchar*, n+1);

    for (i = 0; i < n; i++) {
        const gchar *begin;
        gboolean backslashed = FALSE, backslashedany = FALSE;

        while (g_ascii_isspace(*value))
            value++;

        if (*value != '"') {
            g_strfreev(values);
            return FALSE;
        }
        value++;
        begin = value;

        while (*value && (backslashed || *value != '"')) {
            if (backslashed)
                backslashed = FALSE;
            else if (*value == '\\')
                backslashed = backslashedany = TRUE;
            value++;
        }

        if (!*value) {
            g_strfreev(values);
            return FALSE;
        }

        if (backslashedany) {
            gchar *compressed = g_strndup(begin, value - begin);
            values[i] = g_strcompress(compressed);
            g_free(compressed);
        }
        else
            values[i] = g_strndup(begin, value - begin);

        /* Technically this means we do not require whitespace between an ending " and another starting ". */
        value++;
    }

    /* Guarantee that we don't touch args pointers if we don't return TRUE. */
    va_start(ap, n);
    for (i = 0; i < n; i++) {
        gchar **u = va_arg(ap, gchar**);
        *u = values[i];
    }
    va_end(ap);

    g_free(values);

    return TRUE;
}

static gchar**
split_per_axis_field(const gchar *value,
                     const gchar *name,
                     guint nitems,
                     gboolean quoted,
                     GError **error)
{
    gchar **raw_fields, **fields, *f;
    guint n = 0, i, len;

    raw_fields = g_strsplit_set(value, " \t\v\r\n", -1);
    fields = g_new0(gchar*, nitems+1);
    for (i = 0; (f = raw_fields[i]); i++) {
        len = strlen(f);
        if (!len)
            continue;

        if (quoted) {
            if (len < 2 || f[0] != '"' || f[len-1] != '"') {
                g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                            _("Items of per-axis header field %s are not quoted."),
                            name);
                goto fail;
            }
            f[len-1] = '\0';
            f++;
        }
        if (n == nitems) {
            g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                        _("Per-axis header field %s contains too many items."),
                        name);
            goto fail;
        }
        fields[n++] = g_strdup(f);
    }
    if (n < nitems) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("Per-axis header field %s contains too few items."),
                    name);
        goto fail;
    }

    g_strfreev(raw_fields);
    return fields;

fail:
    g_strfreev(raw_fields);
    g_strfreev(fields);
    return NULL;
}

static gboolean
nrrdfile_export(G_GNUC_UNUSED GwyContainer *data,
                const gchar *filename,
                G_GNUC_UNUSED GwyRunType mode,
                GError **error)
{
    /* We specify lateral units so at least version 4 is necessary. */
    static const gchar header_format[] =
        "NRRD0004\n"
        "type: float\n"
        "encoding: raw\n"
        "endian: %s\n"
        "dimension: 2\n"
        "sizes: %u %u\n"
        "axismins: %s %s\n"
        "axismaxs: %s %s\n"
        "units: \"%s\" \"%s\"\n"
        "sampleunits: \"%s\"\n"
        "kinds: space space\n"
        "\n";

    GwyDataField *dfield;
    const gdouble *d;
    gdouble xreal, yreal, xoff, yoff;
    guint xres, yres, i;
    gchar *unitxy, *unitz;
    gfloat *dfl;
    gchar buf[4][32];
    gboolean ok = TRUE;
    FILE *fh;

    gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD, &dfield, 0);
    if (!dfield) {
        err_NO_CHANNEL_EXPORT(error);
        return FALSE;
    }

    /* The specification says both kind of EOLs are fine so write Unix EOLs everywhere. */
    if (!(fh = gwy_fopen(filename, "wb"))) {
        err_OPEN_WRITE(error);
        return FALSE;
    }

    d = gwy_data_field_get_data_const(dfield);
    xres = gwy_data_field_get_xres(dfield);
    yres = gwy_data_field_get_yres(dfield);
    xreal = gwy_data_field_get_xreal(dfield);
    yreal = gwy_data_field_get_yreal(dfield);
    xoff = gwy_data_field_get_xoffset(dfield);
    yoff = gwy_data_field_get_yoffset(dfield);
    unitxy = gwy_si_unit_get_string(gwy_data_field_get_si_unit_xy(dfield), GWY_SI_UNIT_FORMAT_PLAIN);
    unitz = gwy_si_unit_get_string(gwy_data_field_get_si_unit_z(dfield), GWY_SI_UNIT_FORMAT_PLAIN);

    g_ascii_formatd(buf[0], sizeof(buf[0]), "%.8g", xoff);
    g_ascii_formatd(buf[1], sizeof(buf[1]), "%.8g", yoff);
    g_ascii_formatd(buf[2], sizeof(buf[2]), "%.8g", xreal + xoff);
    g_ascii_formatd(buf[3], sizeof(buf[3]), "%.8g", yreal + yoff);

    /* Write in native endian. */
    gwy_fprintf(fh, header_format,
                G_BYTE_ORDER == G_LITTLE_ENDIAN ? "little" : "big",
                xres, yres,
                buf[0], buf[1], buf[2], buf[3],
                unitxy, unitxy, unitz);
    g_free(unitz);
    g_free(unitxy);

    dfl = g_new(gfloat, xres*yres);
    for (i = 0; i < xres*yres; i++)
        dfl[i] = d[i];

    if (fwrite(dfl, sizeof(gfloat), xres*yres, fh) != xres*yres) {
        /* uses errno, must do this before fclose(). */
        err_WRITE(error);
        ok = FALSE;
    }
    g_free(dfl);
    fclose(fh);

    return ok;
}

/* vim: set cin columns=120 tw=118 et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */