-
Notifications
You must be signed in to change notification settings - Fork 228
/
nii_dicom_batch.cpp
10497 lines (10195 loc) · 430 KB
/
nii_dicom_batch.cpp
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
// #define myNoSave //do not save images to disk
#ifdef _MSC_VER
#include <direct.h>
#define getcwd _getcwd
#define chdir _chrdir
#include "io.h"
// #include <math.h>
#define MiniZ
#else
#include <unistd.h>
#ifdef myDisableMiniZ
#undef MiniZ
#else
#define MiniZ
#endif
#endif
#if defined(__APPLE__) && defined(__MACH__)
#endif
#ifndef myDisableZLib
#ifdef MiniZ
#include "miniz.c" //single file clone of libz
#else
#include <zlib.h>
#endif
#else
#undef MiniZ
#endif
#include "tinydir.h"
#include "nifti1_io_core.h"
#include "print.h"
#ifndef USING_R
#include "nifti1.h"
#endif
#include "nii_dicom_batch.h"
#ifndef USING_R
#include "nii_foreign.h"
#endif
#include "nii_dicom.h"
#include "nii_ortho.h"
#ifdef myEnableJNIFTI
#include "base64.h"
#include "cJSON.h"
#endif
#include <ctype.h> //toupper
#include <float.h>
#include <math.h>
#include <stdbool.h> //requires VS 2015 or later
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h> // clock_t, clock, CLOCKS_PER_SEC
#if defined(_WIN64) || defined(_WIN32)
#include <windows.h> //write to registry
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define kSliceTolerance 0.2
#if defined(_WIN64) || defined(_WIN32)
const char kPathSeparator = '\\';
const char kFileSep[2] = "\\";
#else
const char kPathSeparator = '/';
const char kFileSep[2] = "/";
#endif
#ifdef USING_R
#include "ImageList.h"
#undef isnan
#define isnan ISNAN
#undef isfinite
#define isfinite R_FINITE
#endif
#define newTilt
#ifdef USING_R
#ifndef max
#define max(a, b) (a > b ? a : b)
#endif
#ifndef min
#define min(a, b) (a < b ? a : b)
#endif
#else
#ifndef max
#define max(a, b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#endif
#ifndef min
#define min(a, b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
#endif
#endif
#ifdef USING_DCM2NIIXFSWRAPPER
// create the struct to save nifti header, image data, TDICOMdata, & TDTI information.
// no .nii, .bval, .bvec are created.
MRIFSSTRUCT mrifsStruct;
std::vector<MRIFSSTRUCT> mrifsStruct_vector;
// retrieve the struct
MRIFSSTRUCT *nii_getMrifsStruct() {
return &mrifsStruct;
}
// free the memory used for the image and dti
void nii_clrMrifsStruct() {
free(mrifsStruct.imgM);
free(mrifsStruct.tdti);
for (int n = 0; n < mrifsStruct.nDcm; n++)
free(mrifsStruct.dicomlst[n]);
if (mrifsStruct.dicomlst != NULL)
free(mrifsStruct.dicomlst);
}
// retrieve the struct
std::vector<MRIFSSTRUCT> *nii_getMrifsStructVector() {
return &mrifsStruct_vector;
}
// free the memory used for the image and dti
void nii_clrMrifsStructVector() {
int nitem = mrifsStruct_vector.size();
for (int n = 0; n < nitem; n++) {
free(mrifsStruct_vector[n].imgM);
free(mrifsStruct_vector[n].tdti);
for (int n = 0; n < mrifsStruct.nDcm; n++)
free(mrifsStruct_vector[n].dicomlst[n]);
if (mrifsStruct_vector[n].dicomlst != NULL)
free(mrifsStruct_vector[n].dicomlst);
}
}
#endif
bool isADCnotDTI(TDTI bvec) { // returns true if bval!=0 but all bvecs == 0 (Philips code for derived ADC image)
return ((!isSameFloat(bvec.V[0], 0.0f)) && // not a B-0 image
((isSameFloat(bvec.V[1], 0.0f)) && (isSameFloat(bvec.V[2], 0.0f)) && (isSameFloat(bvec.V[3], 0.0f))));
}
struct TDCMsort {
uint64_t indx, img;
uint32_t dimensionIndexValues[MAX_NUMBER_OF_DIMENSIONS];
};
struct TSearchList {
unsigned long numItems, maxItems;
char **str;
};
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
void dropFilenameFromPath(char *path) {
const char *dirPath = strrchr(path, '/'); // UNIX
if (dirPath == 0)
dirPath = strrchr(path, '\\'); // Windows
if (dirPath == NULL) {
strcpy(path, "");
} else
path[dirPath - path] = 0; // please make sure there is enough space in TargetDirectory
if (strlen(path) == 0) { // file name did not specify path, assume relative path and return current working directory
// strcat (path,"."); //relative path - use cwd <- not sure if this works on Windows!
char cwd[PATH_MAX];
char *ok = getcwd(cwd, sizeof(cwd));
if (ok != NULL)
strcat(path, cwd);
}
}
void dropTrailingFileSep(char *path) { //
size_t len = strlen(path) - 1;
if (len <= 0)
return;
if (path[len] == '/')
path[len] = '\0';
else if (path[len] == '\\')
path[len] = '\0';
}
bool is_fileexists(const char *filename) {
FILE *fp = NULL;
if ((fp = fopen(filename, "r"))) {
fclose(fp);
return true;
}
return false;
}
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
#endif
bool is_fileNotDir(const char *path) { // returns false if path is a folder; requires #include <sys/stat.h>
struct stat buf;
stat(path, &buf);
return S_ISREG(buf.st_mode);
} // is_file()
bool is_exe(const char *path) { // requires #include <sys/stat.h>
struct stat buf;
if (stat(path, &buf) != 0)
return false; // file does not eist
if (!S_ISREG(buf.st_mode))
return false; // not regular file, e.g. '..'
return (buf.st_mode & 0111);
// return (S_ISREG(buf.st_mode) && (buf.st_mode & 0111) );
} // is_exe()
#if defined(_WIN64) || defined(_WIN32)
// Windows does not support lstat
int is_dir(const char *pathname, int follow_link) {
struct stat s;
if ((NULL == pathname) || (0 == strlen(pathname)))
return 0;
int err = stat(pathname, &s);
if (-1 == err)
return 0; // does not exist
else {
if (S_ISDIR(s.st_mode)) {
return 1; // it's a dir
} else {
return 0; // exists but is no dir
}
}
} // is_dir()
#else // if windows else Unix
int is_dir(const char *pathname, int follow_link) {
struct stat s;
int retval;
if ((NULL == pathname) || (0 == strlen(pathname)))
return 0; // does not exist
retval = follow_link ? stat(pathname, &s) : lstat(pathname, &s);
if ((-1 != retval) && (S_ISDIR(s.st_mode)))
return 1; // it's a dir
return 0; // exists but is no dir
} // is_dir()
#endif
void opts2Prefs(struct TDCMopts *opts, struct TDCMprefs *prefs) {
setDefaultPrefs(prefs);
prefs->isVerbose = opts->isVerbose;
prefs->compressFlag = opts->compressFlag;
prefs->isIgnoreTriggerTimes = opts->isIgnoreTriggerTimes;
}
void geCorrectBvecs(struct TDICOMdata *d, int sliceDir, struct TDTI *vx, int isVerbose) {
// 0018,1312 phase encoding is either in row or column direction
// 0043,1039 (or 0043,a039). b value (as the first number in the string).
// 0019,10bb (or 0019,a0bb). phase diffusion direction
// 0019,10bc (or 0019,a0bc). frequency diffusion direction
// 0019,10bd (or 0019,a0bd). slice diffusion direction
// These directions are relative to freq,phase,slice, so although no
// transformations are required, you need to check the direction of the
// phase encoding. This is in DICOM message 0018,1312. If this has value
// COL then if swap the x and y value and reverse the sign on the z value.
// If the phase encoding is not COL, then just reverse the sign on the x value.
if ((d->manufacturer != kMANUFACTURER_GE) && (d->manufacturer != kMANUFACTURER_CANON))
return;
if (d->isBVecWorldCoordinates)
return; // Canon classic DICOMs use image space, enhanced use world space!
if ((!d->isEPI) && (d->CSA.numDti == 1))
d->CSA.numDti = 0; // issue449
if (d->CSA.numDti < 1)
return;
if ((toupper(d->patientOrient[0]) == 'H') && (toupper(d->patientOrient[1]) == 'F') && (toupper(d->patientOrient[2]) == 'S'))
; // participant was head first supine
else {
printWarning("Limited validation for non-HFS (Head first supine) GE DTI: confirm gradient vector transformation\n");
}
bool col = false;
if (d->phaseEncodingRC == 'C')
col = true;
else if (d->phaseEncodingRC != 'R') {
printWarning("Unable to determine DTI gradients, 0018,1312 should be either R or C");
return;
}
if (abs(sliceDir) != 3)
printWarning("Limited validation for non-Axial DTI: confirm gradient vector transformation.\n");
// GE vectors from Xiangrui Li' dicm2nii, validated with datasets from https://www.nitrc.org/plugins/mwiki/index.php/dcm2nii:MainPage#Diffusion_Tensor_Imaging
ivec3 flp;
if (abs(sliceDir) == 1)
flp = setiVec3(1, 1, 0); // SAGITTAL
else if (abs(sliceDir) == 2)
flp = setiVec3(0, 1, 1); // CORONAL
else if (abs(sliceDir) == 3)
flp = setiVec3(0, 0, 1); // AXIAL
else {
printMessage("Impossible GE slice orientation!");
flp = setiVec3(0, 0, 1); // AXIAL???
}
if (sliceDir < 0)
flp.v[2] = 1 - flp.v[2];
if ((isVerbose) || (!col)) {
printMessage("Saving %d DTI gradients. GE Reorienting %s : please validate. isCol=%d sliceDir=%d flp=%d %d %d\n", d->CSA.numDti, d->protocolName, col, sliceDir, flp.v[0], flp.v[1], flp.v[2]);
if (!col)
printWarning("Reorienting for ROW phase-encoding untested.\n");
}
bool scaledBValWarning = false;
for (int i = 0; i < d->CSA.numDti; i++) {
float vLen = sqrt((vx[i].V[1] * vx[i].V[1]) + (vx[i].V[2] * vx[i].V[2]) + (vx[i].V[3] * vx[i].V[3]));
if ((vx[i].V[0] <= FLT_EPSILON) || (vLen <= FLT_EPSILON)) { // bvalue=0
for (int v = 1; v < 4; v++)
vx[i].V[v] = 0.0f;
continue; // do not normalize or reorient 0 vectors
}
if ((vLen > 0.03) && (vLen < 0.97)) {
// bVal scaled by norm(g)^2 issue163,245
float bValtemp = 0, bVal = 0, bVecScale = 0;
// rounding by 5 with minimum of 5 if b-value > 0
bValtemp = vx[i].V[0] * (vLen * vLen);
if (bValtemp > 0 && bValtemp < 5) {
bVal = 5;
} else {
bVal = (int)((bValtemp + 2.5f) / 5) * 5;
}
if (bVal == 0)
bVecScale = 0;
else {
bVecScale = sqrt((float)vx[i].V[0] / bVal);
}
if (!scaledBValWarning) {
printMessage("GE BVal scaling (e.g. %g -> %g s/mm^2)\n", vx[i].V[0], bVal);
scaledBValWarning = true;
}
vx[i].V[0] = bVal;
vx[i].V[1] = vx[i].V[1] * bVecScale;
vx[i].V[2] = vx[i].V[2] * bVecScale;
vx[i].V[3] = vx[i].V[3] * bVecScale;
}
if (!col) { // rows need to be swizzled
// see Stanford dataset Ax_DWI_Tetrahedral_7 unable to resolve between possible solutions
// http://www.nitrc.org/plugins/mwiki/index.php/dcm2nii:MainPage#Diffusion_Tensor_Imaging
float swap = vx[i].V[1];
vx[i].V[1] = vx[i].V[2];
vx[i].V[2] = swap;
vx[i].V[2] = -vx[i].V[2]; // because of transpose?
}
for (int v = 0; v < 3; v++)
if (flp.v[v] == 1)
vx[i].V[v + 1] = -vx[i].V[v + 1];
vx[i].V[2] = -vx[i].V[2]; // we read out Y-direction opposite order as dicm2nii, see also opts.isFlipY
}
// These next lines are only so files appear identical to old versions of dcm2niix:
// dicm2nii and dcm2niix generate polar opposite gradient directions.
// this does not matter, since intensity is the normal of the gradient vector.
for (int i = 0; i < d->CSA.numDti; i++)
for (int v = 1; v < 4; v++)
vx[i].V[v] = -vx[i].V[v];
// These next lines convert any "-0" values to "0"
for (int i = 0; i < d->CSA.numDti; i++)
for (int v = 1; v < 4; v++)
if (isSameFloat(vx[i].V[v], -0))
vx[i].V[v] = 0.0f;
} // geCorrectBvecs()
void siemensPhilipsCorrectBvecs(struct TDICOMdata *d, int sliceDir, struct TDTI *vx, int isVerbose) {
// see Matthew Robson's http://users.fmrib.ox.ac.uk/~robson/internal/Dicom2Nifti111.m
// convert DTI vectors from scanner coordinates to image frame of reference
// Uses 6 orient values from ImageOrientationPatient (0020,0037)
// requires PatientPosition 0018,5100 is HFS (head first supine)
if ((!d->isBVecWorldCoordinates) && (d->manufacturer != kMANUFACTURER_MEDISO) && (d->manufacturer != kMANUFACTURER_BRUKER) && (d->manufacturer != kMANUFACTURER_TOSHIBA) && (d->manufacturer != kMANUFACTURER_HITACHI) && (d->manufacturer != kMANUFACTURER_UIH) && (d->manufacturer != kMANUFACTURER_SIEMENS) && (d->manufacturer != kMANUFACTURER_PHILIPS))
return;
if (d->CSA.numDti < 1)
return;
if (d->manufacturer == kMANUFACTURER_UIH) {
for (int i = 0; i < d->CSA.numDti; i++) {
vx[i].V[2] = -vx[i].V[2];
for (int v = 0; v < 4; v++)
if (vx[i].V[v] == -0.0f)
vx[i].V[v] = 0.0f; // remove sign from values that are virtually zero
}
// simple diagnostics for data prior to realignment: useful as first direction is the same for al Philips sequences
// for (int i = 0; i < 3; i++)
// printf("%g = %g %g %g\n", vx[i].V[0], vx[i].V[1], vx[i].V[2], vx[i].V[3]);
return;
} // https://github.com/rordenlab/dcm2niix/issues/225
if ((toupper(d->patientOrient[0]) == 'H') && (toupper(d->patientOrient[1]) == 'F') && (toupper(d->patientOrient[2]) == 'S'))
; // participant was head first supine
else {
printMessage("Check bvecs: expected Patient Position (0018,5100) to be 'HFS' not '%s'\n", d->patientOrient);
// return; //see https://github.com/rordenlab/dcm2niix/issues/238
}
float minBvalThreshold = 6.0;
if (d->manufacturer == kMANUFACTURER_SIEMENS)
minBvalThreshold = 50.0;
vec3 read_vector = setVec3(d->orient[1], d->orient[2], d->orient[3]);
vec3 phase_vector = setVec3(d->orient[4], d->orient[5], d->orient[6]);
vec3 slice_vector = crossProduct(read_vector, phase_vector);
read_vector = nifti_vect33_norm(read_vector);
phase_vector = nifti_vect33_norm(phase_vector);
slice_vector = nifti_vect33_norm(slice_vector);
for (int i = 0; i < d->CSA.numDti; i++) {
float vLen = sqrt((vx[i].V[1] * vx[i].V[1]) + (vx[i].V[2] * vx[i].V[2]) + (vx[i].V[3] * vx[i].V[3]));
if ((vx[i].V[0] <= FLT_EPSILON) || (vLen <= FLT_EPSILON)) { // bvalue=0
if ((vx[i].V[0] > minBvalThreshold) && (!d->isDerived)) // Philip stores n.b. UIH B=1.25126 Vec=0,0,0 while Philips stored isotropic images
printWarning("Volume %d appears to be derived image ADC/Isotropic (non-zero b-value with zero vector length)\n", i);
continue; // do not normalize or reorient b0 vectors
} // if bvalue=0
vec3 bvecs_old = setVec3(vx[i].V[1], vx[i].V[2], vx[i].V[3]);
vec3 bvecs_new = setVec3(dotProduct(bvecs_old, read_vector), dotProduct(bvecs_old, phase_vector), dotProduct(bvecs_old, slice_vector));
bvecs_new = nifti_vect33_norm(bvecs_new);
vx[i].V[1] = bvecs_new.v[0];
vx[i].V[2] = -bvecs_new.v[1];
vx[i].V[3] = bvecs_new.v[2];
if (abs(sliceDir) == kSliceOrientMosaicNegativeDeterminant)
vx[i].V[2] = -vx[i].V[2];
for (int v = 0; v < 4; v++)
if (vx[i].V[v] == -0.0f)
vx[i].V[v] = 0.0f; // remove sign from values that are virtually zero
} // for each direction
if (d->isVectorFromBMatrix) {
printWarning("Saving %d DTI gradients. Eddy users: B-matrix does not encode b-vector polarity (issue 265).\n", d->CSA.numDti);
} else if (abs(sliceDir) == kSliceOrientMosaicNegativeDeterminant) {
printWarning("Saving %d DTI gradients. Validate vectors (matrix had a negative determinant).\n", d->CSA.numDti); // perhaps Siemens sagittal
} else if ((d->sliceOrient == kSliceOrientTra) || (d->manufacturer != kMANUFACTURER_PHILIPS)) {
if (isVerbose)
printMessage("Saving %d DTI gradients. Validate vectors.\n", d->CSA.numDti);
} else if (d->sliceOrient == kSliceOrientUnknown)
printWarning("Saving %d DTI gradients. Validate vectors (image slice orientation not reported, e.g. 2001,100B).\n", d->CSA.numDti);
if (d->manufacturer == kMANUFACTURER_BRUKER)
printWarning("Bruker DTI support experimental (issue 265).\n");
} // siemensPhilipsCorrectBvecs()
bool isNanPosition(struct TDICOMdata d) { // in 2007 some Siemens RGB DICOMs did not include the PatientPosition 0020,0032 tag
if (isnan(d.patientPosition[1]))
return true;
if (isnan(d.patientPosition[2]))
return true;
if (isnan(d.patientPosition[3]))
return true;
return false;
} // isNanPosition()
bool isSamePosition(struct TDICOMdata d, struct TDICOMdata d2) {
if (isNanPosition(d) || isNanPosition(d2))
return false;
if (!isSameFloat(d.patientPosition[1], d2.patientPosition[1]))
return false;
if (!isSameFloat(d.patientPosition[2], d2.patientPosition[2]))
return false;
if (!isSameFloat(d.patientPosition[3], d2.patientPosition[3]))
return false;
return true;
} // isSamePosition()
void nii_saveText(char pathoutname[], struct TDICOMdata d, struct TDCMopts opts, struct nifti_1_header *h, char *dcmname) {
if (!opts.isCreateText)
return;
char txtname[2048] = {""};
strcpy(txtname, pathoutname);
strcat(txtname, ".txt");
// printMessage("Saving text %s\n",txtname);
FILE *fp = fopen(txtname, "w");
fprintf(fp, "%s\tField Strength:\t%g\tProtocolName:\t%s\tScanningSequence00180020:\t%s\tTE:\t%g\tTR:\t%g\tSeriesNum:\t%ld\tAcquNum:\t%d\tImageNum:\t%d\tImageComments:\t%s\tDateTime:\t%f\tName:\t%s\tConvVers:\t%s\tDoB:\t%s\tGender:\t%c\tAge:\t%s\tDimXYZT:\t%d\t%d\t%d\t%d\tCoil:\t%d\tEchoNum:\t%d\tOrient(6)\t%g\t%g\t%g\t%g\t%g\t%g\tbitsAllocated\t%d\tInputName\t%s\n",
pathoutname, d.fieldStrength, d.protocolName, d.scanningSequence, d.TE, d.TR, d.seriesNum, d.acquNum, d.imageNum, d.imageComments,
d.dateTime, d.patientName, kDCMvers, d.patientBirthDate, d.patientSex, d.patientAge, h->dim[1], h->dim[2], h->dim[3], h->dim[4],
d.coilCrc, d.echoNum, d.orient[1], d.orient[2], d.orient[3], d.orient[4], d.orient[5], d.orient[6],
d.bitsAllocated, dcmname);
fclose(fp);
} // nii_saveText()
#define myReadAsciiCsa
#ifdef myReadAsciiCsa
// read from the ASCII portion of the Siemens CSA series header
// this is not recommended: poorly documented
// it is better to stick to the binary portion of the Siemens CSA image header
#if defined(_WIN64) || defined(_WIN32) || defined(__sun) || (defined(__APPLE__) && defined(__POWERPC__))
// https://opensource.apple.com/source/Libc/Libc-1044.1.2/string/FreeBSD/memmem.c
/*-
* Copyright (c) 2005 Pascal Gloor <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
const void *memmem(const char *l, size_t l_len, const char *s, size_t s_len) {
char *cur, *last;
const char *cl = (const char *)l;
const char *cs = (const char *)s;
/* we need something to compare */
if (l_len == 0 || s_len == 0)
return NULL;
/* "s" must be smaller or equal to "l" */
if (l_len < s_len)
return NULL;
/* special case where s_len == 1 */
if (s_len == 1)
return memchr(l, (int)*cs, l_len);
/* the last position where its possible to find "s" in "l" */
last = (char *)cl + l_len - s_len;
for (cur = (char *)cl; cur <= last; cur++)
if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
return cur;
return NULL;
}
// n.b. memchr returns "const void *" not "void *" for Windows C++ https://msdn.microsoft.com/en-us/library/d7zdhf37.aspx
#endif // for systems without memmem
int readKeyN1(const char *key, char *buffer, int remLength) { // look for text key in binary data stream, return subsequent integer value
char *keyPos = (char *)memmem(buffer, remLength, key, strlen(key));
if (!keyPos)
return -1;
int ret = 0;
int i = (int)strlen(key);
while ((i < remLength) && (keyPos[i] != 0x0A)) {
if (keyPos[i] >= '0' && keyPos[i] <= '9')
ret = (10 * ret) + keyPos[i] - '0';
i++;
}
return ret;
} // readKeyN1() //return -1 if key not found
int readKey(const char *key, char *buffer, int remLength) { // look for text key in binary data stream, return subsequent integer value
int ret = 0;
char *keyPos = (char *)memmem(buffer, remLength, key, strlen(key));
if (!keyPos)
return ret;
int i = (int)strlen(key);
while ((i < remLength) && (keyPos[i] != 0x0A)) {
if (keyPos[i] >= '0' && keyPos[i] <= '9')
ret = (10 * ret) + keyPos[i] - '0';
i++;
}
return ret;
} // readKey() //return 0 if key not found
float readKeyFloatNan(const char *key, char *buffer, int remLength) { // look for text key in binary data stream, return subsequent integer value
char *keyPos = (char *)memmem(buffer, remLength, key, strlen(key));
if (!keyPos)
return NAN;
char str[kDICOMStr];
strcpy(str, "");
char tmpstr[2];
tmpstr[1] = 0;
int i = (int)strlen(key);
while ((i < remLength) && (keyPos[i] != 0x0A)) {
if ((keyPos[i] >= '0' && keyPos[i] <= '9') || (keyPos[i] == '.') || (keyPos[i] == '-')) {
tmpstr[0] = keyPos[i];
strcat(str, tmpstr);
}
i++;
}
if (strlen(str) < 1)
return NAN;
return atof(str);
} // readKeyFloatNan()
float readKeyFloat(const char *key, char *buffer, int remLength) { // look for text key in binary data stream, return subsequent integer value
char *keyPos = (char *)memmem(buffer, remLength, key, strlen(key));
if (!keyPos)
return 0.0;
char str[kDICOMStr];
strcpy(str, "");
char tmpstr[2];
tmpstr[1] = 0;
int i = (int)strlen(key);
while ((i < remLength) && (keyPos[i] != 0x0A)) {
if ((keyPos[i] >= '0' && keyPos[i] <= '9') || (keyPos[i] == '.') || (keyPos[i] == '-')) {
tmpstr[0] = keyPos[i];
strcat(str, tmpstr);
}
i++;
}
if (strlen(str) < 1)
return 0.0;
return atof(str);
} // readKeyFloat()
void readKeyStrLen(const char *key, char *buffer, int remLength, char *outStr, int outStrLen) {
// if key is CoilElementID.tCoilID the string 'CoilElementID.tCoilID = ""Head_32""' returns 'Head32'
strcpy(outStr, "");
char *keyPos = (char *)memmem(buffer, remLength, key, strlen(key));
if (!keyPos)
return;
int i = (int)strlen(key);
int outLen = 0;
char tmpstr[2];
tmpstr[1] = 0;
bool isQuote = false;
while ((i < remLength) && (keyPos[i] != 0x0A)) {
if ((isQuote) && (keyPos[i] != '"') && (outLen < outStrLen)) {
tmpstr[0] = keyPos[i];
strcat(outStr, tmpstr);
outLen++;
}
if (keyPos[i] == '"') {
if (outLen > 0)
break;
isQuote = true;
}
i++;
}
} // readKeyStr()
void readKeyStr(const char *key, char *buffer, int remLength, char *outStr) {
readKeyStrLen(key, buffer, remLength, outStr, kDICOMStrLarge);
} // readKeyStr()
int phoenixOffsetCSASeriesHeader(unsigned char *buff, int lLength) {
// returns offset to ASCII Phoenix data
if (lLength < 36)
return 0;
if ((buff[0] != 'S') || (buff[1] != 'V') || (buff[2] != '1') || (buff[3] != '0'))
return EXIT_FAILURE;
int lPos = 8; // skip 8 bytes of data, 'SV10' plus 2 32-bit values unused1 and unused2
int lnTag = buff[lPos] + (buff[lPos + 1] << 8) + (buff[lPos + 2] << 16) + (buff[lPos + 3] << 24);
if ((buff[lPos + 4] != 77) || (lnTag < 1))
return 0;
lPos += 8; // skip 8 bytes of data, 32-bit lnTag plus 77 00 00 0
TCSAtag tagCSA;
TCSAitem itemCSA;
for (int lT = 1; lT <= lnTag; lT++) {
memcpy(&tagCSA, &buff[lPos], sizeof(tagCSA)); // read tag
if (!littleEndianPlatform())
nifti_swap_4bytes(1, &tagCSA.nitems);
if (tagCSA.nitems > 128) {
printError("%d n_tags CSA Series Header corrupted (0029,1020 ) see issue 633.\n", tagCSA.nitems);
return EXIT_FAILURE;
}
// printf("%d CSA of %s %d\n",lPos, tagCSA.name, tagCSA.nitems);
lPos += sizeof(tagCSA);
if (strcmp(tagCSA.name, "MrPhoenixProtocol") == 0)
return lPos;
for (int lI = 1; lI <= tagCSA.nitems; lI++) {
memcpy(&itemCSA, &buff[lPos], sizeof(itemCSA));
lPos += sizeof(itemCSA);
if (!littleEndianPlatform())
nifti_swap_4bytes(1, &itemCSA.xx2_Len);
lPos += ((itemCSA.xx2_Len + 3) / 4) * 4;
}
}
return 0;
} // phoenixOffsetCSASeriesHeader()
#define kMaxWipFree 64
#define freeDiffusionMaxN 512
typedef struct {
float TE0, TE1, delayTimeInTR, phaseOversampling, phaseResolution, txRefAmp, accelFactTotal;
int lInvContrasts, lContrasts, phaseEncodingLines, existUcImageNumb, ucMode, baseResolution, interp, partialFourier, echoSpacing,
difBipolar, parallelReductionFactorInPlane, refLinesPE, combineMode, patMode, ucMTC, accelFact3D, freeDiffusionN;
float alFree[kMaxWipFree];
float adFree[kMaxWipFree];
float alTI[kMaxWipFree];
float sPostLabelingDelay, ulLabelingDuration, dAveragesDouble, dThickness, ulShape, sPositionDTra, sNormalDTra;
vec3 freeDiffusionVec[freeDiffusionMaxN];
} TCsaAscii;
void siemensCsaAscii(const char *filename, TCsaAscii *csaAscii, int csaOffset, int csaLength, float *shimSetting, char *coilID, char *consistencyInfo, char *coilElements, char *pulseSequenceDetails, char *fmriExternalInfo, char *protocolName, char *wipMemBlock) {
// reads ASCII portion of CSASeriesHeaderInfo and returns lEchoTrainDuration or lEchoSpacing value
// returns 0 if no value found
csaAscii->sPostLabelingDelay = 0.0;
csaAscii->ulLabelingDuration = 0.0;
csaAscii->TE0 = 0.0;
csaAscii->TE1 = 0.0;
csaAscii->delayTimeInTR = -0.001;
csaAscii->phaseOversampling = 0.0;
csaAscii->phaseResolution = 0.0;
csaAscii->txRefAmp = 0.0;
csaAscii->phaseEncodingLines = 0;
csaAscii->existUcImageNumb = 0;
csaAscii->ucMode = -1;
csaAscii->baseResolution = 0;
csaAscii->interp = 0;
csaAscii->partialFourier = 0;
csaAscii->echoSpacing = 0;
csaAscii->lInvContrasts = 0;
csaAscii->lContrasts = 0;
csaAscii->difBipolar = 0; // 0=not assigned,1=bipolar,2=monopolar
csaAscii->parallelReductionFactorInPlane = 0;
csaAscii->accelFact3D = 0; // lAccelFact3D
csaAscii->accelFactTotal = 0.0;
csaAscii->refLinesPE = 0;
csaAscii->combineMode = 0;
csaAscii->patMode = 0;
csaAscii->ucMTC = 0;
csaAscii->freeDiffusionN = 0;
for (int i = 0; i < 8; i++)
shimSetting[i] = 0.0;
strcpy(coilID, "");
strcpy(consistencyInfo, "");
strcpy(coilElements, "");
strcpy(pulseSequenceDetails, "");
strcpy(fmriExternalInfo, "");
strcpy(wipMemBlock, "");
strcpy(protocolName, "");
if ((csaOffset < 0) || (csaLength < 8))
return;
FILE *pFile = fopen(filename, "rb");
if (pFile == NULL)
return;
fseek(pFile, 0, SEEK_END);
long lSize = ftell(pFile);
if (lSize < (csaOffset + csaLength)) {
fclose(pFile);
return;
}
fseek(pFile, csaOffset, SEEK_SET);
char *buffer = (char *)malloc(csaLength);
if (buffer == NULL)
return;
size_t result = fread(buffer, 1, csaLength, pFile);
if ((int)result != csaLength)
return;
fclose(pFile);
// next bit complicated: restrict to ASCII portion to avoid buffer overflow errors in BINARY portion
int startAscii = phoenixOffsetCSASeriesHeader((unsigned char *)buffer, csaLength);
// n.b. previous function parses binary V* "SV10" portion of header
// it will return "EXIT_FAILURE for text based X* "<XProtocol>"
int csaLengthTrim = csaLength;
char *bufferTrim = buffer;
if ((startAscii > 0) && (startAscii < csaLengthTrim)) { // ignore binary data at start
bufferTrim += startAscii;
csaLengthTrim -= startAscii;
}
char keyStr[] = "### ASCCONV BEGIN"; // skip to start of ASCII often "### ASCCONV BEGIN ###" but also "### ASCCONV BEGIN object=MrProtDataImpl@MrProtocolData"
char *keyPos = (char *)memmem(bufferTrim, csaLengthTrim, keyStr, strlen(keyStr));
if (keyPos) {
// We can detect multi-echo MPRAGE here, e.g. "lContrasts = 4"- but ideally we want an earlier detection
csaLengthTrim -= (keyPos - bufferTrim);
// FmriExternalInfo listed AFTER AscConvEnd and uses different delimiter ||
// char keyStrExt[] = "FmriExternalInfo";
// readKeyStr(keyStrExt, keyPos, csaLengthTrim, fmriExternalInfo);
#define myCropAtAscConvEnd
#ifdef myCropAtAscConvEnd
char keyStrEnd[] = "### ASCCONV END";
char *keyPosEnd = (char *)memmem(keyPos, csaLengthTrim, keyStrEnd, strlen(keyStrEnd));
if ((keyPosEnd) && ((keyPosEnd - keyPos) < csaLengthTrim)) // ignore binary data at end
csaLengthTrim = (int)(keyPosEnd - keyPos);
#endif
char keyStrLns[] = "sKSpace.lPhaseEncodingLines";
csaAscii->phaseEncodingLines = readKey(keyStrLns, keyPos, csaLengthTrim);
char keyStrUcImg[] = "sSliceArray.ucImageNumb"; // some non-mosaics like ToF include "sSliceArray.ucImageNumbSag"
csaAscii->existUcImageNumb = readKey(keyStrUcImg, keyPos, csaLengthTrim);
char keyStrUcMode[] = "sSliceArray.ucMode";
csaAscii->ucMode = readKeyN1(keyStrUcMode, keyPos, csaLengthTrim);
char keyStrBase[] = "sKSpace.lBaseResolution";
csaAscii->baseResolution = readKey(keyStrBase, keyPos, csaLengthTrim);
char keyStrInterp[] = "sKSpace.uc2DInterpolation";
csaAscii->interp = readKey(keyStrInterp, keyPos, csaLengthTrim);
char keyStrPF[] = "sKSpace.ucPhasePartialFourier";
csaAscii->partialFourier = readKey(keyStrPF, keyPos, csaLengthTrim);
char keyStrES[] = "sFastImaging.lEchoSpacing";
csaAscii->echoSpacing = readKey(keyStrES, keyPos, csaLengthTrim);
char keyStrNumInv[] = "lInvContrasts";
csaAscii->lInvContrasts = readKey(keyStrNumInv, keyPos, csaLengthTrim);
char keyStrNumEcho[] = "lContrasts";
csaAscii->lContrasts = readKey(keyStrNumEcho, keyPos, csaLengthTrim);
char keyStrDS[] = "sDiffusion.dsScheme";
csaAscii->difBipolar = readKey(keyStrDS, keyPos, csaLengthTrim);
if (csaAscii->difBipolar == 0) {
char keyStrROM[] = "ucReadOutMode";
csaAscii->difBipolar = readKey(keyStrROM, keyPos, csaLengthTrim);
if ((csaAscii->difBipolar >= 1) && (csaAscii->difBipolar <= 2)) { // E11C Siemens/CMRR dsScheme: 1=bipolar, 2=unipolar, B17 CMRR ucReadOutMode 0x1=monopolar, 0x2=bipolar
csaAscii->difBipolar = 3 - csaAscii->difBipolar;
} // https://github.com/poldracklab/fmriprep/pull/1359#issuecomment-448379329
}
char keyStrAF[] = "sPat.lAccelFactPE";
csaAscii->parallelReductionFactorInPlane = readKey(keyStrAF, keyPos, csaLengthTrim);
char keyStrAF3D[] = "sPat.lAccelFact3D";
csaAscii->accelFact3D = readKey(keyStrAF3D, keyPos, csaLengthTrim);
char keyStrAFTotal[] = "sPat.dTotalAccelFact";
csaAscii->accelFactTotal = readKeyFloat(keyStrAFTotal, keyPos, csaLengthTrim);
// issue 672: the tag "sSliceAcceleration.lMultiBandFactor" is not reliable:
// series 7 dcm_qa_xa30 has x3 multiband, but this tag reports "1" (perhaps cmrr sequences)
// char keyStrMB[] = "sSliceAcceleration.lMultiBandFactor";
// csaAscii->multiBandFactor = readKey(keyStrMB, keyPos, csaLengthTrim);
char keyStrRef[] = "sPat.lRefLinesPE";
csaAscii->refLinesPE = readKey(keyStrRef, keyPos, csaLengthTrim);
char keyStrCombineMode[] = "ucCoilCombineMode";
csaAscii->combineMode = readKeyN1(keyStrCombineMode, keyPos, csaLengthTrim);
// BIDS CoilCombinationMethod <- Siemens 'Coil Combine Mode' CSA ucCoilCombineMode 1 = Sum of Squares, 2 = Adaptive Combine,
// printf("CoilCombineMode %d\n", csaAscii->combineMode);
char keyStrPATMode[] = "sPat.ucPATMode"; // n.b. field set even if PAT not enabled, e.g. will list SENSE for a R-factor of 1
csaAscii->patMode = readKeyN1(keyStrPATMode, keyPos, csaLengthTrim);
char keyStrucMTC[] = "sPrepPulses.ucMTC"; // n.b. field set even if PAT not enabled, e.g. will list SENSE for a R-factor of 1
csaAscii->ucMTC = readKeyN1(keyStrucMTC, keyPos, csaLengthTrim);
// printf("PATMODE %d\n", csaAscii->patMode);
// char keyStrETD[] = "sFastImaging.lEchoTrainDuration";
//*echoTrainDuration = readKey(keyStrETD, keyPos, csaLengthTrim);
// char keyStrEF[] = "sFastImaging.lEPIFactor";
// ret = readKey(keyStrEF, keyPos, csaLengthTrim);
char keyStrCoil[] = "sCoilElementID.tCoilID";
readKeyStr(keyStrCoil, keyPos, csaLengthTrim, coilID);
char keyStrCI[] = "sProtConsistencyInfo.tMeasuredBaselineString";
// issue848 VE11 reports N4_VE11C_LATEST_20160120
readKeyStr(keyStrCI, keyPos, csaLengthTrim, consistencyInfo);
// issue848 VB17 reports N4_VB17A_LATEST_20090307
if (strlen(consistencyInfo) < 1) {
char keyStrCI2[] = "sProtConsistencyInfo.tBaselineString";
readKeyStr(keyStrCI2, keyPos, csaLengthTrim, consistencyInfo);
}
// issue848 XA30 reports 63010001
if (strlen(consistencyInfo) < 1) {
char keyStrCI3[] = "sProtConsistencyInfo.ulConvFromVersion";
int vers = readKey(keyStrCI3, keyPos, csaLengthTrim);
if (vers > 0)
snprintf(consistencyInfo, 16, "%d", vers);
}
char keyStrCS[] = "sCoilSelectMeas.sCoilStringForConversion";
readKeyStr(keyStrCS, keyPos, csaLengthTrim, coilElements);
char keyStrSeq[] = "tSequenceFileName";
readKeyStr(keyStrSeq, keyPos, csaLengthTrim, pulseSequenceDetails);
char keyStrWipMemBlock[] = "sWipMemBlock.tFree";
readKeyStrLen(keyStrWipMemBlock, keyPos, csaLengthTrim, wipMemBlock, kDICOMStrExtraLarge);
char keyStrPn[] = "tProtocolName";
readKeyStr(keyStrPn, keyPos, csaLengthTrim, protocolName);
char keyStrTE0[] = "alTE[0]";
csaAscii->TE0 = readKeyFloatNan(keyStrTE0, keyPos, csaLengthTrim);
char keyStrTE1[] = "alTE[1]";
csaAscii->TE1 = readKeyFloatNan(keyStrTE1, keyPos, csaLengthTrim);
char keyStrPLD[] = "sAsl.sPostLabelingDelay[0]";
csaAscii->sPostLabelingDelay = readKeyFloatNan(keyStrPLD, keyPos, csaLengthTrim);
char keyStrLD[] = "sAsl.ulLabelingDuration";
csaAscii->ulLabelingDuration = readKeyFloatNan(keyStrLD, keyPos, csaLengthTrim);
// read ALL alTI[*] values
for (int k = 0; k < kMaxWipFree; k++)
csaAscii->alTI[k] = NAN;
char keyStrTiFree[] = "alTI[";
// check if ANY csaAscii.alFree tags exist
char *keyPosTi = (char *)memmem(keyPos, csaLengthTrim, keyStrTiFree, strlen(keyStrTiFree));
if (keyPosTi) {
for (int k = 0; k < kMaxWipFree; k++) {
char txt[1024] = {""};
snprintf(txt, 1024, "%s%d]", keyStrTiFree, k);
csaAscii->alTI[k] = readKeyFloatNan(txt, keyPos, csaLengthTrim);
}
}
// read ALL csaAscii.alFree[*] values
for (int k = 0; k < kMaxWipFree; k++)
csaAscii->alFree[k] = 0.0;
char keyStrAlFree[] = "sWipMemBlock.alFree[";
// check if ANY csaAscii.alFree tags exist
char *keyPosFree = (char *)memmem(keyPos, csaLengthTrim, keyStrAlFree, strlen(keyStrAlFree));
if (keyPosFree) {
for (int k = 0; k < kMaxWipFree; k++) {
char txt[1024] = {""};
snprintf(txt, 1024, "%s%d]", keyStrAlFree, k);
csaAscii->alFree[k] = readKeyFloat(txt, keyPos, csaLengthTrim);
}
}
// read ALL csaAscii.adFree[*] values
for (int k = 0; k < kMaxWipFree; k++)
csaAscii->adFree[k] = NAN;
char keyStrAdFree[50];
strcpy(keyStrAdFree, "sWipMemBlock.adFree[");
// char keyStrAdFree[] = "sWipMemBlock.adFree[";
// check if ANY csaAscii.adFree tags exist
keyPosFree = (char *)memmem(keyPos, csaLengthTrim, keyStrAdFree, strlen(keyStrAdFree));
if (!keyPosFree) { //"Wip" -> "WiP", modern -> old Siemens
strcpy(keyStrAdFree, "sWiPMemBlock.adFree[");
keyPosFree = (char *)memmem(keyPos, csaLengthTrim, keyStrAdFree, strlen(keyStrAdFree));
}
if (keyPosFree) {
for (int k = 0; k < kMaxWipFree; k++) {
char txt[1024] = {""};
snprintf(txt, 1024, "%s%d]", keyStrAdFree, k);
csaAscii->adFree[k] = readKeyFloatNan(txt, keyPos, csaLengthTrim);
}
}
// read labelling plane
char keyStrDThickness[] = "sRSatArray.asElm[1].dThickness";
csaAscii->dThickness = readKeyFloat(keyStrDThickness, keyPos, csaLengthTrim);
if (csaAscii->dThickness > 0.0) {
char keyStrUlShape[] = "sRSatArray.asElm[1].ulShape";
csaAscii->ulShape = readKeyFloat(keyStrUlShape, keyPos, csaLengthTrim);
char keyStrSPositionDTra[] = "sRSatArray.asElm[1].sPosition.dTra";
csaAscii->sPositionDTra = readKeyFloat(keyStrSPositionDTra, keyPos, csaLengthTrim);
char keyStrSNormalDTra[] = "sRSatArray.asElm[1].sNormal.dTra";
csaAscii->sNormalDTra = readKeyFloat(keyStrSNormalDTra, keyPos, csaLengthTrim);
}
// Read NEX number of averages
char keyStrDAveragesDouble[] = "dAveragesDouble";
csaAscii->dAveragesDouble = readKeyFloat(keyStrDAveragesDouble, keyPos, csaLengthTrim);
// read delay time
char keyStrDelay[] = "lDelayTimeInTR";
csaAscii->delayTimeInTR = readKeyFloat(keyStrDelay, keyPos, csaLengthTrim);
char keyStrOver[] = "sKSpace.dPhaseOversamplingForDialog";
csaAscii->phaseOversampling = readKeyFloat(keyStrOver, keyPos, csaLengthTrim);
char keyStrPhase[] = "sKSpace.dPhaseResolution";
csaAscii->phaseResolution = readKeyFloat(keyStrPhase, keyPos, csaLengthTrim);
char keyStrAmp[] = "sTXSPEC.asNucleusInfo[0].flReferenceAmplitude";
csaAscii->txRefAmp = readKeyFloat(keyStrAmp, keyPos, csaLengthTrim);
// lower order shims: newer sequences
char keyStrSh0[] = "sGRADSPEC.asGPAData[0].lOffsetX";
shimSetting[0] = readKeyFloat(keyStrSh0, keyPos, csaLengthTrim);
char keyStrSh1[] = "sGRADSPEC.asGPAData[0].lOffsetY";
shimSetting[1] = readKeyFloat(keyStrSh1, keyPos, csaLengthTrim);
char keyStrSh2[] = "sGRADSPEC.asGPAData[0].lOffsetZ";
shimSetting[2] = readKeyFloat(keyStrSh2, keyPos, csaLengthTrim);
// lower order shims: older sequences
char keyStrSh0s[] = "sGRADSPEC.lOffsetX";
if (shimSetting[0] == 0.0)
shimSetting[0] = readKeyFloat(keyStrSh0s, keyPos, csaLengthTrim);
char keyStrSh1s[] = "sGRADSPEC.lOffsetY";
if (shimSetting[1] == 0.0)
shimSetting[1] = readKeyFloat(keyStrSh1s, keyPos, csaLengthTrim);
char keyStrSh2s[] = "sGRADSPEC.lOffsetZ";
if (shimSetting[2] == 0.0)
shimSetting[2] = readKeyFloat(keyStrSh2s, keyPos, csaLengthTrim);
// higher order shims: older sequences
char keyStrSh3[] = "sGRADSPEC.alShimCurrent[0]";
shimSetting[3] = readKeyFloat(keyStrSh3, keyPos, csaLengthTrim);
char keyStrSh4[] = "sGRADSPEC.alShimCurrent[1]";
shimSetting[4] = readKeyFloat(keyStrSh4, keyPos, csaLengthTrim);
char keyStrSh5[] = "sGRADSPEC.alShimCurrent[2]";
shimSetting[5] = readKeyFloat(keyStrSh5, keyPos, csaLengthTrim);
char keyStrSh6[] = "sGRADSPEC.alShimCurrent[3]";
shimSetting[6] = readKeyFloat(keyStrSh6, keyPos, csaLengthTrim);
char keyStrSh7[] = "sGRADSPEC.alShimCurrent[4]";
shimSetting[7] = readKeyFloat(keyStrSh7, keyPos, csaLengthTrim);
// pull out the directions in the DVI
char keyStrDVIn[] = "sDiffusion.sFreeDiffusionData.lDiffDirections";
int nDiffDir = readKey(keyStrDVIn, keyPos, csaLengthTrim);
csaAscii->freeDiffusionN = min(nDiffDir, freeDiffusionMaxN);
// printMessage("Free diffusion: %i\n", csaAscii->freeDiffusionN);
for (int k = 0; k < csaAscii->freeDiffusionN; k++) {
char txt[128];
snprintf(txt, 128, "sDiffusion.sFreeDiffusionData.asDiffDirVector[%i].dSag", k);
float x = readKeyFloat(txt, keyPos, csaLengthTrim);
snprintf(txt, 128, "sDiffusion.sFreeDiffusionData.asDiffDirVector[%i].dCor", k);
float y = readKeyFloat(txt, keyPos, csaLengthTrim);
snprintf(txt, 128, "sDiffusion.sFreeDiffusionData.asDiffDirVector[%i].dTra", k);
float z = readKeyFloat(txt, keyPos, csaLengthTrim);
csaAscii->freeDiffusionVec[k].v[0] = x;
csaAscii->freeDiffusionVec[k].v[1] = y;
csaAscii->freeDiffusionVec[k].v[2] = z;
}
}
free(buffer);
return;
} // siemensCsaAscii()
#endif // myReadAsciiCsa()
#ifndef myDisableZLib
// Uncomment next line to decode GE Protocol Data Block, for caveats see https://github.com/rordenlab/dcm2niix/issues/163
#define myReadGeProtocolBlock
#endif
#ifdef myReadGeProtocolBlock
int geProtocolBlock(const char *filename, int geOffset, int geLength, int isVerbose, int *sliceOrder, int *viewOrder, int *mbAccel, int *nSlices, float *groupDelay, char ioptGE[], char seqStr[]) {
*sliceOrder = -1;
*viewOrder = 0;
*mbAccel = 0;
*nSlices = 0;
*groupDelay = 0.0;
int ret = EXIT_FAILURE;