-
Notifications
You must be signed in to change notification settings - Fork 228
/
nii_dicom.cpp
7487 lines (7358 loc) · 310 KB
/
nii_dicom.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 MY_DEBUG
#if defined(_WIN64) || defined(_WIN32)
#include <windows.h> //write to registry
#endif
#ifdef _MSC_VER
#include <direct.h>
#define getcwd _getcwd
#define chdir _chrdir
#include "io.h"
#include <math.h>
//#define snprintf _snprintf
//#define vsnprintf _vsnprintf
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#ifdef _WIN32
#pragma comment(lib, "advapi32")
#endif
#else
#include <unistd.h>
#endif
//#include <time.h> //clock()
#ifndef USING_R
#include "nifti1.h"
#endif
#include "jpg_0XC3.h"
#include "nifti1_io_core.h"
#include "nii_dicom.h"
#include "print.h"
#include <ctype.h> //toupper
#include <float.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h> // discriminate files from folders
#include <sys/types.h>
#ifdef USING_R
#undef isnan
#define isnan ISNAN
#endif
#ifndef myDisableClassicJPEG
#ifdef myTurboJPEG
#include <turbojpeg.h>
#else
#include "ujpeg.h"
#endif
#endif
#ifdef myEnableJasper
#include <jasper/jasper.h>
#endif
#ifndef myDisableOpenJPEG
#include "openjpeg.h"
#ifdef myEnableJasper
ERROR : YOU CAN NOT COMPILE WITH myEnableJasper AND NOT myDisableOpenJPEG OPTIONS SET SIMULTANEOUSLY
#endif
unsigned char * imagetoimg(opj_image_t *image) {
int numcmpts = image->numcomps;
int sgnd = image->comps[0].sgnd;
int width = image->comps[0].w;
int height = image->comps[0].h;
int bpp = (image->comps[0].prec + 7) >> 3; //e.g. 12 bits requires 2 bytes
int imgbytes = bpp * width * height * numcmpts;
bool isOK = true;
if (numcmpts > 1) {
for (int comp = 1; comp < numcmpts; comp++) { //check RGB data
if (image->comps[0].w != image->comps[comp].w)
isOK = false;
if (image->comps[0].h != image->comps[comp].h)
isOK = false;
if (image->comps[0].dx != image->comps[comp].dx)
isOK = false;
if (image->comps[0].dy != image->comps[comp].dy)
isOK = false;
if (image->comps[0].prec != image->comps[comp].prec)
isOK = false;
if (image->comps[0].sgnd != image->comps[comp].sgnd)
isOK = false;
}
if (numcmpts != 3)
isOK = false; //we only handle Gray and RedGreenBlue, not GrayAlpha or RedGreenBlueAlpha
if (image->comps[0].prec != 8)
isOK = false; //only 8-bit for RGB data
}
if ((image->comps[0].prec < 1) || (image->comps[0].prec > 16))
isOK = false; //currently we only handle 1 and 2 byte data
if (!isOK) {
printMessage("jpeg decode failure w*h %d*%d bpp %d sgnd %d components %d OpenJPEG=%s\n", width, height, bpp, sgnd, numcmpts, opj_version());
return NULL;
}
#ifdef MY_DEBUG
printMessage("w*h %d*%d bpp %d sgnd %d components %d OpenJPEG=%s\n", width, height, bpp, sgnd, numcmpts, opj_version());
#endif
//extract the data
if ((bpp < 1) || (bpp > 2) || (width < 1) || (height < 1) || (imgbytes < 1)) {
printError("Catastrophic decompression error\n");
return NULL;
}
unsigned char *img = (unsigned char *)malloc(imgbytes);
uint16_t *img16ui = (uint16_t *)img; //unsigned 16-bit
int16_t *img16i = (int16_t *)img; //signed 16-bit
if (sgnd)
bpp = -bpp;
if (bpp == -1) {
free(img);
printError("Signed 8-bit DICOM?\n");
return NULL;
}
//n.b. Analyze rgb-24 are PLANAR e.g. RRR..RGGG..GBBB..B not RGBRGBRGB...RGB
int pix = 0; //ouput pixel
for (int cmptno = 0; cmptno < numcmpts; ++cmptno) {
int cpix = 0; //component pixel
int *v = image->comps[cmptno].data;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
switch (bpp) {
case 1:
img[pix] = (unsigned char)v[cpix];
break;
case 2:
img16ui[pix] = (uint16_t)v[cpix];
break;
case -2:
img16i[pix] = (int16_t)v[cpix];
break;
}
pix++;
cpix++;
} //for x
} //for y
} //for each component
return img;
} // imagetoimg()
typedef struct bufinfo {
unsigned char *buf;
unsigned char *cur;
size_t len;
} BufInfo;
static void my_stream_free(void *p_user_data) { //do nothing
//BufInfo d = (BufInfo) p_user_data;
//free(d.buf);
} // my_stream_free()
static OPJ_UINT32 opj_read_from_buffer(void *p_buffer, OPJ_UINT32 p_nb_bytes, BufInfo *p_file) {
OPJ_UINT32 l_nb_read;
if (p_file->cur + p_nb_bytes < p_file->buf + p_file->len) {
l_nb_read = p_nb_bytes;
} else {
l_nb_read = (OPJ_UINT32)(p_file->buf + p_file->len - p_file->cur);
}
memcpy(p_buffer, p_file->cur, l_nb_read);
p_file->cur += l_nb_read;
return l_nb_read ? l_nb_read : ((OPJ_UINT32)-1);
} //opj_read_from_buffer()
static OPJ_UINT32 opj_write_from_buffer(void *p_buffer, OPJ_UINT32 p_nb_bytes, BufInfo *p_file) {
memcpy(p_file->cur, p_buffer, p_nb_bytes);
p_file->cur += p_nb_bytes;
p_file->len += p_nb_bytes;
return p_nb_bytes;
} // opj_write_from_buffer()
static OPJ_SIZE_T opj_skip_from_buffer(OPJ_SIZE_T p_nb_bytes, BufInfo *p_file) {
if (p_file->cur + p_nb_bytes < p_file->buf + p_file->len) {
p_file->cur += p_nb_bytes;
return p_nb_bytes;
}
p_file->cur = p_file->buf + p_file->len;
return (OPJ_SIZE_T)-1;
} //opj_skip_from_buffer()
//fix for https://github.com/neurolabusc/dcm_qa/issues/5
static OPJ_BOOL opj_seek_from_buffer(OPJ_SIZE_T p_nb_bytes, BufInfo *p_file) {
//printf("opj_seek_from_buffer %d + %d -> %d + %d\n", p_file->cur , p_nb_bytes, p_file->buf, p_file->len);
if (p_nb_bytes < p_file->len) {
p_file->cur = p_file->buf + p_nb_bytes;
return OPJ_TRUE;
}
p_file->cur = p_file->buf + p_file->len;
return OPJ_FALSE;
} //opj_seek_from_buffer()
opj_stream_t *opj_stream_create_buffer_stream(BufInfo *p_file, OPJ_UINT32 p_size, OPJ_BOOL p_is_read_stream) {
opj_stream_t *l_stream;
if (!p_file)
return NULL;
l_stream = opj_stream_create(p_size, p_is_read_stream);
if (!l_stream)
return NULL;
opj_stream_set_user_data(l_stream, p_file, my_stream_free);
opj_stream_set_user_data_length(l_stream, p_file->len);
opj_stream_set_read_function(l_stream, (opj_stream_read_fn)opj_read_from_buffer);
opj_stream_set_write_function(l_stream, (opj_stream_write_fn)opj_write_from_buffer);
opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn)opj_skip_from_buffer);
opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn)opj_seek_from_buffer);
return l_stream;
} //opj_stream_create_buffer_stream()
unsigned char *nii_loadImgCoreOpenJPEG(char *imgname, struct nifti_1_header hdr, struct TDICOMdata dcm, int compressFlag) {
//OpenJPEG library is not well documented and has changed between versions
//Since the JPEG is embedded in a DICOM we need to skip bytes at the start of the file
// In theory we might also want to strip data that exists AFTER the image, see gdcmJPEG2000Codec.c
unsigned char *ret = NULL;
opj_dparameters_t params;
opj_codec_t *codec;
opj_image_t *jpx;
opj_stream_t *stream;
FILE *reader = fopen(imgname, "rb");
fseek(reader, 0, SEEK_END);
long size = ftell(reader) - dcm.imageStart;
if (size <= 8)
return NULL;
fseek(reader, dcm.imageStart, SEEK_SET);
unsigned char *data = (unsigned char *)malloc(size);
size_t sz = fread(data, 1, size, reader);
fclose(reader);
if (sz < size)
return NULL;
OPJ_CODEC_FORMAT format = OPJ_CODEC_JP2;
//DICOM JPEG2k is SUPPOSED to start with codestream, but some vendors include a header
if (data[0] == 0xFF && data[1] == 0x4F && data[2] == 0xFF && data[3] == 0x51)
format = OPJ_CODEC_J2K;
opj_set_default_decoder_parameters(¶ms);
BufInfo dx;
dx.buf = data;
dx.cur = data;
dx.len = size;
stream = opj_stream_create_buffer_stream(&dx, (OPJ_UINT32)size, true);
if (stream == NULL)
return NULL;
codec = opj_create_decompress(format);
// setup the decoder decoding parameters using user parameters
if (!opj_setup_decoder(codec, ¶ms))
goto cleanup2;
// Read the main header of the codestream and if necessary the JP2 boxes
if (!opj_read_header(stream, codec, &jpx)) {
printError("OpenJPEG failed to read the header %s (offset %d)\n", imgname, dcm.imageStart);
//comment these next lines to abort: include these to create zero-padded slice
#ifdef MY_ZEROFILLBROKENJPGS
//fix broken slices https://github.com/scitran-apps/dcm2niix/issues/4
printError("Zero-filled slice created\n");
int imgbytes = (hdr.bitpix / 8) * hdr.dim[1] * hdr.dim[2];
ret = (unsigned char *)calloc(imgbytes, 1);
#endif
goto cleanup2;
}
// Get the decoded image
if (!(opj_decode(codec, stream, jpx) && opj_end_decompress(codec, stream))) {
printError("OpenJPEG j2k_to_image failed to decode %s\n", imgname);
goto cleanup1;
}
ret = imagetoimg(jpx);
cleanup1:
opj_image_destroy(jpx);
cleanup2:
free(dx.buf);
opj_stream_destroy(stream);
opj_destroy_codec(codec);
return ret;
}
#endif //myDisableOpenJPEG
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
float deFuzz(float v) {
if (fabs(v) < 0.00001)
return 0;
else
return v;
}
#ifdef MY_DEBUG
void reportMat33(char *str, mat33 A) {
printMessage("%s = [%g %g %g ; %g %g %g; %g %g %g ]\n", str,
deFuzz(A.m[0][0]), deFuzz(A.m[0][1]), deFuzz(A.m[0][2]),
deFuzz(A.m[1][0]), deFuzz(A.m[1][1]), deFuzz(A.m[1][2]),
deFuzz(A.m[2][0]), deFuzz(A.m[2][1]), deFuzz(A.m[2][2]));
}
void reportMat44(char *str, mat44 A) {
//example: reportMat44((char*)"out",*R);
printMessage("%s = [%g %g %g %g; %g %g %g %g; %g %g %g %g; 0 0 0 1]\n", str,
deFuzz(A.m[0][0]), deFuzz(A.m[0][1]), deFuzz(A.m[0][2]), deFuzz(A.m[0][3]),
deFuzz(A.m[1][0]), deFuzz(A.m[1][1]), deFuzz(A.m[1][2]), deFuzz(A.m[1][3]),
deFuzz(A.m[2][0]), deFuzz(A.m[2][1]), deFuzz(A.m[2][2]), deFuzz(A.m[2][3]));
}
#endif
int verify_slice_dir(struct TDICOMdata d, struct TDICOMdata d2, struct nifti_1_header *h, mat44 *R, int isVerbose) {
//returns slice direction: 1=sag,2=coronal,3=axial, -= flipped
if (h->dim[3] < 2)
return 0; //don't care direction for single slice
int iSL = 1; //find Z-slice direction: row with highest magnitude of 3rd column
if ((fabs(R->m[1][2]) >= fabs(R->m[0][2])) && (fabs(R->m[1][2]) >= fabs(R->m[2][2])))
iSL = 2; //
if ((fabs(R->m[2][2]) >= fabs(R->m[0][2])) && (fabs(R->m[2][2]) >= fabs(R->m[1][2])))
iSL = 3; //axial acquisition
float pos = NAN;
if (!isnan(d2.patientPosition[iSL])) { //patient position fields exist
pos = d2.patientPosition[iSL];
if (isSameFloat(pos, d.patientPosition[iSL]))
pos = NAN;
#ifdef MY_DEBUG
if (!isnan(pos))
printMessage("position determined using lastFile %f\n", pos);
#endif
}
if (isnan(pos) && (!isnan(d.patientPositionLast[iSL]))) { //patient position fields exist
pos = d.patientPositionLast[iSL];
if (isSameFloat(pos, d.patientPosition[iSL]))
pos = NAN;
#ifdef MY_DEBUG
if (!isnan(pos))
printMessage("position determined using last (4d) %f\n", pos);
#endif
}
if (isnan(pos) && (!isnan(d.stackOffcentre[iSL])))
pos = d.stackOffcentre[iSL];
if (isnan(pos) && (!isnan(d.lastScanLoc)))
pos = d.lastScanLoc;
vec4 x;
x.v[0] = 0.0;
x.v[1] = 0.0;
x.v[2] = (float)(h->dim[3] - 1.0);
x.v[3] = 1.0;
vec4 pos1v = nifti_vect44mat44_mul(x, *R);
float pos1 = pos1v.v[iSL - 1]; //-1 as C indexed from 0
bool flip = false;
if (!isnan(pos)) // we have real SliceLocation for last slice or volume center
flip = (pos > R->m[iSL - 1][3]) != (pos1 > R->m[iSL - 1][3]); // same direction?, note C indices from 0
else { // we do some guess work and warn user
vec3 readV = setVec3(d.orient[1], d.orient[2], d.orient[3]);
vec3 phaseV = setVec3(d.orient[4], d.orient[5], d.orient[6]);
//printMessage("rd %g %g %g\n",readV.v[0],readV.v[1],readV.v[2]);
//printMessage("ph %g %g %g\n",phaseV.v[0],phaseV.v[1],phaseV.v[2]);
vec3 sliceV = crossProduct(readV, phaseV); //order important: this is our hail mary
flip = ((sliceV.v[0] + sliceV.v[1] + sliceV.v[2]) < 0);
//printMessage("verify slice dir %g %g %g\n",sliceV.v[0],sliceV.v[1],sliceV.v[2]);
if (isVerbose) { //1st pass only
if (!d.isDerived) { //do not warn user if image is derived
printWarning("Unable to determine slice direction: please check whether slices are flipped\n");
} else {
printWarning("Unable to determine slice direction: please check whether slices are flipped (derived image)\n");
}
}
}
if (flip) {
for (int i = 0; i < 4; i++)
R->m[i][2] = -R->m[i][2];
}
if (flip)
iSL = -iSL;
#ifdef MY_DEBUG
printMessage("verify slice dir %d %d %d\n", h->dim[1], h->dim[2], h->dim[3]);
//reportMat44((char*)"Rout",*R);
printMessage("flip = %d\n", flip);
printMessage("sliceDir = %d\n", iSL);
printMessage(" pos1 = %f\n", pos1);
#endif
return iSL;
} //verify_slice_dir()
mat44 noNaN(mat44 Q44, bool isVerbose, bool *isBogus) //simplify any headers that have NaN values
{
mat44 ret = Q44;
bool isNaN44 = false;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if (isnan(ret.m[i][j]))
isNaN44 = true;
if (isNaN44) {
*isBogus = true;
if (isVerbose)
printWarning("Bogus spatial matrix (perhaps non-spatial image): inspect spatial orientation\n");
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if (i == j)
ret.m[i][j] = 1;
else
ret.m[i][j] = 0;
ret.m[1][1] = -1;
} //if isNaN detected
return ret;
}
#define kSessionOK 0
#define kSessionBadMatrix 1
void setQSForm(struct nifti_1_header *h, mat44 Q44i, bool isVerbose) {
bool isBogus = false;
mat44 Q44 = noNaN(Q44i, isVerbose, &isBogus);
if ((h->session_error == kSessionBadMatrix) || (isBogus)) {
h->session_error = kSessionBadMatrix;
h->sform_code = NIFTI_XFORM_UNKNOWN;
} else
h->sform_code = NIFTI_XFORM_SCANNER_ANAT;
h->srow_x[0] = Q44.m[0][0];
h->srow_x[1] = Q44.m[0][1];
h->srow_x[2] = Q44.m[0][2];
h->srow_x[3] = Q44.m[0][3];
h->srow_y[0] = Q44.m[1][0];
h->srow_y[1] = Q44.m[1][1];
h->srow_y[2] = Q44.m[1][2];
h->srow_y[3] = Q44.m[1][3];
h->srow_z[0] = Q44.m[2][0];
h->srow_z[1] = Q44.m[2][1];
h->srow_z[2] = Q44.m[2][2];
h->srow_z[3] = Q44.m[2][3];
float dumdx, dumdy, dumdz;
nifti_mat44_to_quatern(Q44, &h->quatern_b, &h->quatern_c, &h->quatern_d, &h->qoffset_x, &h->qoffset_y, &h->qoffset_z, &dumdx, &dumdy, &dumdz, &h->pixdim[0]);
h->qform_code = h->sform_code;
} //setQSForm()
#ifdef my_unused
ivec3 maxCol(mat33 R) {
//return index of maximum column in 3x3 matrix, e.g. [1 0 0; 0 1 0; 0 0 1] -> 1,2,3
ivec3 ixyz;
mat33 foo;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
foo.m[i][j] = fabs(R.m[i][j]);
//ixyz.v[0] : row with largest value in column 1
ixyz.v[0] = 1;
if ((foo.m[1][0] > foo.m[0][0]) && (foo.m[1][0] >= foo.m[2][0]))
ixyz.v[0] = 2; //2nd column largest column
else if ((foo.m[2][0] > foo.m[0][0]) && (foo.m[2][0] > foo.m[1][0]))
ixyz.v[0] = 3; //3rd column largest column
//ixyz.v[1] : row with largest value in column 2, but not the same row as ixyz.v[1]
if (ixyz.v[0] == 1) {
ixyz.v[1] = 2;
if (foo.m[2][1] > foo.m[1][1])
ixyz.v[1] = 3;
} else if (ixyz.v[0] == 2) {
ixyz.v[1] = 1;
if (foo.m[2][1] > foo.m[0][1])
ixyz.v[1] = 3;
} else { //ixyz.v[0] == 3
ixyz.v[1] = 1;
if (foo.m[1][1] > foo.m[0][1])
ixyz.v[1] = 2;
}
//ixyz.v[2] : 3rd row, constrained by previous rows
ixyz.v[2] = 6 - ixyz.v[1] - ixyz.v[0]; //sum of 1+2+3
return ixyz;
}
int sign(float x) {
//returns -1,0,1 depending on if X is less than, equal to or greater than zero
if (x < 0)
return -1;
else if (x > 0)
return 1;
return 0;
}
// Subfunction: get dicom xform matrix and related info
// This is a direct port of Xiangrui Li's dicm2nii function
mat44 xform_mat(struct TDICOMdata d) {
vec3 readV = setVec3(d.orient[1], d.orient[2], d.orient[3]);
vec3 phaseV = setVec3(d.orient[4], d.orient[5], d.orient[6]);
vec3 sliceV = crossProduct(readV, phaseV);
mat33 R;
LOAD_MAT33(R, readV.v[0], readV.v[1], readV.v[2],
phaseV.v[0], phaseV.v[1], phaseV.v[2],
sliceV.v[0], sliceV.v[1], sliceV.v[2]);
R = nifti_mat33_transpose(R);
//reportMat33((char*)"R",R);
ivec3 ixyz = maxCol(R);
//printMessage("%d %d %d\n", ixyz.v[0], ixyz.v[1], ixyz.v[2]);
int iSL = ixyz.v[2]; // 1/2/3 for Sag/Cor/Tra slice
float cosSL = R.m[iSL - 1][2];
//printMessage("cosSL\t%g\n", cosSL);
//vec3 pixdim = setVec3(d.xyzMM[1], d.xyzMM[2], d.xyzMM[3]);
//printMessage("%g %g %g\n", pixdim.v[0], pixdim.v[1], pixdim.v[2]);
mat33 pixdim;
LOAD_MAT33(pixdim, d.xyzMM[1], 0.0, 0.0,
0.0, d.xyzMM[2], 0.0,
0.0, 0.0, d.xyzMM[3]);
R = nifti_mat33_mul(R, pixdim);
//reportMat33((char*)"R",R);
mat44 R44;
LOAD_MAT44(R44, R.m[0][0], R.m[0][1], R.m[0][2], d.patientPosition[1],
R.m[1][0], R.m[1][1], R.m[1][2], d.patientPosition[2],
R.m[2][0], R.m[2][1], R.m[2][2], d.patientPosition[3]);
//reportMat44((char*)"R",R44);
//rest are former: R = verify_slice_dir(R, s, dim, iSL)
if ((d.xyzDim[3] < 2) && (d.CSA.mosaicSlices < 2))
return R44; //don't care direction for single slice
vec3 dim = setVec3(d.xyzDim[1], d.xyzDim[2], d.xyzDim[3]);
if (d.CSA.mosaicSlices > 1) { //Siemens mosaic: use dim(1) since no transpose to img
float nRowCol = ceil(sqrt((double)d.CSA.mosaicSlices));
dim.v[0] = dim.v[0] / nRowCol;
dim.v[1] = dim.v[1] / nRowCol;
dim.v[2] = d.CSA.mosaicSlices;
vec4 dim4 = setVec4((nRowCol - 1) * dim.v[0] / 2.0f, (nRowCol - 1) * dim.v[1] / 2.0f, 0);
vec4 offset = nifti_vect44mat44_mul(dim4, R44);
//printMessage("%g %g %g\n", dim.v[0], dim.v[1], dim.v[2]);
//printMessage("%g %g %g\n", dim4.v[0], dim4.v[1], dim4.v[2]);
//printMessage("%g %g %g %g\n", offset.v[0], offset.v[1], offset.v[2], offset.v[3]);
//printMessage("nRowCol\t%g\n", nRowCol);
R44.m[0][3] = offset.v[0];
R44.m[1][3] = offset.v[1];
R44.m[2][3] = offset.v[2];
//R44.m[3][3] = offset.v[3];
if (sign(d.CSA.sliceNormV[iSL]) != sign(cosSL)) {
R44.m[0][2] = -R44.m[0][2];
R44.m[1][2] = -R44.m[1][2];
R44.m[2][2] = -R44.m[2][2];
R44.m[3][2] = -R44.m[3][2];
}
//reportMat44((char*)"iR44",R44);
return R44;
} else if (true) {
//SliceNormalVector TO DO
printMessage("Not completed");
#ifndef USING_R
exit(2);
#endif
return R44;
}
printMessage("Unable to determine spatial transform\n");
#ifndef USING_R
exit(1);
#else
return R44;
#endif
}
mat44 set_nii_header(struct TDICOMdata d) {
mat44 R = xform_mat(d);
//R(1:2,:) = -R(1:2,:); % dicom LPS to nifti RAS, xform matrix before reorient
for (int i = 0; i < 2; i++)
for (int j = 0; j < 4; j++)
R.m[i][j] = -R.m[i][j];
#ifdef MY_DEBUG
reportMat44((char *)"R44", R);
#endif
}
#endif
// This code predates Xiangrui Li's set_nii_header function
mat44 set_nii_header_x(struct TDICOMdata d, struct TDICOMdata d2, struct nifti_1_header *h, int *sliceDir, int isVerbose) {
*sliceDir = 0;
mat44 Q44 = nifti_dicom2mat(d.orient, d.patientPosition, d.xyzMM);
//Q44 = doQuadruped(Q44);
if (d.isSegamiOasis == true) {
//Segami reconstructions appear to disregard DICOM spatial parameters: assume center of volume is isocenter and no table tilt
// Consider sample image with d.orient (0020,0037) = -1 0 0; 0 1 0: this suggests image RAI (L->R, P->A, S->I) but the vendors viewing software suggests LPS
//Perhaps we should ignore 0020,0037 and 0020,0032 as they are hidden in sequence 0054,0022, but in this case no positioning is provided
// http://www.cs.ucl.ac.uk/fileadmin/cmic/Documents/DavidAtkinson/DICOM.pdf
// https://www.slicer.org/wiki/Coordinate_systems
LOAD_MAT44(Q44, -h->pixdim[1], 0, 0, 0, 0, -h->pixdim[2], 0, 0, 0, 0, h->pixdim[3], 0); //X and Y dimensions flipped in NIfTI (RAS) vs DICOM (LPS)
vec4 originVx = setVec4((h->dim[1] + 1.0f) / 2.0f, (h->dim[2] + 1.0f) / 2.0f, (h->dim[3] + 1.0f) / 2.0f);
vec4 originMm = nifti_vect44mat44_mul(originVx, Q44);
for (int i = 0; i < 3; i++)
Q44.m[i][3] = -originMm.v[i]; //set origin to center voxel
if (isVerbose) {
//printMessage("origin (vx) %g %g %g\n",originVx.v[0],originVx.v[1],originVx.v[2]);
//printMessage("origin (mm) %g %g %g\n",originMm.v[0],originMm.v[1],originMm.v[2]);
printWarning("Segami coordinates defy DICOM convention, please check orientation\n");
}
return Q44;
}
//next line only for Siemens mosaic: ignore for UIH grid
// https://github.com/xiangruili/dicm2nii/commit/47ad9e6d9bc8a999344cbd487d602d420fb1509f
if ((d.manufacturer == kMANUFACTURER_SIEMENS) && (d.CSA.mosaicSlices > 1)) {
double nRowCol = ceil(sqrt((double)d.CSA.mosaicSlices));
double lFactorX = (d.xyzDim[1] - (d.xyzDim[1] / nRowCol)) / 2.0;
double lFactorY = (d.xyzDim[2] - (d.xyzDim[2] / nRowCol)) / 2.0;
Q44.m[0][3] = (float)((Q44.m[0][0] * lFactorX) + (Q44.m[0][1] * lFactorY) + Q44.m[0][3]);
Q44.m[1][3] = (float)((Q44.m[1][0] * lFactorX) + (Q44.m[1][1] * lFactorY) + Q44.m[1][3]);
Q44.m[2][3] = (float)((Q44.m[2][0] * lFactorX) + (Q44.m[2][1] * lFactorY) + Q44.m[2][3]);
for (int c = 0; c < 2; c++)
for (int r = 0; r < 4; r++)
Q44.m[c][r] = -Q44.m[c][r];
mat33 Q;
LOAD_MAT33(Q, d.orient[1], d.orient[4], d.CSA.sliceNormV[1],
d.orient[2], d.orient[5], d.CSA.sliceNormV[2],
d.orient[3], d.orient[6], d.CSA.sliceNormV[3]);
if (nifti_mat33_determ(Q) < 0) { //Siemens sagittal are R>>L, whereas NIfTI is L>>R, we retain Siemens order on disk so ascending is still ascending, but we need to have the spatial transform reflect this.
mat44 det;
*sliceDir = kSliceOrientMosaicNegativeDeterminant; //we need to handle DTI vectors accordingly
LOAD_MAT44(det, 1.0l, 0.0l, 0.0l, 0.0l, 0.0l, 1.0l, 0.0l, 0.0l, 0.0l, 0.0l, -1.0l, 0.0l);
//patient_to_tal.m[2][3] = 1-d.CSA.MosaicSlices;
Q44 = nifti_mat44_mul(Q44, det);
}
} else { //not a mosaic
*sliceDir = verify_slice_dir(d, d2, h, &Q44, isVerbose);
for (int c = 0; c < 4; c++) // LPS to nifti RAS, xform matrix before reorient
for (int r = 0; r < 2; r++) //swap rows 1 & 2
Q44.m[r][c] = -Q44.m[r][c];
}
#ifdef MY_DEBUG
reportMat44((char *)"Q44", Q44);
#endif
return Q44;
}
int headerDcm2NiiSForm(struct TDICOMdata d, struct TDICOMdata d2, struct nifti_1_header *h, int isVerbose) { //fill header s and q form
//see http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c
//returns sliceDir: 0=unknown,1=sag,2=coro,3=axial,-=reversed slices
int sliceDir = 0;
if (h->dim[3] < 2) {
mat44 Q44 = set_nii_header_x(d, d2, h, &sliceDir, isVerbose);
setQSForm(h, Q44, isVerbose);
return sliceDir; //don't care direction for single slice
}
h->sform_code = NIFTI_XFORM_UNKNOWN;
h->qform_code = NIFTI_XFORM_UNKNOWN;
bool isOK = false;
for (int i = 1; i <= 6; i++)
if (d.orient[i] != 0.0)
isOK = true;
if (!isOK) {
//we will have to guess, assume axial acquisition saved in standard Siemens style?
d.orient[1] = 1.0f;
d.orient[2] = 0.0f;
d.orient[3] = 0.0f;
d.orient[1] = 0.0f;
d.orient[2] = 1.0f;
d.orient[3] = 0.0f;
if ((d.isDerived) || ((d.bitsAllocated == 8) && (d.samplesPerPixel == 3) && (d.manufacturer == kMANUFACTURER_SIEMENS))) {
printMessage("Unable to determine spatial orientation: 0020,0037 missing (probably not a problem: derived image)\n");
} else {
printMessage("Unable to determine spatial orientation: 0020,0037 missing (Type 1 attribute: not a valid DICOM) Series %ld\n", d.seriesNum);
}
}
mat44 Q44 = set_nii_header_x(d, d2, h, &sliceDir, isVerbose);
setQSForm(h, Q44, isVerbose);
return sliceDir;
} //headerDcm2NiiSForm()
int headerDcm2Nii2(struct TDICOMdata d, struct TDICOMdata d2, struct nifti_1_header *h, int isVerbose) { //final pass after de-mosaic
char txt[1024] = {""};
if (h->slice_code == NIFTI_SLICE_UNKNOWN)
h->slice_code = d.CSA.sliceOrder;
if (h->slice_code == NIFTI_SLICE_UNKNOWN)
h->slice_code = d2.CSA.sliceOrder; //sometimes the first slice order is screwed up https://github.com/eauerbach/CMRR-MB/issues/29
if (d.modality == kMODALITY_MR)
sprintf(txt, "TE=%.2g;Time=%.3f", d.TE, d.acquisitionTime);
else
sprintf(txt, "Time=%.3f", d.acquisitionTime);
if (d.CSA.phaseEncodingDirectionPositive >= 0) {
char dtxt[1024] = {""};
sprintf(dtxt, ";phase=%d", d.CSA.phaseEncodingDirectionPositive);
strcat(txt, dtxt);
}
//from dicm2nii 20151117 InPlanePhaseEncodingDirection
if (d.phaseEncodingRC == 'R')
h->dim_info = (3 << 4) + (1 << 2) + 2;
if (d.phaseEncodingRC == 'C')
h->dim_info = (3 << 4) + (2 << 2) + 1;
if (d.CSA.multiBandFactor > 1) {
char dtxt[1024] = {""};
sprintf(dtxt, ";mb=%d", d.CSA.multiBandFactor);
strcat(txt, dtxt);
}
// GCC 8 warns about truncation using snprintf
// snprintf(h->descrip,80, "%s",txt);
memcpy(h->descrip, txt, 79);
h->descrip[79] = '\0';
if (strlen(d.imageComments) > 0)
snprintf(h->aux_file, 24, "%.23s", d.imageComments);
return headerDcm2NiiSForm(d, d2, h, isVerbose);
} //headerDcm2Nii2()
int dcmStrLen(int len, int kMaxLen) {
if (len < kMaxLen)
return len + 1;
else
return kMaxLen;
} //dcmStrLen()
struct TDICOMdata clear_dicom_data() {
struct TDICOMdata d;
//d.dti4D = NULL;
d.locationsInAcquisition = 0;
d.locationsInAcquisitionConflict = 0; //for GE discrepancy between tags 0020,1002; 0021,104F; 0054,0081
d.modality = kMODALITY_UNKNOWN;
d.effectiveEchoSpacingGE = 0;
for (int i = 0; i < 4; i++) {
d.CSA.dtiV[i] = 0;
d.patientPosition[i] = NAN;
//d.patientPosition2nd[i] = NAN; //used to distinguish XYZT vs XYTZ for Philips 4D
d.patientPositionLast[i] = NAN; //used to compute slice direction for Philips 4D
d.stackOffcentre[i] = NAN;
d.angulation[i] = 0.0f;
d.xyzMM[i] = 1;
}
for (int i = 0; i < MAX_NUMBER_OF_DIMENSIONS; ++i)
d.dimensionIndexValues[i] = 0;
//d.CSA.sliceTiming[0] = -1.0f; //impossible value denotes not known
for (int z = 0; z < kMaxEPI3D; z++)
d.CSA.sliceTiming[z] = -1.0;
d.CSA.numDti = 0;
for (int i = 0; i < 5; i++)
d.xyzDim[i] = 1;
for (int i = 0; i < 7; i++)
d.orient[i] = 0.0f;
strcpy(d.patientName, "");
strcpy(d.patientID, "");
strcpy(d.accessionNumber, "");
strcpy(d.imageType, "");
strcpy(d.imageComments, "");
strcpy(d.imageBaseName, "");
strcpy(d.phaseEncodingDirectionDisplayedUIH, "");
strcpy(d.studyDate, "");
strcpy(d.studyTime, "");
strcpy(d.protocolName, "");
strcpy(d.seriesDescription, "");
strcpy(d.sequenceName, "");
strcpy(d.scanningSequence, "");
strcpy(d.sequenceVariant, "");
strcpy(d.manufacturersModelName, "");
strcpy(d.institutionalDepartmentName, "");
strcpy(d.procedureStepDescription, "");
strcpy(d.institutionName, "");
strcpy(d.referringPhysicianName, "");
strcpy(d.institutionAddress, "");
strcpy(d.deviceSerialNumber, "");
strcpy(d.softwareVersions, "");
strcpy(d.stationName, "");
strcpy(d.scanOptions, "");
//strcpy(d.mrAcquisitionType, "");
strcpy(d.seriesInstanceUID, "");
strcpy(d.instanceUID, "");
strcpy(d.studyID, "");
strcpy(d.studyInstanceUID, "");
strcpy(d.bodyPartExamined, "");
strcpy(d.coilName, "");
strcpy(d.coilElements, "");
strcpy(d.radiopharmaceutical, "");
strcpy(d.convolutionKernel, "");
strcpy(d.parallelAcquisitionTechnique, "");
strcpy(d.imageOrientationText, "");
strcpy(d.unitsPT, "");
strcpy(d.decayCorrection, "");
strcpy(d.attenuationCorrectionMethod, "");
strcpy(d.reconstructionMethod, "");
d.phaseEncodingLines = 0;
//~ d.patientPositionSequentialRepeats = 0;
//~ d.patientPositionRepeats = 0;
d.isHasPhase = false;
d.isHasReal = false;
d.isHasImaginary = false;
d.isHasMagnitude = false;
//d.maxGradDynVol = -1; //PAR/REC only
d.sliceOrient = kSliceOrientUnknown;
d.dateTime = (double)19770703150928.0;
d.acquisitionTime = 0.0f;
d.acquisitionDate = 0.0f;
d.manufacturer = kMANUFACTURER_UNKNOWN;
d.isPlanarRGB = false;
d.lastScanLoc = NAN;
d.TR = 0.0;
d.TE = 0.0;
d.TI = 0.0;
d.flipAngle = 0.0;
d.bandwidthPerPixelPhaseEncode = 0.0;
d.acquisitionDuration = 0.0;
d.imagingFrequency = 0.0;
d.numberOfAverages = 0.0;
d.fieldStrength = 0.0;
d.SAR = 0.0;
d.pixelBandwidth = 0.0;
d.zSpacing = 0.0;
d.zThick = 0.0;
//~ d.numberOfDynamicScans = 0;
d.echoNum = 1;
d.echoTrainLength = 0;
d.waterFatShift = 0.0;
d.groupDelay = 0.0;
d.decayFactor = 0.0;
d.percentSampling = 0.0;
d.phaseFieldofView = 0.0;
d.dwellTime = 0;
d.protocolBlockStartGE = 0;
d.protocolBlockLengthGE = 0;
d.phaseEncodingSteps = 0;
d.coilCrc = 0;
d.seriesUidCrc = 0;
d.instanceUidCrc = 0;
d.accelFactPE = 0.0;
d.accelFactOOP = 0.0;
//d.patientPositionNumPhilips = 0;
d.imageBytes = 0;
d.intenScale = 1;
d.intenScalePhilips = 0;
d.intenIntercept = 0;
d.gantryTilt = 0.0;
d.exposureTimeMs = 0.0;
d.xRayTubeCurrent = 0.0;
d.radionuclidePositronFraction = 0.0;
d.radionuclideHalfLife = 0.0;
d.doseCalibrationFactor = 0.0;
d.ecat_isotope_halflife = 0.0;
d.frameDuration = -1.0;
d.ecat_dosage = 0.0;
d.radionuclideTotalDose = 0.0;
d.seriesNum = 1;
d.acquNum = 0;
d.imageNum = 1;
d.imageStart = 0;
d.is3DAcq = false; //e.g. MP-RAGE, SPACE, TFE
d.is2DAcq = false; //
d.isDerived = false; //0008,0008 = DERIVED,CSAPARALLEL,POSDISP
d.isSegamiOasis = false; //these images do not store spatial coordinates
d.isBVecWorldCoordinates = false; //bvecs can be in image space (GE) or world coordinates (Siemens)
d.isGrayscaleSoftcopyPresentationState = false;
d.isRawDataStorage = false;
d.isPartialFourier = false;
d.isIR = false;
d.isEPI = false;
d.isDiffusion = false;
d.isVectorFromBMatrix = false;
d.isStackableSeries = false; //combine DCE series https://github.com/rordenlab/dcm2niix/issues/252
d.isXA10A = false; //https://github.com/rordenlab/dcm2niix/issues/236
d.triggerDelayTime = 0.0;
d.RWVScale = 0.0;
d.RWVIntercept = 0.0;
d.isScaleOrTEVaries = false;
d.isScaleVariesEnh = false; //issue363
d.bitsAllocated = 16; //bits
d.bitsStored = 0;
d.samplesPerPixel = 1;
d.pixelPaddingValue = NAN;
d.isValid = false;
d.isXRay = false;
d.isMultiEcho = false;
d.isSigned = false; //default is unsigned!
d.isFloat = false; //default is for integers, not single or double precision
d.isResampled = false; //assume data not resliced to remove gantry tilt problems
d.isLocalizer = false;
d.isNonParallelSlices = false;
d.isCoilVaries = false;
d.compressionScheme = 0; //none
d.isExplicitVR = true;
d.isLittleEndian = true; //DICOM initially always little endian
d.converted2NII = 0;
d.numberOfDiffusionDirectionGE = -1;
d.phaseEncodingGE = kGE_PHASE_ENCODING_POLARITY_UNKNOWN;
d.rtia_timerGE = -1.0;
d.rawDataRunNumber = -1;
d.maxEchoNumGE = -1;
d.epiVersionGE = -1;
d.internalepiVersionGE = -1;
d.durationLabelPulseGE = -1;
d.aslFlags = kASL_FLAG_NONE;
d.partialFourierDirection = kPARTIAL_FOURIER_DIRECTION_UNKNOWN;
d.mtState = -1;
d.numberOfExcitations = -1;
d.numberOfArms = -1;
d.numberOfPointsPerArm = -1;
d.phaseNumber = - 1; //Philips Multi-Phase ASL
d.spoiling = kSPOILING_UNKOWN;
d.interp3D = -1;
for (int i = 0; i < kMaxOverlay; i++)
d.overlayStart[i] = 0;
d.isHasOverlay = false;
d.isPrivateCreatorRemap = false;
d.isRealIsPhaseMapHz = false;
d.numberOfImagesInGridUIH = 0;
d.phaseEncodingRC = '?';
d.patientSex = '?';
d.patientWeight = 0.0;
strcpy(d.patientBirthDate, "");
strcpy(d.patientAge, "");
d.CSA.bandwidthPerPixelPhaseEncode = 0.0;
d.CSA.mosaicSlices = 0;
d.CSA.sliceNormV[1] = 0.0;
d.CSA.sliceNormV[2] = 0.0;
d.CSA.sliceNormV[3] = 1.0; //default Siemens Image Numbering is F>>H https://www.mccauslandcenter.sc.edu/crnl/tools/stc
d.CSA.sliceOrder = NIFTI_SLICE_UNKNOWN;
d.CSA.slice_start = 0;
d.CSA.slice_end = 0;
d.CSA.protocolSliceNumber1 = 0;
d.CSA.phaseEncodingDirectionPositive = -1; //unknown
d.CSA.isPhaseMap = false;
d.CSA.multiBandFactor = 1;
d.CSA.SeriesHeader_offset = 0;
d.CSA.SeriesHeader_length = 0;
return d;
} //clear_dicom_data()
int isdigitdot(int c) { //returns true if digit or '.'
if (c == '.')
return 1;
return isdigit(c);
}
void dcmStrDigitsDotOnlyKey(char key, char *lStr) {
//e.g. string "F:2.50" returns 2.50 if key==":"
size_t len = strlen(lStr);
if (len < 1)
return;
bool isKey = false;
for (int i = 0; i < (int)len; i++) {
if (!isdigitdot(lStr[i])) {
isKey = (lStr[i] == key);
lStr[i] = ' ';
} else if (!isKey)
lStr[i] = ' ';
}
} //dcmStrDigitsOnlyKey()
void dcmStrDigitsOnlyKey(char key, char *lStr) {
//e.g. string "p2s3" returns 2 if key=="p" and 3 if key=="s"
size_t len = strlen(lStr);
if (len < 1)
return;
bool isKey = false;
for (int i = 0; i < (int)len; i++) {
if (!isdigit(lStr[i])) {
isKey = (lStr[i] == key);
lStr[i] = ' ';
} else if (!isKey)
lStr[i] = ' ';
}
} //dcmStrDigitsOnlyKey()
void dcmStrDigitsOnly(char *lStr) {
//e.g. change "H11" to " 11"
size_t len = strlen(lStr);
if (len < 1)
return;
for (int i = 0; i < (int)len; i++)
if (!isdigit(lStr[i]))
lStr[i] = ' ';
}
// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/
uint32_t mz_crc32X(unsigned char *ptr, size_t buf_len) {
static const uint32_t s_crc32[16] = {0, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,0xedb88320, 0xf00f9344,
0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
uint32_t crcu32 = 0;
if (!ptr)
return crcu32;
crcu32 = ~crcu32;
while (buf_len--) {
uint8_t b = *ptr++;
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
}
return ~crcu32;
}
void dcmStr(int lLength, unsigned char lBuffer[], char *lOut, bool isStrLarge = false) {
if (lLength < 1)
return;
char *cString = (char *)malloc(sizeof(char) * (lLength + 1));
cString[lLength] = 0;
memcpy(cString, (char *)&lBuffer[0], lLength);
//memcpy(cString, test, lLength);
//printMessage("X%dX\n", (unsigned char)d.patientName[1]);
#ifdef ISO8859
for (int i = 0; i < lLength; i++)
//assume specificCharacterSet (0008,0005) is ISO_IR 100 http://en.wikipedia.org/wiki/ISO/IEC_8859-1
if (cString[i] < 1) {
unsigned char c = (unsigned char)cString[i];
if ((c >= 192) && (c <= 198))
cString[i] = 'A';
if (c == 199)
cString[i] = 'C';
if ((c >= 200) && (c <= 203))
cString[i] = 'E';
if ((c >= 204) && (c <= 207))
cString[i] = 'I';
if (c == 208)
cString[i] = 'D';
if (c == 209)
cString[i] = 'N';
if ((c >= 210) && (c <= 214))
cString[i] = 'O';
if (c == 215)
cString[i] = 'x';
if (c == 216)
cString[i] = 'O';
if ((c >= 217) && (c <= 220))
cString[i] = 'O';
if (c == 221)
cString[i] = 'Y';
if ((c >= 224) && (c <= 230))
cString[i] = 'a';
if (c == 231)
cString[i] = 'c';
if ((c >= 232) && (c <= 235))
cString[i] = 'e';
if ((c >= 236) && (c <= 239))