1 #define _NIFTI1_IO_C_
2 
3 #include "nifti1_io.h"   /* typedefs, prototypes, macros, etc. */
4 
5 /*****===================================================================*****/
6 /*****     Sample functions to deal with NIFTI-1 and ANALYZE files       *****/
7 /*****...................................................................*****/
8 /*****            This code is released to the public domain.            *****/
9 /*****...................................................................*****/
10 /*****  Author: Robert W Cox, SSCC/DIRP/NIMH/NIH/DHHS/USA/EARTH          *****/
11 /*****  Date:   August 2003                                              *****/
12 /*****...................................................................*****/
13 /*****  Neither the National Institutes of Health (NIH), nor any of its  *****/
14 /*****  employees imply any warranty of usefulness of this software for  *****/
15 /*****  any purpose, and do not assume any liability for damages,        *****/
16 /*****  incidental or otherwise, caused by any use of this document.     *****/
17 /*****===================================================================*****/
18 
19 /** \file nifti1_io.c
20     \brief main collection of nifti1 i/o routines
21            - written by Bob Cox, SSCC NIMH
22            - revised by Mark Jenkinson, FMRIB
23            - revised by Rick Reynolds, SSCC, NIMH
24            - revised by Kate Fissell, University of Pittsburgh
25 
26         The library history can be viewed via "nifti_tool -nifti_hist".
27     <br>The library version can be viewed via "nifti_tool -nifti_ver".
28  */
29 
30 /*! global history and version strings, for printing */
31 static char * gni_history[] =
32 {
33   "----------------------------------------------------------------------\n"
34   "history (of nifti library changes):\n"
35   "\n",
36   "0.0  August, 2003 [rwcox]\n"
37   "     (Robert W Cox of the National Institutes of Health, SSCC/DIRP/NIMH)\n"
38   "   - initial version\n"
39   "\n",
40   "0.1  July/August, 2004 [Mark Jenkinson]\n"
41   "     (FMRIB Centre, University of Oxford, UK)\n"
42   "   - Mainly adding low-level IO and changing things to allow gzipped\n"
43   "     files to be read and written\n"
44   "   - Full backwards compatability should have been maintained\n"
45   "\n",
46   "0.2  16 Nov 2004 [rickr]\n"
47   "     (Rick Reynolds of the National Institutes of Health, SSCC/DIRP/NIMH)\n"
48   "   - included Mark's changes in the AFNI distribution (including znzlib/)\n"
49   "     (HAVE_ZLIB is commented out for the standard distribution)\n"
50   "   - modified nifti_validfilename() and nifti_makebasename()\n"
51   "   - added nifti_find_file_extension()\n"
52   "\n",
53   "0.3  3 Dec 2004 [rickr]\n"
54   "   - note: header extensions are not yet checked for\n"
55   "   - added formatted history as global string, for printing\n"
56   "   - added nifti_disp_lib_hist(), to display the nifti library history\n"
57   "   - added nifti_disp_lib_version(), to display the nifti library history\n",
58   "   - re-wrote nifti_findhdrname()\n"
59   "       o used nifti_find_file_extension()\n"
60   "       o changed order of file tests (default is .nii, depends on input)\n"
61   "       o free hdrname on failure\n"
62   "   - made similar changes to nifti_findimgname()\n"
63   "   - check for NULL return from nifti_findhdrname() calls\n",
64   "   - removed most of ERREX() macros\n"
65   "   - modified nifti_image_read()\n"
66   "       o added debug info and error checking (on gni_debug > 0, only)\n"
67   "       o fail if workingname is NULL\n"
68   "       o check for failure to open header file\n"
69   "       o free workingname on failure\n"
70   "       o check for failure of nifti_image_load()\n"
71   "       o check for failure of nifti_convert_nhdr2nim()\n",
72   "   - changed nifti_image_load() to int, and check nifti_read_buffer return\n"
73   "   - changed nifti_read_buffer() to fail on short read, and to count float\n"
74   "     fixes (to print on debug)\n"
75   "   - changed nifti_image_infodump to print to stderr\n"
76   "   - updated function header comments, or moved comments above header\n"
77   "   - removed const keyword\n"
78   "   - added LNI_FERR() macro for error reporting on input files\n"
79   "\n",
80   "0.4  10 Dec 2004 [rickr]  - added header extensions\n"
81   "   - in nifti1_io.h:\n"
82   "       o added num_ext and ext_list to the definition of nifti_image\n"
83   "       o made many functions static (more to follow)\n"
84   "       o added LNI_MAX_NIA_EXT_LEN, for max nifti_type 3 extension length\n",
85   "   - added __DATE__ to version output in nifti_disp_lib_version()\n"
86   "   - added nifti_disp_matrix_orient() to print orientation information\n"
87   "   - added '.nia' as a valid file extension in nifti_find_file_extension()\n"
88   "   - added much more debug output\n"
89   "   - in nifti_image_read(), in the case of an ASCII header, check for\n"
90   "     extensions after the end of the header\n",
91   "   - added nifti_read_extensions() function\n"
92   "   - added nifti_read_next_extension() function\n"
93   "   - added nifti_add_exten_to_list() function\n"
94   "   - added nifti_check_extension() function\n"
95   "   - added nifti_write_extensions() function\n"
96   "   - added nifti_extension_size() function\n"
97   "   - in nifti_set_iname_offest():\n"
98   "       o adjust offset by the extension size and the extender size\n",
99   "       o fixed the 'ceiling modulo 16' computation\n"
100   "   - in nifti_image_write_hdr_img2(): \n"
101   "       o added extension writing\n"
102   "       o check for NULL return from nifti_findimgname()\n"
103   "   - include number of extensions in nifti_image_to_ascii() output\n"
104   "   - in nifti_image_from_ascii():\n"
105   "       o return bytes_read as a parameter, computed from the final spos\n"
106   "       o extract num_ext from ASCII header\n"
107   "\n",
108   "0.5  14 Dec 2004 [rickr]  - added sub-brick reading functions\n"
109   "   - added nifti_brick_list type to nifti1_io.h, along with new prototypes\n"
110   "   - added main nifti_image_read_bricks() function, with description\n"
111   "   - added nifti_image_load_bricks() - library function (requires nim)\n"
112   "   - added valid_nifti_brick_list() - library function\n"
113   "   - added free_NBL() - library function\n",
114   "   - added update_nifti_image_for_brick_list() for dimension update\n"
115   "   - added nifti_load_NBL_bricks(), nifti_alloc_NBL_mem(),\n"
116   "           nifti_copynsort() and force_positive() (static functions)\n"
117   "   - in nifti_image_read(), check for failed load only if read_data is set\n"
118   "   - broke most of nifti_image_load() into nifti_image_load_prep()\n"
119   "\n",
120   "0.6  15 Dec 2004 [rickr]  - added sub-brick writing functionality\n"
121   "   - in nifti1_io.h, removed znzlib directory from include - all nifti\n"
122   "       library files are now under the nifti directory\n"
123   "   - nifti_read_extensions(): print no offset warning for nifti_type 3\n"
124   "   - nifti_write_all_data():\n"
125   "       o pass nifti_brick_list * NBL, for optional writing\n"
126   "       o if NBL, write each sub-brick, sequentially\n",
127   "   - nifti_set_iname_offset(): case 1 must have sizeof() cast to int\n"
128   "   - pass NBL to nifti_image_write_hdr_img2(), and allow NBL or data\n"
129   "   - added nifti_image_write_bricks() wrapper for ...write_hdr_img2()\n"
130   "   - included compression abilities\n"
131   "\n",
132   "0.7  16 Dec 2004 [rickr] - minor changes to extension reading\n"
133   "\n",
134   "0.8  21 Dec 2004 [rickr] - restrict extension reading, and minor changes\n"
135   "   - in nifti_image_read(), compute bytes for extensions (see remaining)\n"
136   "   - in nifti_read_extensions(), pass 'remain' as space for extensions,\n"
137   "        pass it to nifti_read_next_ext(), and update for each one read \n"
138   "   - in nifti_check_extension(), require (size <= remain)\n",
139   "   - in update_nifti_image_brick_list(), update nvox\n"
140   "   - in nifti_image_load_bricks(), make explicit check for nbricks <= 0\n"
141   "   - in int_force_positive(), check for (!list)\n"
142   "   - in swap_nifti_header(), swap sizeof_hdr, and reorder to struct order\n"
143   "   - change get_filesize functions to signed ( < 0 is no file or error )\n",
144   "   - in nifti_validfilename(), lose redundant (len < 0) check\n"
145   "   - make print_hex_vals() static\n"
146   "   - in disp_nifti_1_header, restrict string field widths\n"
147   "\n",
148   "0.9  23 Dec 2004 [rickr] - minor changes\n"
149   "   - broke ASCII header reading out of nifti_image_read(), into new\n"
150   "        functions has_ascii_header() and read_ascii_image()\n",
151   "   - check image_read failure and znzseek failure\n"
152   "   - altered some debug output\n"
153   "   - nifti_write_all_data() now returns an int\n"
154   "\n",
155   "0.10 29 Dec 2004 [rickr]\n"
156   "   - renamed nifti_valid_extension() to nifti_check_extension()\n"
157   "   - added functions nifti_makehdrname() and nifti_makeimgname()\n"
158   "   - added function valid_nifti_extensions()\n"
159   "   - in nifti_write_extensions(), check for validity before writing\n",
160   "   - rewrote nifti_image_write_hdr_img2():\n"
161   "       o set write_data and leave_open flags from write_opts\n"
162   "       o add debug print statements\n"
163   "       o use nifti_write_ascii_image() for the ascii case\n"
164   "       o rewrote the logic of all cases to be easier to follow\n",
165   "   - broke out code as nifti_write_ascii_image() function\n"
166   "   - added debug to top-level write functions, and free the znzFile\n"
167   "   - removed unused internal function nifti_image_open()\n"
168   "\n",
169   "0.11 30 Dec 2004 [rickr] - small mods\n"
170   "   - moved static function prototypes from header to C file\n"
171   "   - free extensions in nifti_image_free()\n"
172   "\n",
173   "1.0  07 Jan 2005 [rickr] - INITIAL RELEASE VERSION\n"
174   "   - added function nifti_set_filenames()\n"
175   "   - added function nifti_read_header()\n"
176   "   - added static function nhdr_looks_good()\n"
177   "   - added static function need_nhdr_swap()\n"
178   "   - exported nifti_add_exten_to_list symbol\n",
179   "   - fixed #bytes written in nifti_write_extensions()\n"
180   "   - only modify offset if it is too small (nifti_set_iname_offset)\n"
181   "   - added nifti_type 3 to nifti_makehdrname and nifti_makeimgname\n"
182   "   - added function nifti_set_filenames()\n"
183   "\n",
184   "1.1  07 Jan 2005 [rickr]\n"
185   "   - in nifti_read_header(), swap if needed\n"
186   "\n",
187   "1.2  07 Feb 2005 [kate fissell c/o rickr] \n"
188   "   - nifti1.h: added doxygen comments for main struct and #define groups\n"
189   "   - nifti1_io.h: added doxygen comments for file and nifti_image struct\n"
190   "   - nifti1_io.h: added doxygen comments for file and some functions\n"
191   "   - nifti1_io.c: changed nifti_copy_nim_info to use memcpy\n"
192   "\n",
193   "1.3  09 Feb 2005 [rickr]\n"
194   "   - nifti1.h: added doxygen comments for extension structs\n"
195   "   - nifti1_io.h: put most #defines in #ifdef _NIFTI1_IO_C_ block\n"
196   "   - added a doxygen-style description to every exported function\n"
197   "   - added doxygen-style comments within some functions\n"
198   "   - re-exported many znzFile functions that I had made static\n"
199   "   - re-added nifti_image_open (sorry, Mark)\n"
200   "   - every exported function now has 'nifti' in the name (19 functions)\n",
201   "   - made sure every alloc() has a failure test\n"
202   "   - added nifti_copy_extensions function, for use in nifti_copy_nim_info\n"
203   "   - nifti_is_gzfile: added initial strlen test\n"
204   "   - nifti_set_filenames: added set_byte_order parameter option\n"
205   "     (it seems appropriate to set the BO when new files are associated)\n"
206   "   - disp_nifti_1_header: prints to stdout (a.o.t. stderr), with fflush\n"
207   "\n",
208   "1.4  23 Feb 2005 [rickr] - sourceforge merge\n"
209   "   - merged into the nifti_io CVS directory structure at sourceforge.net\n"
210   "   - merged in 4 changes by Mark, and re-added his const keywords\n"
211   "   - cast some pointers to (void *) for -pedantic compile option\n"
212   "   - added nifti_free_extensions()\n"
213   "\n",
214   "1.5  02 Mar 2005 [rickr] - started nifti global options\n"
215   "   - gni_debug is now g_opts.debug\n"
216   "   - added validity check parameter to nifti_read_header\n"
217   "   - need_nhdr_swap no longer does test swaps on the stack\n"
218   "\n",
219   "1.6  05 April 2005 [rickr] - validation and collapsed_image_read\n"
220   "   - added nifti_read_collapsed_image(), an interface for reading partial\n"
221   "     datasets, specifying a subset of array indices\n"
222   "   - for read_collapsed_image, added static functions: rci_read_data(),\n"
223   "     rci_alloc_mem(), and make_pivot_list()\n",
224   "   - added nifti_nim_is_valid() to check for consistency (more to do)\n"
225   "   - added nifti_nim_has_valid_dims() to do many dimensions tests\n"
226   "\n",
227   "1.7  08 April 2005 [rickr]\n"
228   "   - added nifti_update_dims_from_array() - to update dimensions\n"
229   "   - modified nifti_makehdrname() and nifti_makeimgname():\n"
230   "       if prefix has a valid extension, use it (else make one up)\n"
231   "   - added nifti_get_intlist - for making an array of ints\n"
232   "   - fixed init of NBL->bsize in nifti_alloc_NBL_mem()  {thanks, Bob}\n"
233   "\n",
234   "1.8  14 April 2005 [rickr]\n"
235   "   - added nifti_set_type_from_names(), for nifti_set_filenames()\n"
236   "     (only updates type if number of files does not match it)\n"
237   "   - added is_valid_nifti_type(), just to be sure\n"
238   "   - updated description of nifti_read_collapsed_image() for *data change\n"
239   "     (if *data is already set, assume memory exists for results)\n"
240   "   - modified rci_alloc_mem() to allocate only if *data is NULL\n"
241   "\n",
242   "1.9  19 April 2005 [rickr]\n"
243   "   - added extension codes NIFTI_ECODE_COMMENT and NIFTI_ECODE_XCEDE\n"
244   "   - added nifti_type codes NIFTI_MAX_ECODE and NIFTI_MAX_FTYPE\n"
245   "   - added nifti_add_extension() {exported}\n"
246   "   - added nifti_fill_extension() as a static function\n"
247   "   - added nifti_is_valid_ecode() {exported}\n",
248   "   - nifti_type values are now NIFTI_FTYPE_* file codes\n"
249   "   - in nifti_read_extensions(), decrement 'remain' by extender size, 4\n"
250   "   - in nifti_set_iname_offset(), case 1, update if offset differs\n"
251   "   - only output '-d writing nifti file' if debug > 1\n"
252   "\n",
253   "1.10 10 May 2005 [rickr]\n"
254   "   - files are read using ZLIB only if they end in '.gz'\n"
255   "\n",
256   "1.11 12 August 2005 [kate fissell]\n"
257   "   - Kate's 0.2 release packaging, for sourceforge\n"
258   "\n",
259   "1.12 17 August 2005 [rickr] - comment (doxygen) updates\n"
260   "   - updated comments for most functions (2 updates from Cinly Ooi)\n"
261   "   - added nifti_type_and_names_match()\n"
262   "\n",
263   "1.12a 24 August 2005 [rickr] - remove all tabs from Clibs/*/*.[ch]\n",
264   "1.12b 25 August 2005 [rickr] - changes by Hans Johnson\n",
265   "1.13  25 August 2005 [rickr]\n",
266   "   - finished changes by Hans for Insight\n"
267   "   - added const in all appropraite parameter locations (30-40)\n"
268   "     (any pointer referencing data that will not change)\n"
269   "   - shortened all string constants below 509 character limit\n"
270   "1.14  28 October 2005 [HJohnson]\n",
271   "   - use nifti_set_filenames() in nifti_convert_nhdr2nim()\n"
272   "1.15  02 November 2005 [rickr]\n",
273   "   - added skip_blank_ext to nifti_global_options\n"
274   "   - added nifti_set_skip_blank_ext(), to set option\n"
275   "   - if skip_blank_ext and no extensions, do not read/write extender\n"
276   "1.16 18 November 2005 [rickr]\n",
277   "   - removed any test or access of dim[i], i>dim[0]\n"
278   "   - do not set pixdim for collapsed dims to 1.0, leave them as they are\n"
279   "   - added magic and dim[i] tests in nifti_hdr_looks_good()\n"
280   "   - added 2 size_t casts\n"
281   "1.17 22 November 2005 [rickr]\n",
282   "   - in hdr->nim, for i > dim[0], pass 0 or 1, else set to 1\n"
283   "1.18 02 March 2006 [rickr]\n",
284   "   - in nifti_alloc_NBL_mem(), fixed nt=0 case from 1.17 change\n"
285   "1.19 23 May 2006 [HJohnson,rickr]\n",
286   "   - nifti_write_ascii_image(): free(hstr)\n"
287   "   - nifti_copy_extensions(): clear num_ext and ext_list\n"
288   "1.20 27 Jun 2006 [rickr]\n",
289   "   - nifti_findhdrname(): fixed assign of efirst to match stated logic\n"
290   "     (problem found by Atle Bjørnerud)\n"
291   "1.21 05 Sep 2006 [rickr] update for nifticlib-0.4 release\n",
292   "   - was reminded to actually add nifti_set_skip_blank_ext()\n"
293   "   - init g_opts.skip_blank_ext to 0\n"
294   "1.22 01 Jun 2007 nifticlib-0.5 release\n",
295   "1.23 05 Jun 2007 nifti_add_exten_to_list: revert on failure, free old list\n"
296   "1.24 07 Jun 2007 nifti_copy_extensions: use esize-8 for data size\n"
297   "1.25 12 Jun 2007 [rickr] EMPTY_IMAGE creation\n",
298   "   - added nifti_make_new_header() - to create from dims/dtype\n"
299   "   - added nifti_make_new_nim() - to create from dims/dtype/fill\n"
300   "   - added nifti_is_valid_datatype(), and more debug info\n",
301   "1.26 27 Jul 2007 [rickr] handle single volumes > 2^31 bytes (but < 2^32)\n",
302   "1.27 28 Jul 2007 [rickr] nim->nvox, NBL-bsize are now type size_t\n"
303   "1.28 30 Jul 2007 [rickr] size_t updates\n",
304   "1.29 08 Aug 2007 [rickr] for list, valid_nifti_brick_list requires 3 dims\n"
305   "1.30 08 Nov 2007 [Yaroslav/rickr]\n"
306   "   - fix ARM struct alignment problem in byte-swapping routines\n",
307   "1.31 29 Nov 2007 [rickr] for nifticlib-1.0.0\n"
308   "   - added nifti_datatype_to/from_string routines\n"
309   "   - added DT_RGBA32/NIFTI_TYPE_RGBA32 datatype macros (2304)\n"
310   "   - added NIFTI_ECODE_FREESURFER (14)\n",
311   "1.32 08 Dec 2007 [rickr]\n"
312   "   - nifti_hdr_looks_good() allows ANALYZE headers (req. by V. Luccio)\n"
313   "   - added nifti_datatype_is_valid()\n",
314   "1.33 05 Feb 2008 [hansj,rickr] - block nia.gz use\n"
315   "1.34 13 Jun 2008 [rickr] - added nifti_compiled_with_zlib()\n"
316   "1.35 03 Aug 2008 [rickr]\n",
317   "   - deal with swapping, so that CPU type does not affect output\n"
318   "     (motivated by C Burns)\n"
319   "   - added nifti_analyze75 structure and nifti_swap_as_analyze()\n"
320   "   - previous swap_nifti_header is saved as old_swap_nifti_header\n"
321   "   - also swap UNUSED fields in nifti_1_header struct\n",
322   "1.36 07 Oct 2008 [rickr]\n",
323   "   - added nifti_NBL_matches_nim() check for write_bricks()\n"
324   "1.37 10 Mar 2009 [rickr]\n",
325   "   - H Johnson cast updates (06 Feb)\n"
326   "   - added NIFTI_ECODE_PYPICKLE for PyNIfTI (06 Feb)\n"
327   "   - added NIFTI_ECODEs 18-28 for the LONI MiND group\n"
328   "1.38 28 Apr 2009 [rickr]\n",
329   "   - uppercase extensions are now valid (requested by M. Coursolle)\n"
330   "   - nifti_set_allow_upper_fext controls this option (req by C. Ooi)\n"
331   "1.39 23 Jun 2009 [rickr]: added 4 checks of alloc() returns\n",
332   "1.40 16 Mar 2010 [rickr]: added NIFTI_ECODE_VOXBO for D. Kimberg\n",
333   "1.41 28 Apr 2010 [rickr]: added NIFTI_ECODE_CARET for J. Harwell\n",
334   "1.42 06 Jul 2010 [rickr]: trouble with large (gz) files\n",
335   "   - noted/investigated by M Hanke and Y Halchenko\n"
336   "   - fixed znzread/write, noting example by M Adler\n"
337   "   - changed nifti_swap_* routines/calls to take size_t (6)\n"
338   "1.43 07 Jul 2010 [rickr]: fixed znzR/W to again return nmembers\n",
339   "----------------------------------------------------------------------\n"
340 };
341 static char gni_version[] = "nifti library version 1.43 (7 July, 2010)";
342 
343 /*! global nifti options structure - init with defaults */
344 static nifti_global_options g_opts = {
345         1, /* debug level                                         */
346         0, /* skip_blank_ext    - skip extender if no extensions  */
347         1  /* allow_upper_fext  - allow uppercase file extensions */
348 };
349 
350 /*! global nifti types structure list (per type, ordered oldest to newest) */
351 static nifti_type_ele nifti_type_list[] = {
352     /* type  nbyper  swapsize   name  */
353     {    0,     0,       0,   "DT_UNKNOWN"              },
354     {    0,     0,       0,   "DT_NONE"                 },
355     {    1,     0,       0,   "DT_BINARY"               },  /* not usable */
356     {    2,     1,       0,   "DT_UNSIGNED_CHAR"        },
357     {    2,     1,       0,   "DT_UINT8"                },
358     {    2,     1,       0,   "NIFTI_TYPE_UINT8"        },
359     {    4,     2,       2,   "DT_SIGNED_SHORT"         },
360     {    4,     2,       2,   "DT_INT16"                },
361     {    4,     2,       2,   "NIFTI_TYPE_INT16"        },
362     {    8,     4,       4,   "DT_SIGNED_INT"           },
363     {    8,     4,       4,   "DT_INT32"                },
364     {    8,     4,       4,   "NIFTI_TYPE_INT32"        },
365     {   16,     4,       4,   "DT_FLOAT"                },
366     {   16,     4,       4,   "DT_FLOAT32"              },
367     {   16,     4,       4,   "NIFTI_TYPE_FLOAT32"      },
368     {   32,     8,       4,   "DT_COMPLEX"              },
369     {   32,     8,       4,   "DT_COMPLEX64"            },
370     {   32,     8,       4,   "NIFTI_TYPE_COMPLEX64"    },
371     {   64,     8,       8,   "DT_DOUBLE"               },
372     {   64,     8,       8,   "DT_FLOAT64"              },
373     {   64,     8,       8,   "NIFTI_TYPE_FLOAT64"      },
374     {  128,     3,       0,   "DT_RGB"                  },
375     {  128,     3,       0,   "DT_RGB24"                },
376     {  128,     3,       0,   "NIFTI_TYPE_RGB24"        },
377     {  255,     0,       0,   "DT_ALL"                  },
378     {  256,     1,       0,   "DT_INT8"                 },
379     {  256,     1,       0,   "NIFTI_TYPE_INT8"         },
380     {  512,     2,       2,   "DT_UINT16"               },
381     {  512,     2,       2,   "NIFTI_TYPE_UINT16"       },
382     {  768,     4,       4,   "DT_UINT32"               },
383     {  768,     4,       4,   "NIFTI_TYPE_UINT32"       },
384     { 1024,     8,       8,   "DT_INT64"                },
385     { 1024,     8,       8,   "NIFTI_TYPE_INT64"        },
386     { 1280,     8,       8,   "DT_UINT64"               },
387     { 1280,     8,       8,   "NIFTI_TYPE_UINT64"       },
388     { 1536,    16,      16,   "DT_FLOAT128"             },
389     { 1536,    16,      16,   "NIFTI_TYPE_FLOAT128"     },
390     { 1792,    16,       8,   "DT_COMPLEX128"           },
391     { 1792,    16,       8,   "NIFTI_TYPE_COMPLEX128"   },
392     { 2048,    32,      16,   "DT_COMPLEX256"           },
393     { 2048,    32,      16,   "NIFTI_TYPE_COMPLEX256"   },
394     { 2304,     4,       0,   "DT_RGBA32"               },
395     { 2304,     4,       0,   "NIFTI_TYPE_RGBA32"       },
396 };
397 
398 /*---------------------------------------------------------------------------*/
399 /* prototypes for internal functions - not part of exported library          */
400 
401 /* extension routines */
402 static int  nifti_read_extensions( nifti_image *nim, znzFile fp, int remain );
403 static int  nifti_read_next_extension( nifti1_extension * nex, nifti_image *nim,                                       int remain, znzFile fp );
404 static int  nifti_check_extension(nifti_image *nim, int size,int code, int rem);
405 static void update_nifti_image_for_brick_list(nifti_image * nim , int nbricks);
406 static int  nifti_add_exten_to_list(nifti1_extension *  new_ext,
407                                     nifti1_extension ** list, int new_length);
408 static int  nifti_fill_extension(nifti1_extension * ext, const char * data,
409                                  int len, int ecode);
410 
411 /* NBL routines */
412 static int  nifti_load_NBL_bricks(nifti_image * nim , int * slist, int * sindex,                                  nifti_brick_list * NBL, znzFile fp );
413 static int  nifti_alloc_NBL_mem(  nifti_image * nim, int nbricks,
414                                   nifti_brick_list * nbl);
415 static int  nifti_copynsort(int nbricks, const int *blist, int **slist,
416                             int **sindex);
417 static int  nifti_NBL_matches_nim(const nifti_image *nim,
418                                   const nifti_brick_list *NBL);
419 
420 /* for nifti_read_collapsed_image: */
421 static int  rci_read_data(nifti_image *nim, int *pivots, int *prods, int nprods,
422                   const int dims[], char *data, znzFile fp, size_t base_offset);
423 static int  rci_alloc_mem(void ** data, int prods[8], int nprods, int nbyper );
424 static int  make_pivot_list(nifti_image * nim, const int dims[], int pivots[],
425                             int prods[], int * nprods );
426 
427 /* misc */
428 static int   compare_strlist   (const char * str, char ** strlist, int len);
429 static int   fileext_compare   (const char * test_ext, const char * known_ext);
430 static int   fileext_n_compare (const char * test_ext,
431                                 const char * known_ext, int maxlen);
432 static int   is_mixedcase      (const char * str);
433 static int   is_uppercase      (const char * str);
434 static int   make_lowercase    (char * str);
435 static int   make_uppercase    (char * str);
436 static int   need_nhdr_swap    (short dim0, int hdrsize);
437 static int   print_hex_vals    (const char * data, int nbytes, FILE * fp);
438 static int   unescape_string   (char *str);  /* string utility functions */
439 static char *escapize_string   (const char *str);
440 
441 /* internal I/O routines */
442 static znzFile nifti_image_load_prep( nifti_image *nim );
443 static int     has_ascii_header(znzFile fp);
444 /*---------------------------------------------------------------------------*/
445 
446 
447 /* for calling from some main program */
448 
449 /*----------------------------------------------------------------------*/
450 /*! display the nifti library module history (via stdout)
451 *//*--------------------------------------------------------------------*/
nifti_disp_lib_hist(void)452 void nifti_disp_lib_hist( void )
453 {
454    int c, len = sizeof(gni_history)/sizeof(char *);
455    for( c = 0; c < len; c++ )
456        fputs(gni_history[c], stdout);
457 }
458 
459 /*----------------------------------------------------------------------*/
460 /*! display the nifti library version (via stdout)
461 *//*--------------------------------------------------------------------*/
nifti_disp_lib_version(void)462 void nifti_disp_lib_version( void )
463 {
464    printf("%s, compiled %s\n", gni_version, __DATE__);
465 }
466 
467 
468 /*----------------------------------------------------------------------*/
469 /*! nifti_image_read_bricks        - read nifti data as array of bricks
470  *
471  *                                   13 Dec 2004 [rickr]
472  *
473  *  \param  hname    - filename of dataset to read (must be valid)
474  *  \param  nbricks  - number of sub-bricks to read
475  *                     (if blist is valid, nbricks must be > 0)
476  *  \param  blist    - list of sub-bricks to read
477  *                     (can be NULL; if NULL, read complete dataset)
478  *  \param  NBL      - pointer to empty nifti_brick_list struct
479  *                     (must be a valid pointer)
480  *
481  *  \return
482  *     <br> nim      - same as nifti_image_read, but
483  *                          nim->nt       = NBL->nbricks (or nt*nu*nv*nw)
484  *                          nim->nu,nv,nw = 1
485  *                          nim->data     = NULL
486  *     <br> NBL      - filled with data volumes
487  *
488  * By default, this function will read the nifti dataset and break the data
489  * into a list of nt*nu*nv*nw sub-bricks, each having size nx*ny*nz elements.
490  * That is to say, instead of reading the entire dataset as a single array,
491  * break it up into sub-bricks (volumes), each of size nx*ny*nz elements.
492  *
493  * Note: in the returned nifti_image, nu, nv and nw will always be 1.  The
494  *       intention of this function is to collapse the dataset into a single
495  *       array of volumes (of length nbricks or nt*nu*nv*nw).
496  *
497  * If 'blist' is valid, it is taken to be a list of sub-bricks, of length
498  * 'nbricks'.  The data will still be separated into sub-bricks of size
499  * nx*ny*nz elements, but now 'nbricks' sub-bricks will be returned, of the
500  * caller's choosing via 'blist'.
501  *
502  * E.g. consider a dataset with 12 sub-bricks (numbered 0..11), and the
503  * following code:
504  *
505  * <pre>
506  * { nifti_brick_list   NB_orig, NB_select;
507  *   nifti_image      * nim_orig, * nim_select;
508  *   int                blist[5] = { 7, 0, 5, 5, 9 };
509  *
510  *   nim_orig   = nifti_image_read_bricks("myfile.nii", 0, NULL,  &NB_orig);
511  *   nim_select = nifti_image_read_bricks("myfile.nii", 5, blist, &NB_select);
512  * }
513  * </pre>
514  *
515  * Here, nim_orig gets the entire dataset, where NB_orig.nbricks = 12.  But
516  * nim_select has NB_select.nbricks = 5.
517  *
518  * Note that the first case is not quite the same as just calling the
519  * nifti_image_read function, as here the data is separated into sub-bricks.
520  *
521  * Note that valid blist elements are in [0..nt*nu*nv*nw-1],
522  * or written [ 0 .. (dim[4]*dim[5]*dim[6]*dim[7] - 1) ].
523  *
524  * Note that, as is the case with all of the reading functions, the
525  * data will be allocated, read in, and properly byte-swapped, if
526  * necessary.
527  *
528  * \sa nifti_image_load_bricks, nifti_free_NBL, valid_nifti_brick_list,
529        nifti_image_read
530 *//*----------------------------------------------------------------------*/
nifti_image_read_bricks(const char * hname,int nbricks,const int * blist,nifti_brick_list * NBL)531 nifti_image *nifti_image_read_bricks(const char * hname, int nbricks,
532                                      const int * blist, nifti_brick_list * NBL)
533 {
534    nifti_image * nim;
535 
536    if( !hname || !NBL ){
537       fprintf(stderr,"** nifti_image_read_bricks: bad params (%p,%p)\n",
538               hname, (void *)NBL);
539       return NULL;
540    }
541 
542    if( blist && nbricks <= 0 ){
543       fprintf(stderr,"** nifti_image_read_bricks: bad nbricks, %d\n", nbricks);
544       return NULL;
545    }
546 
547    nim = nifti_image_read(hname, 0);  /* read header, but not data */
548 
549    if( !nim ) return NULL;   /* errors were already printed */
550 
551    /* if we fail, free image and return */
552    if( nifti_image_load_bricks(nim, nbricks, blist, NBL) <= 0 ){
553       nifti_image_free(nim);
554       return NULL;
555    }
556 
557    if( blist ) update_nifti_image_for_brick_list(nim, nbricks);
558 
559    return nim;
560 }
561 
562 
563 /*----------------------------------------------------------------------
564  * update_nifti_image_for_brick_list  - update nifti_image
565  *
566  * When loading a specific brick list, the distinction between
567  * nt, nu, nv and nw is lost.  So put everything in t, and set
568  * dim[0] = 4.
569  *----------------------------------------------------------------------*/
update_nifti_image_for_brick_list(nifti_image * nim,int nbricks)570 static void update_nifti_image_for_brick_list( nifti_image * nim , int nbricks )
571 {
572    int ndim;
573 
574    if( g_opts.debug > 2 ){
575       fprintf(stderr,"+d updating image dimensions for %d bricks in list\n",
576               nbricks);
577       fprintf(stderr,"   ndim = %d\n",nim->ndim);
578       fprintf(stderr,"   nx,ny,nz,nt,nu,nv,nw: (%d,%d,%d,%d,%d,%d,%d)\n",
579               nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw);
580    }
581 
582    nim->nt = nbricks;
583    nim->nu = nim->nv = nim->nw = 1;
584    nim->dim[4] = nbricks;
585    nim->dim[5] = nim->dim[6] = nim->dim[7] = 1;
586 
587    /* compute nvox                                                       */
588    /* do not rely on dimensions above dim[0]         16 Nov 2005 [rickr] */
589    for( nim->nvox = 1, ndim = 1; ndim <= nim->dim[0]; ndim++ )
590       nim->nvox *= nim->dim[ndim];
591 
592    /* update the dimensions to 4 or lower */
593    for( ndim = 4; (ndim > 1) && (nim->dim[ndim] <= 1); ndim-- )
594        ;
595 
596    if( g_opts.debug > 2 ){
597       fprintf(stderr,"+d ndim = %d -> %d\n",nim->ndim, ndim);
598       fprintf(stderr," --> (%d,%d,%d,%d,%d,%d,%d)\n",
599               nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw);
600    }
601 
602    nim->dim[0] = nim->ndim = ndim;
603 }
604 
605 
606 /*----------------------------------------------------------------------*/
607 /*! nifti_update_dims_from_array  - update nx, ny, ... from nim->dim[]
608 
609     Fix all the dimension information, based on a new nim->dim[].
610 
611     Note: we assume that dim[0] will not increase.
612 
613     Check for updates to pixdim[], dx,...,  nx,..., nvox, ndim, dim[0].
614 *//*--------------------------------------------------------------------*/
nifti_update_dims_from_array(nifti_image * nim)615 int nifti_update_dims_from_array( nifti_image * nim )
616 {
617    int c, ndim;
618 
619    if( !nim ){
620       fprintf(stderr,"** update_dims: missing nim\n");
621       return 1;
622    }
623 
624    if( g_opts.debug > 2 ){
625       fprintf(stderr,"+d updating image dimensions given nim->dim:");
626       for( c = 0; c < 8; c++ ) fprintf(stderr," %d", nim->dim[c]);
627       fputc('\n',stderr);
628    }
629 
630    /* verify dim[0] first */
631    if(nim->dim[0] < 1 || nim->dim[0] > 7){
632       fprintf(stderr,"** invalid dim[0], dim[] = ");
633       for( c = 0; c < 8; c++ ) fprintf(stderr," %d", nim->dim[c]);
634       fputc('\n',stderr);
635       return 1;
636    }
637 
638    /* set nx, ny ..., dx, dy, ..., one by one */
639 
640    /* less than 1, set to 1, else copy */
641    if(nim->dim[1] < 1) nim->nx = nim->dim[1] = 1;
642    else                nim->nx = nim->dim[1];
643    nim->dx = nim->pixdim[1];
644 
645    /* if undefined, or less than 1, set to 1 */
646    if(nim->dim[0] < 2 || (nim->dim[0] >= 2 && nim->dim[2] < 1))
647       nim->ny = nim->dim[2] = 1;
648    else
649       nim->ny = nim->dim[2];
650    /* copy delta values, in any case */
651    nim->dy = nim->pixdim[2];
652 
653    if(nim->dim[0] < 3 || (nim->dim[0] >= 3 && nim->dim[3] < 1))
654       nim->nz = nim->dim[3] = 1;
655    else /* just copy vals from arrays */
656       nim->nz = nim->dim[3];
657    nim->dz = nim->pixdim[3];
658 
659    if(nim->dim[0] < 4 || (nim->dim[0] >= 4 && nim->dim[4] < 1))
660       nim->nt = nim->dim[4] = 1;
661    else /* just copy vals from arrays */
662       nim->nt = nim->dim[4];
663    nim->dt = nim->pixdim[4];
664 
665    if(nim->dim[0] < 5 || (nim->dim[0] >= 5 && nim->dim[5] < 1))
666       nim->nu = nim->dim[5] = 1;
667    else /* just copy vals from arrays */
668       nim->nu = nim->dim[5];
669    nim->du = nim->pixdim[5];
670 
671    if(nim->dim[0] < 6 || (nim->dim[0] >= 6 && nim->dim[6] < 1))
672       nim->nv = nim->dim[6] = 1;
673    else /* just copy vals from arrays */
674       nim->nv = nim->dim[6];
675    nim->dv = nim->pixdim[6];
676 
677    if(nim->dim[0] < 7 || (nim->dim[0] >= 7 && nim->dim[7] < 1))
678       nim->nw = nim->dim[7] = 1;
679    else /* just copy vals from arrays */
680       nim->nw = nim->dim[7];
681    nim->dw = nim->pixdim[7];
682 
683    for( c = 1, nim->nvox = 1; c <= nim->dim[0]; c++ )
684       nim->nvox *= nim->dim[c];
685 
686    /* compute ndim, assuming it can be no larger than the old one */
687    for( ndim = nim->dim[0]; (ndim > 1) && (nim->dim[ndim] <= 1); ndim-- )
688        ;
689 
690    if( g_opts.debug > 2 ){
691       fprintf(stderr,"+d ndim = %d -> %d\n",nim->ndim, ndim);
692       fprintf(stderr," --> (%d,%d,%d,%d,%d,%d,%d)\n",
693               nim->nx, nim->ny, nim->nz, nim->nt, nim->nu, nim->nv, nim->nw);
694    }
695 
696    nim->dim[0] = nim->ndim = ndim;
697 
698    return 0;
699 }
700 
701 
702 /*----------------------------------------------------------------------*/
703 /*! Load the image data from disk into an already-prepared image struct.
704  *
705  * \param    nim      - initialized nifti_image, without data
706  * \param    nbricks  - the length of blist (must be 0 if blist is NULL)
707  * \param    blist    - an array of xyz volume indices to read (can be NULL)
708  * \param    NBL      - pointer to struct where resulting data will be stored
709  *
710  * If blist is NULL, read all sub-bricks.
711  *
712  * \return the number of loaded bricks (NBL->nbricks),
713  *    0 on failure, < 0 on error
714  *
715  * NOTE: it is likely that another function will copy the data pointers
716  *       out of NBL, in which case the only pointer the calling function
717  *       will want to free is NBL->bricks (not each NBL->bricks[i]).
718 *//*--------------------------------------------------------------------*/
nifti_image_load_bricks(nifti_image * nim,int nbricks,const int * blist,nifti_brick_list * NBL)719 int nifti_image_load_bricks( nifti_image * nim , int nbricks,
720                              const int * blist, nifti_brick_list * NBL )
721 {
722    int     * slist = NULL, * sindex = NULL, rv;
723    znzFile   fp;
724 
725    /* we can have blist == NULL */
726    if( !nim || !NBL ){
727       fprintf(stderr,"** nifti_image_load_bricks, bad params (%p,%p)\n",
728               (void *)nim, (void *)NBL);
729       return -1;
730    }
731 
732    if( blist && nbricks <= 0 ){
733       if( g_opts.debug > 1 )
734          fprintf(stderr,"-d load_bricks: received blist with nbricks = %d,"
735                         "ignoring blist\n", nbricks);
736       blist = NULL; /* pretend nothing was passed */
737    }
738 
739    if( blist && ! valid_nifti_brick_list(nim, nbricks, blist, g_opts.debug>0) )
740       return -1;
741 
742    /* for efficiency, let's read the file in order */
743    if( blist && nifti_copynsort( nbricks, blist, &slist, &sindex ) != 0 )
744       return -1;
745 
746    /* open the file and position the FILE pointer */
747    fp = nifti_image_load_prep( nim );
748    if( !fp ){
749       if( g_opts.debug > 0 )
750          fprintf(stderr,"** nifti_image_load_bricks, failed load_prep\n");
751       if( blist ){ free(slist); free(sindex); }
752       return -1;
753    }
754 
755    /* this will flag to allocate defaults */
756    if( !blist ) nbricks = 0;
757    if( nifti_alloc_NBL_mem( nim, nbricks, NBL ) != 0 ){
758       if( blist ){ free(slist); free(sindex); }
759       znzclose(fp);
760       return -1;
761    }
762 
763    rv = nifti_load_NBL_bricks(nim, slist, sindex, NBL, fp);
764 
765    if( rv != 0 ){
766       nifti_free_NBL( NBL );  /* failure! */
767       NBL->nbricks = 0; /* repetative, but clear */
768    }
769 
770    if( slist ){ free(slist); free(sindex); }
771 
772    znzclose(fp);
773 
774    return NBL->nbricks;
775 }
776 
777 
778 /*----------------------------------------------------------------------*/
779 /*! nifti_free_NBL      - free all pointers and clear structure
780  *
781  * note: this does not presume to free the structure pointer
782 *//*--------------------------------------------------------------------*/
nifti_free_NBL(nifti_brick_list * NBL)783 void nifti_free_NBL( nifti_brick_list * NBL )
784 {
785    int c;
786 
787    if( NBL->bricks ){
788       for( c = 0; c < NBL->nbricks; c++ )
789          if( NBL->bricks[c] ) free(NBL->bricks[c]);
790       free(NBL->bricks);
791       NBL->bricks = NULL;
792    }
793 
794    NBL->bsize = NBL->nbricks = 0;
795 }
796 
797 
798 /*----------------------------------------------------------------------
799  * nifti_load_NBL_bricks      - read the file data into the NBL struct
800  *
801  * return 0 on success, -1 on failure
802  *----------------------------------------------------------------------*/
nifti_load_NBL_bricks(nifti_image * nim,int * slist,int * sindex,nifti_brick_list * NBL,znzFile fp)803 static int nifti_load_NBL_bricks( nifti_image * nim , int * slist, int * sindex,
804                                   nifti_brick_list * NBL, znzFile fp )
805 {
806    size_t oposn, fposn;      /* orig and current file positions */
807    size_t rv;
808    long   test;
809    int    c;
810    int    prev, isrc, idest; /* previous and current sub-brick, and new index */
811 
812    test = znztell(fp);  /* store current file position */
813    if( test < 0 ){
814       fprintf(stderr,"** load bricks: ztell failed??\n");
815       return -1;
816    }
817    fposn = oposn = test;
818 
819    /* first, handle the default case, no passed blist */
820    if( !slist ){
821       for( c = 0; c < NBL->nbricks; c++ ) {
822          rv = nifti_read_buffer(fp, NBL->bricks[c], NBL->bsize, nim);
823          if( rv != NBL->bsize ){
824             fprintf(stderr,"** load bricks: cannot read brick %d from '%s'\n",
825                     c, nim->iname ? nim->iname : nim->fname);
826             return -1;
827          }
828       }
829       if( g_opts.debug > 1 )
830          fprintf(stderr,"+d read %d default %u-byte bricks from file %s\n",
831                  NBL->nbricks, (unsigned int)NBL->bsize,
832                  nim->iname ? nim->iname:nim->fname );
833       return 0;
834    }
835 
836    if( !sindex ){
837       fprintf(stderr,"** load_NBL_bricks: missing index list\n");
838       return -1;
839    }
840 
841    prev = -1;   /* use prev for previous sub-brick */
842    for( c = 0; c < NBL->nbricks; c++ ){
843        isrc = slist[c];   /* this is original brick index (c is new one) */
844        idest = sindex[c]; /* this is the destination index for this data */
845 
846        /* if this sub-brick is not the previous, we must read from disk */
847        if( isrc != prev ){
848 
849           /* if we are not looking at the correct sub-brick, scan forward */
850           if( fposn != (oposn + isrc*NBL->bsize) ){
851              fposn = oposn + isrc*NBL->bsize;
852              if( znzseek(fp, (long)fposn, SEEK_SET) < 0 ){
853                 fprintf(stderr,"** failed to locate brick %d in file '%s'\n",
854                         isrc, nim->iname ? nim->iname : nim->fname);
855                 return -1;
856              }
857           }
858 
859           /* only 10,000 lines later and we're actually reading something! */
860           rv = nifti_read_buffer(fp, NBL->bricks[idest], NBL->bsize, nim);
861           if( rv != NBL->bsize ){
862              fprintf(stderr,"** failed to read brick %d from file '%s'\n",
863                      isrc, nim->iname ? nim->iname : nim->fname);
864              if( g_opts.debug > 1 )
865                 fprintf(stderr,"   (read %u of %u bytes)\n",
866                         (unsigned int)rv, (unsigned int)NBL->bsize);
867              return -1;
868           }
869           fposn += NBL->bsize;
870        } else {
871           /* we have already read this sub-brick, just copy the previous one */
872           /* note that this works because they are sorted */
873           memcpy(NBL->bricks[idest], NBL->bricks[sindex[c-1]], NBL->bsize);
874        }
875 
876        prev = isrc;  /* in any case, note the now previous sub-brick */
877    }
878 
879    return 0;
880 }
881 
882 
883 /*----------------------------------------------------------------------
884  * nifti_alloc_NBL_mem      - allocate memory for bricks
885  *
886  * return 0 on success, -1 on failure
887  *----------------------------------------------------------------------*/
nifti_alloc_NBL_mem(nifti_image * nim,int nbricks,nifti_brick_list * nbl)888 static int nifti_alloc_NBL_mem(nifti_image * nim, int nbricks,
889                                nifti_brick_list * nbl)
890 {
891    int c;
892 
893    /* if nbricks is not specified, use the default */
894    if( nbricks > 0 ) nbl->nbricks = nbricks;
895    else {  /* I missed this one with the 1.17 change    02 Mar 2006 [rickr] */
896       nbl->nbricks = 1;
897       for( c = 4; c <= nim->ndim; c++ )
898           nbl->nbricks *= nim->dim[c];
899    }
900 
901    nbl->bsize   = (size_t)nim->nx * nim->ny * nim->nz * nim->nbyper;/* bytes */
902    nbl->bricks  = (void **)malloc(nbl->nbricks * sizeof(void *));
903 
904    if( ! nbl->bricks ){
905       fprintf(stderr,"** NANM: failed to alloc %d void ptrs\n",nbricks);
906       return -1;
907    }
908 
909    for( c = 0; c < nbl->nbricks; c++ ){
910       nbl->bricks[c] = (void *)malloc(nbl->bsize);
911       if( ! nbl->bricks[c] ){
912          fprintf(stderr,"** NANM: failed to alloc %u bytes for brick %d\n",
913                  (unsigned int)nbl->bsize, c);
914          /* so free and clear everything before returning */
915          while( c > 0 ){
916             c--;
917             free(nbl->bricks[c]);
918          }
919          free(nbl->bricks);
920          nbl->bricks = NULL;
921          nbl->bsize = nbl->nbricks = 0;
922          return -1;
923       }
924    }
925 
926    if( g_opts.debug > 2 )
927       fprintf(stderr,"+d NANM: alloc'd %d bricks of %u bytes for NBL\n",
928               nbl->nbricks, (unsigned int)nbl->bsize);
929 
930    return 0;
931 }
932 
933 
934 /*----------------------------------------------------------------------
935  * nifti_copynsort      - copy int list, and sort with indices
936  *
937  * 1. duplicate the incoming list
938  * 2. create an sindex list, and init with 0..nbricks-1
939  * 3. do a slow insertion sort on the small slist, along with sindex list
940  * 4. check results, just to be positive
941  *
942  * So slist is sorted, and sindex hold original positions.
943  *
944  * return 0 on success, -1 on failure
945  *----------------------------------------------------------------------*/
nifti_copynsort(int nbricks,const int * blist,int ** slist,int ** sindex)946 static int nifti_copynsort(int nbricks, const int * blist, int ** slist,
947                            int ** sindex)
948 {
949    int * stmp, * itmp;   /* for ease of typing/reading */
950    int   c1, c2, spos, tmp;
951 
952    *slist  = (int *)malloc(nbricks * sizeof(int));
953    *sindex = (int *)malloc(nbricks * sizeof(int));
954 
955    if( !*slist || !*sindex ){
956       fprintf(stderr,"** NCS: failed to alloc %d ints for sorting\n",nbricks);
957       if(*slist)  free(*slist);   /* maybe one succeeded */
958       if(*sindex) free(*sindex);
959       return -1;
960    }
961 
962    /* init the lists */
963    memcpy(*slist, blist, nbricks*sizeof(int));
964    for( c1 = 0; c1 < nbricks; c1++ ) (*sindex)[c1] = c1;
965 
966    /* now actually sort slist */
967    stmp = *slist;
968    itmp = *sindex;
969    for( c1 = 0; c1 < nbricks-1; c1++ ) {
970       /* find smallest value, init to current */
971       spos = c1;
972       for( c2 = c1+1; c2 < nbricks; c2++ )
973          if( stmp[c2] < stmp[spos] ) spos = c2;
974       if( spos != c1 ) /* swap: fine, don't maintain sub-order, see if I care */
975       {
976          tmp        = stmp[c1];      /* first swap the sorting values */
977          stmp[c1]   = stmp[spos];
978          stmp[spos] = tmp;
979 
980          tmp        = itmp[c1];      /* then swap the index values */
981          itmp[c1]   = itmp[spos];
982          itmp[spos] = tmp;
983       }
984    }
985 
986    if( g_opts.debug > 2 ){
987       fprintf(stderr,  "+d sorted indexing list:\n");
988       fprintf(stderr,  "  orig   : ");
989       for( c1 = 0; c1 < nbricks; c1++ ) fprintf(stderr,"  %d",blist[c1]);
990       fprintf(stderr,"\n  new    : ");
991       for( c1 = 0; c1 < nbricks; c1++ ) fprintf(stderr,"  %d",stmp[c1]);
992       fprintf(stderr,"\n  indices: ");
993       for( c1 = 0; c1 < nbricks; c1++ ) fprintf(stderr,"  %d",itmp[c1]);
994       fputc('\n', stderr);
995    }
996 
997    /* check the sort (why not?  I've got time...) */
998    for( c1 = 0; c1 < nbricks-1; c1++ ){
999        if( (stmp[c1] > stmp[c1+1]) || (blist[itmp[c1]] != stmp[c1]) ){
1000           fprintf(stderr,"** sorting screw-up, way to go, rick!\n");
1001           free(stmp); free(itmp); *slist = NULL; *sindex = NULL;
1002           return -1;
1003        }
1004    }
1005 
1006    if( g_opts.debug > 2 ) fprintf(stderr,"-d sorting is okay\n");
1007 
1008    return 0;
1009 }
1010 
1011 
1012 /*----------------------------------------------------------------------*/
1013 /*! valid_nifti_brick_list      - check sub-brick list for image
1014  *
1015  * This function verifies that nbricks and blist are appropriate
1016  * for use with this nim, based on the dimensions.
1017  *
1018  * \param nim        nifti_image to check against
1019  * \param nbricks    number of brick indices in blist
1020  * \param blist      list of brick indices to check in nim
1021  * \param disp_error if this flag is set, report errors to user
1022  *
1023  * \return 1 if valid, 0 if not
1024 *//*--------------------------------------------------------------------*/
valid_nifti_brick_list(nifti_image * nim,int nbricks,const int * blist,int disp_error)1025 int valid_nifti_brick_list(nifti_image * nim , int nbricks,
1026                            const int * blist, int disp_error)
1027 {
1028    int c, nsubs;
1029 
1030    if( !nim ){
1031       if( disp_error || g_opts.debug > 0 )
1032          fprintf(stderr,"** valid_nifti_brick_list: missing nifti image\n");
1033       return 0;
1034    }
1035 
1036    if( nbricks <= 0 || !blist ){
1037       if( disp_error || g_opts.debug > 1 )
1038          fprintf(stderr,"** valid_nifti_brick_list: no brick list to check\n");
1039       return 0;
1040    }
1041 
1042    if( nim->dim[0] < 3 ){
1043       if( disp_error || g_opts.debug > 1 )
1044          fprintf(stderr,"** cannot read explict brick list from %d-D dataset\n",
1045                  nim->dim[0]);
1046       return 0;
1047    }
1048 
1049    /* nsubs sub-brick is nt*nu*nv*nw */
1050    for( c = 4, nsubs = 1; c <= nim->dim[0]; c++ )
1051       nsubs *= nim->dim[c];
1052 
1053    if( nsubs <= 0 ){
1054       fprintf(stderr,"** VNBL warning: bad dim list (%d,%d,%d,%d)\n",
1055                      nim->dim[4], nim->dim[5], nim->dim[6], nim->dim[7]);
1056       return 0;
1057    }
1058 
1059    for( c = 0; c < nbricks; c++ )
1060       if( (blist[c] < 0) || (blist[c] >= nsubs) ){
1061          if( disp_error || g_opts.debug > 1 )
1062             fprintf(stderr,
1063                "** volume index %d (#%d) is out of range [0,%d]\n",
1064                blist[c], c, nsubs-1);
1065          return 0;
1066       }
1067 
1068    return 1;  /* all is well */
1069 }
1070 
1071 /*----------------------------------------------------------------------*/
1072 /* verify that NBL struct is a valid data source for the image
1073  *
1074  * return 1 if so, 0 otherwise
1075 *//*--------------------------------------------------------------------*/
nifti_NBL_matches_nim(const nifti_image * nim,const nifti_brick_list * NBL)1076 static int nifti_NBL_matches_nim(const nifti_image *nim,
1077                                  const nifti_brick_list *NBL)
1078 {
1079    size_t volbytes = 0;     /* bytes per volume */
1080    int    ind, errs = 0, nvols = 0;
1081 
1082 
1083    if( !nim || !NBL ) {
1084       if( g_opts.debug > 0 )
1085          fprintf(stderr,"** nifti_NBL_matches_nim: NULL pointer(s)\n");
1086       return 0;
1087    }
1088 
1089    /* for nim, compute volbytes and nvols */
1090    if( nim->ndim > 0 ) {
1091       /* first 3 indices are over a single volume */
1092       volbytes = (size_t)nim->nbyper;
1093       for( ind = 1; ind <= nim->ndim && ind < 4; ind++ )
1094          volbytes *= (size_t)nim->dim[ind];
1095 
1096       for( ind = 4, nvols = 1; ind <= nim->ndim; ind++ )
1097          nvols *= nim->dim[ind];
1098    }
1099 
1100    if( volbytes != NBL->bsize ) {
1101       if( g_opts.debug > 1 )
1102          fprintf(stderr,"** NBL/nim mismatch, volbytes = %u, %u\n",
1103                  (unsigned)NBL->bsize, (unsigned)volbytes);
1104       errs++;
1105    }
1106 
1107    if( nvols != NBL->nbricks ) {
1108       if( g_opts.debug > 1 )
1109          fprintf(stderr,"** NBL/nim mismatch, nvols = %d, %d\n",
1110                  NBL->nbricks, nvols);
1111       errs++;
1112    }
1113 
1114    if( errs ) return 0;
1115    else if ( g_opts.debug > 2 )
1116       fprintf(stderr,"-- nim/NBL agree: nvols = %d, nbytes = %u\n",
1117               nvols, (unsigned)volbytes);
1118 
1119    return 1;
1120 }
1121 
1122 /* end of new nifti_image_read_bricks() functionality */
1123 
1124 /*----------------------------------------------------------------------*/
1125 /*! display the orientation from the quaternian fields
1126  *
1127  * \param mesg if non-NULL, display this message first
1128  * \param mat  the matrix to convert to "nearest" orientation
1129  *
1130  * \return -1 if results cannot be determined, 0 if okay
1131 *//*--------------------------------------------------------------------*/
nifti_disp_matrix_orient(const char * mesg,mat44 mat)1132 int nifti_disp_matrix_orient( const char * mesg, mat44 mat )
1133 {
1134    int i, j, k;
1135 
1136    if ( mesg ) fputs( mesg, stderr );  /* use stdout? */
1137 
1138    nifti_mat44_to_orientation( mat, &i,&j,&k );
1139    if ( i <= 0 || j <= 0 || k <= 0 ) return -1;
1140 
1141    /* so we have good codes */
1142    fprintf(stderr, "  i orientation = '%s'\n"
1143                    "  j orientation = '%s'\n"
1144                    "  k orientation = '%s'\n",
1145                    nifti_orientation_string(i),
1146                    nifti_orientation_string(j),
1147                    nifti_orientation_string(k) );
1148    return 0;
1149 }
1150 
1151 
1152 /*----------------------------------------------------------------------*/
1153 /*! duplicate the given string (alloc length+1)
1154  *
1155  * \return allocated pointer (or NULL on failure)
1156 *//*--------------------------------------------------------------------*/
nifti_strdup(const char * str)1157 char *nifti_strdup(const char *str)
1158 {
1159   char *dup;
1160 
1161   if( !str ) return NULL;       /* allow calls passing NULL */
1162 
1163   dup = (char *)malloc(strlen(str) + 1);
1164 
1165   /* check for failure */
1166   if( dup ) strcpy(dup, str);
1167   else      fprintf(stderr,"** nifti_strdup: failed to alloc %u bytes\n",
1168                     (unsigned int)strlen(str)+1);
1169 
1170   return dup;
1171 }
1172 
1173 
1174 /*---------------------------------------------------------------------------*/
1175 /*! Return a pointer to a string holding the name of a NIFTI datatype.
1176 
1177     \param dt NIfTI-1 datatype
1178 
1179     \return pointer to static string holding the datatype name
1180 
1181     \warning Do not free() or modify this string!
1182              It points to static storage.
1183 
1184     \sa NIFTI1_DATATYPES group in nifti1.h
1185 *//*-------------------------------------------------------------------------*/
nifti_datatype_string(int dt)1186 char *nifti_datatype_string( int dt )
1187 {
1188    switch( dt ){
1189      case DT_UNKNOWN:    return "UNKNOWN"    ;
1190      case DT_BINARY:     return "BINARY"     ;
1191      case DT_INT8:       return "INT8"       ;
1192      case DT_UINT8:      return "UINT8"      ;
1193      case DT_INT16:      return "INT16"      ;
1194      case DT_UINT16:     return "UINT16"     ;
1195      case DT_INT32:      return "INT32"      ;
1196      case DT_UINT32:     return "UINT32"     ;
1197      case DT_INT64:      return "INT64"      ;
1198      case DT_UINT64:     return "UINT64"     ;
1199      case DT_FLOAT32:    return "FLOAT32"    ;
1200      case DT_FLOAT64:    return "FLOAT64"    ;
1201      case DT_FLOAT128:   return "FLOAT128"   ;
1202      case DT_COMPLEX64:  return "COMPLEX64"  ;
1203      case DT_COMPLEX128: return "COMPLEX128" ;
1204      case DT_COMPLEX256: return "COMPLEX256" ;
1205      case DT_RGB24:      return "RGB24"      ;
1206      case DT_RGBA32:     return "RGBA32"     ;
1207    }
1208    return "**ILLEGAL**" ;
1209 }
1210 
1211 /*----------------------------------------------------------------------*/
1212 /*! Determine if the datatype code dt is an integer type (1=YES, 0=NO).
1213 
1214     \return whether the given NIfTI-1 datatype code is valid
1215 
1216     \sa     NIFTI1_DATATYPES group in nifti1.h
1217 *//*--------------------------------------------------------------------*/
nifti_is_inttype(int dt)1218 int nifti_is_inttype( int dt )
1219 {
1220    switch( dt ){
1221      case DT_UNKNOWN:    return 0 ;
1222      case DT_BINARY:     return 0 ;
1223      case DT_INT8:       return 1 ;
1224      case DT_UINT8:      return 1 ;
1225      case DT_INT16:      return 1 ;
1226      case DT_UINT16:     return 1 ;
1227      case DT_INT32:      return 1 ;
1228      case DT_UINT32:     return 1 ;
1229      case DT_INT64:      return 1 ;
1230      case DT_UINT64:     return 1 ;
1231      case DT_FLOAT32:    return 0 ;
1232      case DT_FLOAT64:    return 0 ;
1233      case DT_FLOAT128:   return 0 ;
1234      case DT_COMPLEX64:  return 0 ;
1235      case DT_COMPLEX128: return 0 ;
1236      case DT_COMPLEX256: return 0 ;
1237      case DT_RGB24:      return 1 ;
1238      case DT_RGBA32:     return 1 ;
1239    }
1240    return 0 ;
1241 }
1242 
1243 /*---------------------------------------------------------------------------*/
1244 /*! Return a pointer to a string holding the name of a NIFTI units type.
1245 
1246     \param  uu NIfTI-1 unit code
1247 
1248     \return pointer to static string for the given unit type
1249 
1250     \warning Do not free() or modify this string!
1251              It points to static storage.
1252 
1253     \sa     NIFTI1_UNITS group in nifti1.h
1254 *//*-------------------------------------------------------------------------*/
nifti_units_string(int uu)1255 char *nifti_units_string( int uu )
1256 {
1257    switch( uu ){
1258      case NIFTI_UNITS_METER:  return "m" ;
1259      case NIFTI_UNITS_MM:     return "mm" ;
1260      case NIFTI_UNITS_MICRON: return "um" ;
1261      case NIFTI_UNITS_SEC:    return "s" ;
1262      case NIFTI_UNITS_MSEC:   return "ms" ;
1263      case NIFTI_UNITS_USEC:   return "us" ;
1264      case NIFTI_UNITS_HZ:     return "Hz" ;
1265      case NIFTI_UNITS_PPM:    return "ppm" ;
1266      case NIFTI_UNITS_RADS:   return "rad/s" ;
1267    }
1268    return "Unknown" ;
1269 }
1270 
1271 /*---------------------------------------------------------------------------*/
1272 /*! Return a pointer to a string holding the name of a NIFTI transform type.
1273 
1274     \param  xx NIfTI-1 xform code
1275 
1276     \return pointer to static string describing xform code
1277 
1278     \warning Do not free() or modify this string!
1279              It points to static storage.
1280 
1281     \sa     NIFTI1_XFORM_CODES group in nifti1.h
1282 *//*-------------------------------------------------------------------------*/
nifti_xform_string(int xx)1283 char *nifti_xform_string( int xx )
1284 {
1285    switch( xx ){
1286      case NIFTI_XFORM_SCANNER_ANAT:  return "Scanner Anat" ;
1287      case NIFTI_XFORM_ALIGNED_ANAT:  return "Aligned Anat" ;
1288      case NIFTI_XFORM_TALAIRACH:     return "Talairach" ;
1289      case NIFTI_XFORM_MNI_152:       return "MNI_152" ;
1290    }
1291    return "Unknown" ;
1292 }
1293 
1294 /*---------------------------------------------------------------------------*/
1295 /*! Return a pointer to a string holding the name of a NIFTI intent type.
1296 
1297     \param  ii NIfTI-1 intent code
1298 
1299     \return pointer to static string describing code
1300 
1301     \warning Do not free() or modify this string!
1302              It points to static storage.
1303 
1304     \sa     NIFTI1_INTENT_CODES group in nifti1.h
1305 *//*-------------------------------------------------------------------------*/
nifti_intent_string(int ii)1306 char *nifti_intent_string( int ii )
1307 {
1308    switch( ii ){
1309      case NIFTI_INTENT_CORREL:     return "Correlation statistic" ;
1310      case NIFTI_INTENT_TTEST:      return "T-statistic" ;
1311      case NIFTI_INTENT_FTEST:      return "F-statistic" ;
1312      case NIFTI_INTENT_ZSCORE:     return "Z-score"     ;
1313      case NIFTI_INTENT_CHISQ:      return "Chi-squared distribution" ;
1314      case NIFTI_INTENT_BETA:       return "Beta distribution" ;
1315      case NIFTI_INTENT_BINOM:      return "Binomial distribution" ;
1316      case NIFTI_INTENT_GAMMA:      return "Gamma distribution" ;
1317      case NIFTI_INTENT_POISSON:    return "Poisson distribution" ;
1318      case NIFTI_INTENT_NORMAL:     return "Normal distribution" ;
1319      case NIFTI_INTENT_FTEST_NONC: return "F-statistic noncentral" ;
1320      case NIFTI_INTENT_CHISQ_NONC: return "Chi-squared noncentral" ;
1321      case NIFTI_INTENT_LOGISTIC:   return "Logistic distribution" ;
1322      case NIFTI_INTENT_LAPLACE:    return "Laplace distribution" ;
1323      case NIFTI_INTENT_UNIFORM:    return "Uniform distribition" ;
1324      case NIFTI_INTENT_TTEST_NONC: return "T-statistic noncentral" ;
1325      case NIFTI_INTENT_WEIBULL:    return "Weibull distribution" ;
1326      case NIFTI_INTENT_CHI:        return "Chi distribution" ;
1327      case NIFTI_INTENT_INVGAUSS:   return "Inverse Gaussian distribution" ;
1328      case NIFTI_INTENT_EXTVAL:     return "Extreme Value distribution" ;
1329      case NIFTI_INTENT_PVAL:       return "P-value" ;
1330 
1331      case NIFTI_INTENT_LOGPVAL:    return "Log P-value" ;
1332      case NIFTI_INTENT_LOG10PVAL:  return "Log10 P-value" ;
1333 
1334      case NIFTI_INTENT_ESTIMATE:   return "Estimate" ;
1335      case NIFTI_INTENT_LABEL:      return "Label index" ;
1336      case NIFTI_INTENT_NEURONAME:  return "NeuroNames index" ;
1337      case NIFTI_INTENT_GENMATRIX:  return "General matrix" ;
1338      case NIFTI_INTENT_SYMMATRIX:  return "Symmetric matrix" ;
1339      case NIFTI_INTENT_DISPVECT:   return "Displacement vector" ;
1340      case NIFTI_INTENT_VECTOR:     return "Vector" ;
1341      case NIFTI_INTENT_POINTSET:   return "Pointset" ;
1342      case NIFTI_INTENT_TRIANGLE:   return "Triangle" ;
1343      case NIFTI_INTENT_QUATERNION: return "Quaternion" ;
1344 
1345      case NIFTI_INTENT_DIMLESS:    return "Dimensionless number" ;
1346    }
1347    return "Unknown" ;
1348 }
1349 
1350 /*---------------------------------------------------------------------------*/
1351 /*! Return a pointer to a string holding the name of a NIFTI slice_code.
1352 
1353     \param  ss NIfTI-1 slice order code
1354 
1355     \return pointer to static string describing code
1356 
1357     \warning Do not free() or modify this string!
1358              It points to static storage.
1359 
1360     \sa     NIFTI1_SLICE_ORDER group in nifti1.h
1361 *//*-------------------------------------------------------------------------*/
nifti_slice_string(int ss)1362 char *nifti_slice_string( int ss )
1363 {
1364    switch( ss ){
1365      case NIFTI_SLICE_SEQ_INC:  return "sequential_increasing"    ;
1366      case NIFTI_SLICE_SEQ_DEC:  return "sequential_decreasing"    ;
1367      case NIFTI_SLICE_ALT_INC:  return "alternating_increasing"   ;
1368      case NIFTI_SLICE_ALT_DEC:  return "alternating_decreasing"   ;
1369      case NIFTI_SLICE_ALT_INC2: return "alternating_increasing_2" ;
1370      case NIFTI_SLICE_ALT_DEC2: return "alternating_decreasing_2" ;
1371    }
1372    return "Unknown" ;
1373 }
1374 
1375 /*---------------------------------------------------------------------------*/
1376 /*! Return a pointer to a string holding the name of a NIFTI orientation.
1377 
1378     \param ii orientation code
1379 
1380     \return pointer to static string holding the orientation information
1381 
1382     \warning Do not free() or modify the return string!
1383              It points to static storage.
1384 
1385     \sa  NIFTI_L2R in nifti1_io.h
1386 *//*-------------------------------------------------------------------------*/
nifti_orientation_string(int ii)1387 char *nifti_orientation_string( int ii )
1388 {
1389    switch( ii ){
1390      case NIFTI_L2R: return "Left-to-Right" ;
1391      case NIFTI_R2L: return "Right-to-Left" ;
1392      case NIFTI_P2A: return "Posterior-to-Anterior" ;
1393      case NIFTI_A2P: return "Anterior-to-Posterior" ;
1394      case NIFTI_I2S: return "Inferior-to-Superior" ;
1395      case NIFTI_S2I: return "Superior-to-Inferior" ;
1396    }
1397    return "Unknown" ;
1398 }
1399 
1400 /*--------------------------------------------------------------------------*/
1401 /*! Given a datatype code, set number of bytes per voxel and the swapsize.
1402 
1403     \param datatype nifti1 datatype code
1404     \param nbyper   pointer to return value: number of bytes per voxel
1405     \param swapsize pointer to return value: size of swap blocks
1406 
1407     \return appropriate values at nbyper and swapsize
1408 
1409     The swapsize is set to 0 if this datatype doesn't ever need swapping.
1410 
1411     \sa NIFTI1_DATATYPES in nifti1.h
1412 *//*------------------------------------------------------------------------*/
nifti_datatype_sizes(int datatype,int * nbyper,int * swapsize)1413 void nifti_datatype_sizes( int datatype , int *nbyper, int *swapsize )
1414 {
1415    int nb=0, ss=0 ;
1416    switch( datatype ){
1417      case DT_INT8:
1418      case DT_UINT8:       nb =  1 ; ss =  0 ; break ;
1419 
1420      case DT_INT16:
1421      case DT_UINT16:      nb =  2 ; ss =  2 ; break ;
1422 
1423      case DT_RGB24:       nb =  3 ; ss =  0 ; break ;
1424      case DT_RGBA32:      nb =  4 ; ss =  0 ; break ;
1425 
1426      case DT_INT32:
1427      case DT_UINT32:
1428      case DT_FLOAT32:     nb =  4 ; ss =  4 ; break ;
1429 
1430      case DT_COMPLEX64:   nb =  8 ; ss =  4 ; break ;
1431 
1432      case DT_FLOAT64:
1433      case DT_INT64:
1434      case DT_UINT64:      nb =  8 ; ss =  8 ; break ;
1435 
1436      case DT_FLOAT128:    nb = 16 ; ss = 16 ; break ;
1437 
1438      case DT_COMPLEX128:  nb = 16 ; ss =  8 ; break ;
1439 
1440      case DT_COMPLEX256:  nb = 32 ; ss = 16 ; break ;
1441    }
1442 
1443    ASSIF(nbyper,nb) ; ASSIF(swapsize,ss) ; return ;
1444 }
1445 
1446 /*---------------------------------------------------------------------------*/
1447 /*! Given the quaternion parameters (etc.), compute a transformation matrix.
1448 
1449    See comments in nifti1.h for details.
1450      - qb,qc,qd = quaternion parameters
1451      - qx,qy,qz = offset parameters
1452      - dx,dy,dz = grid stepsizes (non-negative inputs are set to 1.0)
1453      - qfac     = sign of dz step (< 0 is negative; >= 0 is positive)
1454 
1455    <pre>
1456    If qx=qy=qz=0, dx=dy=dz=1, then the output is a rotation matrix.
1457    For qfac >= 0, the rotation is proper.
1458    For qfac <  0, the rotation is improper.
1459    </pre>
1460 
1461    \see "QUATERNION REPRESENTATION OF ROTATION MATRIX" in nifti1.h
1462    \see nifti_mat44_to_quatern, nifti_make_orthog_mat44,
1463        nifti_mat44_to_orientation
1464 
1465 *//*-------------------------------------------------------------------------*/
nifti_quatern_to_mat44(float qb,float qc,float qd,float qx,float qy,float qz,float dx,float dy,float dz,float qfac)1466 mat44 nifti_quatern_to_mat44( float qb, float qc, float qd,
1467                               float qx, float qy, float qz,
1468                               float dx, float dy, float dz, float qfac )
1469 {
1470    mat44 R ;
1471    double a,b=qb,c=qc,d=qd , xd,yd,zd ;
1472 
1473    /* last row is always [ 0 0 0 1 ] */
1474 
1475    R.m[3][0]=R.m[3][1]=R.m[3][2] = 0.0 ; R.m[3][3]= 1.0 ;
1476 
1477    /* compute a parameter from b,c,d */
1478 
1479    a = 1.0l - (b*b + c*c + d*d) ;
1480    if( a < 1.e-7l ){                   /* special case */
1481      a = 1.0l / sqrt(b*b+c*c+d*d) ;
1482      b *= a ; c *= a ; d *= a ;        /* normalize (b,c,d) vector */
1483      a = 0.0l ;                        /* a = 0 ==> 180 degree rotation */
1484    } else{
1485      a = sqrt(a) ;                     /* angle = 2*arccos(a) */
1486    }
1487 
1488    /* load rotation matrix, including scaling factors for voxel sizes */
1489 
1490    xd = (dx > 0.0) ? dx : 1.0l ;       /* make sure are positive */
1491    yd = (dy > 0.0) ? dy : 1.0l ;
1492    zd = (dz > 0.0) ? dz : 1.0l ;
1493 
1494    if( qfac < 0.0 ) zd = -zd ;         /* left handedness? */
1495 
1496    R.m[0][0] =        (a*a+b*b-c*c-d*d) * xd ;
1497    R.m[0][1] = 2.0l * (b*c-a*d        ) * yd ;
1498    R.m[0][2] = 2.0l * (b*d+a*c        ) * zd ;
1499    R.m[1][0] = 2.0l * (b*c+a*d        ) * xd ;
1500    R.m[1][1] =        (a*a+c*c-b*b-d*d) * yd ;
1501    R.m[1][2] = 2.0l * (c*d-a*b        ) * zd ;
1502    R.m[2][0] = 2.0l * (b*d-a*c        ) * xd ;
1503    R.m[2][1] = 2.0l * (c*d+a*b        ) * yd ;
1504    R.m[2][2] =        (a*a+d*d-c*c-b*b) * zd ;
1505 
1506    /* load offsets */
1507 
1508    R.m[0][3] = qx ; R.m[1][3] = qy ; R.m[2][3] = qz ;
1509 
1510    return R ;
1511 }
1512 
1513 /*---------------------------------------------------------------------------*/
1514 /*! Given the 3x4 upper corner of the matrix R, compute the quaternion
1515    parameters that fit it.
1516 
1517      - Any NULL pointer on input won't get assigned (e.g., if you don't want
1518        dx,dy,dz, just pass NULL in for those pointers).
1519      - If the 3 input matrix columns are NOT orthogonal, they will be
1520        orthogonalized prior to calculating the parameters, using
1521        the polar decomposition to find the orthogonal matrix closest
1522        to the column-normalized input matrix.
1523      - However, if the 3 input matrix columns are NOT orthogonal, then
1524        the matrix produced by nifti_quatern_to_mat44 WILL have orthogonal
1525        columns, so it won't be the same as the matrix input here.
1526        This "feature" is because the NIFTI 'qform' transform is
1527        deliberately not fully general -- it is intended to model a volume
1528        with perpendicular axes.
1529      - If the 3 input matrix columns are not even linearly independent,
1530        you'll just have to take your luck, won't you?
1531 
1532    \see "QUATERNION REPRESENTATION OF ROTATION MATRIX" in nifti1.h
1533 
1534    \see nifti_quatern_to_mat44, nifti_make_orthog_mat44,
1535        nifti_mat44_to_orientation
1536 *//*-------------------------------------------------------------------------*/
nifti_mat44_to_quatern(mat44 R,float * qb,float * qc,float * qd,float * qx,float * qy,float * qz,float * dx,float * dy,float * dz,float * qfac)1537 void nifti_mat44_to_quatern( mat44 R ,
1538                              float *qb, float *qc, float *qd,
1539                              float *qx, float *qy, float *qz,
1540                              float *dx, float *dy, float *dz, float *qfac )
1541 {
1542    double r11,r12,r13 , r21,r22,r23 , r31,r32,r33 ;
1543    double xd,yd,zd , a,b,c,d ;
1544    mat33 P,Q ;
1545 
1546    /* offset outputs are read write out of input matrix  */
1547 
1548    ASSIF(qx,R.m[0][3]) ; ASSIF(qy,R.m[1][3]) ; ASSIF(qz,R.m[2][3]) ;
1549 
1550    /* load 3x3 matrix into local variables */
1551 
1552    r11 = R.m[0][0] ; r12 = R.m[0][1] ; r13 = R.m[0][2] ;
1553    r21 = R.m[1][0] ; r22 = R.m[1][1] ; r23 = R.m[1][2] ;
1554    r31 = R.m[2][0] ; r32 = R.m[2][1] ; r33 = R.m[2][2] ;
1555 
1556    /* compute lengths of each column; these determine grid spacings  */
1557 
1558    xd = sqrt( r11*r11 + r21*r21 + r31*r31 ) ;
1559    yd = sqrt( r12*r12 + r22*r22 + r32*r32 ) ;
1560    zd = sqrt( r13*r13 + r23*r23 + r33*r33 ) ;
1561 
1562    /* if a column length is zero, patch the trouble */
1563 
1564    if( xd == 0.0l ){ r11 = 1.0l ; r21 = r31 = 0.0l ; xd = 1.0l ; }
1565    if( yd == 0.0l ){ r22 = 1.0l ; r12 = r32 = 0.0l ; yd = 1.0l ; }
1566    if( zd == 0.0l ){ r33 = 1.0l ; r13 = r23 = 0.0l ; zd = 1.0l ; }
1567 
1568    /* assign the output lengths */
1569 
1570    ASSIF(dx,xd) ; ASSIF(dy,yd) ; ASSIF(dz,zd) ;
1571 
1572    /* normalize the columns */
1573 
1574    r11 /= xd ; r21 /= xd ; r31 /= xd ;
1575    r12 /= yd ; r22 /= yd ; r32 /= yd ;
1576    r13 /= zd ; r23 /= zd ; r33 /= zd ;
1577 
1578    /* At this point, the matrix has normal columns, but we have to allow
1579       for the fact that the hideous user may not have given us a matrix
1580       with orthogonal columns.
1581 
1582       So, now find the orthogonal matrix closest to the current matrix.
1583 
1584       One reason for using the polar decomposition to get this
1585       orthogonal matrix, rather than just directly orthogonalizing
1586       the columns, is so that inputting the inverse matrix to R
1587       will result in the inverse orthogonal matrix at this point.
1588       If we just orthogonalized the columns, this wouldn't necessarily hold. */
1589 
1590    Q.m[0][0] = r11 ; Q.m[0][1] = r12 ; Q.m[0][2] = r13 ; /* load Q */
1591    Q.m[1][0] = r21 ; Q.m[1][1] = r22 ; Q.m[1][2] = r23 ;
1592    Q.m[2][0] = r31 ; Q.m[2][1] = r32 ; Q.m[2][2] = r33 ;
1593 
1594    P = nifti_mat33_polar(Q) ;  /* P is orthog matrix closest to Q */
1595 
1596    r11 = P.m[0][0] ; r12 = P.m[0][1] ; r13 = P.m[0][2] ; /* unload */
1597    r21 = P.m[1][0] ; r22 = P.m[1][1] ; r23 = P.m[1][2] ;
1598    r31 = P.m[2][0] ; r32 = P.m[2][1] ; r33 = P.m[2][2] ;
1599 
1600    /*                            [ r11 r12 r13 ]               */
1601    /* at this point, the matrix  [ r21 r22 r23 ] is orthogonal */
1602    /*                            [ r31 r32 r33 ]               */
1603 
1604    /* compute the determinant to determine if it is proper */
1605 
1606    zd = r11*r22*r33-r11*r32*r23-r21*r12*r33
1607        +r21*r32*r13+r31*r12*r23-r31*r22*r13 ;  /* should be -1 or 1 */
1608 
1609    if( zd > 0 ){             /* proper */
1610      ASSIF(qfac,1.0) ;
1611    } else {                  /* improper ==> flip 3rd column */
1612      ASSIF(qfac,-1.0) ;
1613      r13 = -r13 ; r23 = -r23 ; r33 = -r33 ;
1614    }
1615 
1616    /* now, compute quaternion parameters */
1617 
1618    a = r11 + r22 + r33 + 1.0l ;
1619 
1620    if( a > 0.5l ){                /* simplest case */
1621      a = 0.5l * sqrt(a) ;
1622      b = 0.25l * (r32-r23) / a ;
1623      c = 0.25l * (r13-r31) / a ;
1624      d = 0.25l * (r21-r12) / a ;
1625    } else {                       /* trickier case */
1626      xd = 1.0 + r11 - (r22+r33) ;  /* 4*b*b */
1627      yd = 1.0 + r22 - (r11+r33) ;  /* 4*c*c */
1628      zd = 1.0 + r33 - (r11+r22) ;  /* 4*d*d */
1629      if( xd > 1.0 ){
1630        b = 0.5l * sqrt(xd) ;
1631        c = 0.25l* (r12+r21) / b ;
1632        d = 0.25l* (r13+r31) / b ;
1633        a = 0.25l* (r32-r23) / b ;
1634      } else if( yd > 1.0 ){
1635        c = 0.5l * sqrt(yd) ;
1636        b = 0.25l* (r12+r21) / c ;
1637        d = 0.25l* (r23+r32) / c ;
1638        a = 0.25l* (r13-r31) / c ;
1639      } else {
1640        d = 0.5l * sqrt(zd) ;
1641        b = 0.25l* (r13+r31) / d ;
1642        c = 0.25l* (r23+r32) / d ;
1643        a = 0.25l* (r21-r12) / d ;
1644      }
1645      if( a < 0.0l ){ b=-b ; c=-c ; d=-d; a=-a; }
1646    }
1647 
1648    ASSIF(qb,b) ; ASSIF(qc,c) ; ASSIF(qd,d) ;
1649    return ;
1650 }
1651 
1652 /*---------------------------------------------------------------------------*/
1653 /*! Compute the inverse of a bordered 4x4 matrix.
1654 
1655      <pre>
1656    - Some numerical code fragments were generated by Maple 8.
1657    - If a singular matrix is input, the output matrix will be all zero.
1658    - You can check for this by examining the [3][3] element, which will
1659      be 1.0 for the normal case and 0.0 for the bad case.
1660 
1661      The input matrix should have the form:
1662         [ r11 r12 r13 v1 ]
1663         [ r21 r22 r23 v2 ]
1664         [ r31 r32 r33 v3 ]
1665         [  0   0   0   1 ]
1666      </pre>
1667 *//*-------------------------------------------------------------------------*/
nifti_mat44_inverse(mat44 R)1668 mat44 nifti_mat44_inverse( mat44 R )
1669 {
1670    double r11,r12,r13,r21,r22,r23,r31,r32,r33,v1,v2,v3 , deti ;
1671    mat44 Q ;
1672                                                        /*  INPUT MATRIX IS:  */
1673    r11 = R.m[0][0]; r12 = R.m[0][1]; r13 = R.m[0][2];  /* [ r11 r12 r13 v1 ] */
1674    r21 = R.m[1][0]; r22 = R.m[1][1]; r23 = R.m[1][2];  /* [ r21 r22 r23 v2 ] */
1675    r31 = R.m[2][0]; r32 = R.m[2][1]; r33 = R.m[2][2];  /* [ r31 r32 r33 v3 ] */
1676    v1  = R.m[0][3]; v2  = R.m[1][3]; v3  = R.m[2][3];  /* [  0   0   0   1 ] */
1677 
1678    deti = r11*r22*r33-r11*r32*r23-r21*r12*r33
1679          +r21*r32*r13+r31*r12*r23-r31*r22*r13 ;
1680 
1681    if( deti != 0.0l ) deti = 1.0l / deti ;
1682 
1683    Q.m[0][0] = deti*( r22*r33-r32*r23) ;
1684    Q.m[0][1] = deti*(-r12*r33+r32*r13) ;
1685    Q.m[0][2] = deti*( r12*r23-r22*r13) ;
1686    Q.m[0][3] = deti*(-r12*r23*v3+r12*v2*r33+r22*r13*v3
1687                      -r22*v1*r33-r32*r13*v2+r32*v1*r23) ;
1688 
1689    Q.m[1][0] = deti*(-r21*r33+r31*r23) ;
1690    Q.m[1][1] = deti*( r11*r33-r31*r13) ;
1691    Q.m[1][2] = deti*(-r11*r23+r21*r13) ;
1692    Q.m[1][3] = deti*( r11*r23*v3-r11*v2*r33-r21*r13*v3
1693                      +r21*v1*r33+r31*r13*v2-r31*v1*r23) ;
1694 
1695    Q.m[2][0] = deti*( r21*r32-r31*r22) ;
1696    Q.m[2][1] = deti*(-r11*r32+r31*r12) ;
1697    Q.m[2][2] = deti*( r11*r22-r21*r12) ;
1698    Q.m[2][3] = deti*(-r11*r22*v3+r11*r32*v2+r21*r12*v3
1699                      -r21*r32*v1-r31*r12*v2+r31*r22*v1) ;
1700 
1701    Q.m[3][0] = Q.m[3][1] = Q.m[3][2] = 0.0l ;
1702    Q.m[3][3] = (deti == 0.0l) ? 0.0l : 1.0l ; /* failure flag if deti == 0 */
1703 
1704    return Q ;
1705 }
1706 
1707 /*---------------------------------------------------------------------------*/
1708 /*! Input 9 floats and make an orthgonal mat44 out of them.
1709 
1710    Each row is normalized, then nifti_mat33_polar() is used to orthogonalize
1711    them.  If row #3 (r31,r32,r33) is input as zero, then it will be taken to
1712    be the cross product of rows #1 and #2.
1713 
1714    This function can be used to create a rotation matrix for transforming
1715    an oblique volume to anatomical coordinates.  For this application:
1716     - row #1 (r11,r12,r13) is the direction vector along the image i-axis
1717     - row #2 (r21,r22,r23) is the direction vector along the image j-axis
1718     - row #3 (r31,r32,r33) is the direction vector along the slice direction
1719       (if available; otherwise enter it as 0's)
1720 
1721    The first 2 rows can be taken from the DICOM attribute (0020,0037)
1722    "Image Orientation (Patient)".
1723 
1724    After forming the rotation matrix, the complete affine transformation from
1725    (i,j,k) grid indexes to (x,y,z) spatial coordinates can be computed by
1726    multiplying each column by the appropriate grid spacing:
1727     - column #1 (R.m[0][0],R.m[1][0],R.m[2][0]) by delta-x
1728     - column #2 (R.m[0][1],R.m[1][1],R.m[2][1]) by delta-y
1729     - column #3 (R.m[0][2],R.m[1][2],R.m[2][2]) by delta-z
1730 
1731    and by then placing the center (x,y,z) coordinates of voxel (0,0,0) into
1732    the column #4 (R.m[0][3],R.m[1][3],R.m[2][3]).
1733 
1734    \sa nifti_quatern_to_mat44, nifti_mat44_to_quatern,
1735        nifti_mat44_to_orientation
1736 *//*-------------------------------------------------------------------------*/
nifti_make_orthog_mat44(float r11,float r12,float r13,float r21,float r22,float r23,float r31,float r32,float r33)1737 mat44 nifti_make_orthog_mat44( float r11, float r12, float r13 ,
1738                                float r21, float r22, float r23 ,
1739                                float r31, float r32, float r33  )
1740 {
1741    mat44 R ;
1742    mat33 Q , P ;
1743    double val ;
1744 
1745    R.m[3][0] = R.m[3][1] = R.m[3][2] = 0.0l ; R.m[3][3] = 1.0l ;
1746 
1747    Q.m[0][0] = r11 ; Q.m[0][1] = r12 ; Q.m[0][2] = r13 ; /* load Q */
1748    Q.m[1][0] = r21 ; Q.m[1][1] = r22 ; Q.m[1][2] = r23 ;
1749    Q.m[2][0] = r31 ; Q.m[2][1] = r32 ; Q.m[2][2] = r33 ;
1750 
1751    /* normalize row 1 */
1752 
1753    val = Q.m[0][0]*Q.m[0][0] + Q.m[0][1]*Q.m[0][1] + Q.m[0][2]*Q.m[0][2] ;
1754    if( val > 0.0l ){
1755      val = 1.0l / sqrt(val) ;
1756      Q.m[0][0] *= val ; Q.m[0][1] *= val ; Q.m[0][2] *= val ;
1757    } else {
1758      Q.m[0][0] = 1.0l ; Q.m[0][1] = 0.0l ; Q.m[0][2] = 0.0l ;
1759    }
1760 
1761    /* normalize row 2 */
1762 
1763    val = Q.m[1][0]*Q.m[1][0] + Q.m[1][1]*Q.m[1][1] + Q.m[1][2]*Q.m[1][2] ;
1764    if( val > 0.0l ){
1765      val = 1.0l / sqrt(val) ;
1766      Q.m[1][0] *= val ; Q.m[1][1] *= val ; Q.m[1][2] *= val ;
1767    } else {
1768      Q.m[1][0] = 0.0l ; Q.m[1][1] = 1.0l ; Q.m[1][2] = 0.0l ;
1769    }
1770 
1771    /* normalize row 3 */
1772 
1773    val = Q.m[2][0]*Q.m[2][0] + Q.m[2][1]*Q.m[2][1] + Q.m[2][2]*Q.m[2][2] ;
1774    if( val > 0.0l ){
1775      val = 1.0l / sqrt(val) ;
1776      Q.m[2][0] *= val ; Q.m[2][1] *= val ; Q.m[2][2] *= val ;
1777    } else {
1778      Q.m[2][0] = Q.m[0][1]*Q.m[1][2] - Q.m[0][2]*Q.m[1][1] ;  /* cross */
1779      Q.m[2][1] = Q.m[0][2]*Q.m[1][0] - Q.m[0][0]*Q.m[1][2] ;  /* product */
1780      Q.m[2][2] = Q.m[0][0]*Q.m[1][1] - Q.m[0][1]*Q.m[1][0] ;
1781    }
1782 
1783    P = nifti_mat33_polar(Q) ;  /* P is orthog matrix closest to Q */
1784 
1785    R.m[0][0] = P.m[0][0] ; R.m[0][1] = P.m[0][1] ; R.m[0][2] = P.m[0][2] ;
1786    R.m[1][0] = P.m[1][0] ; R.m[1][1] = P.m[1][1] ; R.m[1][2] = P.m[1][2] ;
1787    R.m[2][0] = P.m[2][0] ; R.m[2][1] = P.m[2][1] ; R.m[2][2] = P.m[2][2] ;
1788 
1789    R.m[0][3] = R.m[1][3] = R.m[2][3] = 0.0 ; return R ;
1790 }
1791 
1792 /*----------------------------------------------------------------------*/
1793 /*! compute the inverse of a 3x3 matrix
1794 *//*--------------------------------------------------------------------*/
nifti_mat33_inverse(mat33 R)1795 mat33 nifti_mat33_inverse( mat33 R )   /* inverse of 3x3 matrix */
1796 {
1797    double r11,r12,r13,r21,r22,r23,r31,r32,r33 , deti ;
1798    mat33 Q ;
1799                                                        /*  INPUT MATRIX:  */
1800    r11 = R.m[0][0]; r12 = R.m[0][1]; r13 = R.m[0][2];  /* [ r11 r12 r13 ] */
1801    r21 = R.m[1][0]; r22 = R.m[1][1]; r23 = R.m[1][2];  /* [ r21 r22 r23 ] */
1802    r31 = R.m[2][0]; r32 = R.m[2][1]; r33 = R.m[2][2];  /* [ r31 r32 r33 ] */
1803 
1804    deti = r11*r22*r33-r11*r32*r23-r21*r12*r33
1805          +r21*r32*r13+r31*r12*r23-r31*r22*r13 ;
1806 
1807    if( deti != 0.0l ) deti = 1.0l / deti ;
1808 
1809    Q.m[0][0] = deti*( r22*r33-r32*r23) ;
1810    Q.m[0][1] = deti*(-r12*r33+r32*r13) ;
1811    Q.m[0][2] = deti*( r12*r23-r22*r13) ;
1812 
1813    Q.m[1][0] = deti*(-r21*r33+r31*r23) ;
1814    Q.m[1][1] = deti*( r11*r33-r31*r13) ;
1815    Q.m[1][2] = deti*(-r11*r23+r21*r13) ;
1816 
1817    Q.m[2][0] = deti*( r21*r32-r31*r22) ;
1818    Q.m[2][1] = deti*(-r11*r32+r31*r12) ;
1819    Q.m[2][2] = deti*( r11*r22-r21*r12) ;
1820 
1821    return Q ;
1822 }
1823 
1824 /*----------------------------------------------------------------------*/
1825 /*! compute the determinant of a 3x3 matrix
1826 *//*--------------------------------------------------------------------*/
nifti_mat33_determ(mat33 R)1827 float nifti_mat33_determ( mat33 R )   /* determinant of 3x3 matrix */
1828 {
1829    double r11,r12,r13,r21,r22,r23,r31,r32,r33 ;
1830                                                        /*  INPUT MATRIX:  */
1831    r11 = R.m[0][0]; r12 = R.m[0][1]; r13 = R.m[0][2];  /* [ r11 r12 r13 ] */
1832    r21 = R.m[1][0]; r22 = R.m[1][1]; r23 = R.m[1][2];  /* [ r21 r22 r23 ] */
1833    r31 = R.m[2][0]; r32 = R.m[2][1]; r33 = R.m[2][2];  /* [ r31 r32 r33 ] */
1834 
1835    return r11*r22*r33-r11*r32*r23-r21*r12*r33
1836          +r21*r32*r13+r31*r12*r23-r31*r22*r13 ;
1837 }
1838 
1839 /*----------------------------------------------------------------------*/
1840 /*! compute the max row norm of a 3x3 matrix
1841 *//*--------------------------------------------------------------------*/
nifti_mat33_rownorm(mat33 A)1842 float nifti_mat33_rownorm( mat33 A )  /* max row norm of 3x3 matrix */
1843 {
1844    float r1,r2,r3 ;
1845 
1846    r1 = fabs(A.m[0][0])+fabs(A.m[0][1])+fabs(A.m[0][2]) ;
1847    r2 = fabs(A.m[1][0])+fabs(A.m[1][1])+fabs(A.m[1][2]) ;
1848    r3 = fabs(A.m[2][0])+fabs(A.m[2][1])+fabs(A.m[2][2]) ;
1849    if( r1 < r2 ) r1 = r2 ;
1850    if( r1 < r3 ) r1 = r3 ;
1851    return r1 ;
1852 }
1853 
1854 /*----------------------------------------------------------------------*/
1855 /*! compute the max column norm of a 3x3 matrix
1856 *//*--------------------------------------------------------------------*/
nifti_mat33_colnorm(mat33 A)1857 float nifti_mat33_colnorm( mat33 A )  /* max column norm of 3x3 matrix */
1858 {
1859    float r1,r2,r3 ;
1860 
1861    r1 = fabs(A.m[0][0])+fabs(A.m[1][0])+fabs(A.m[2][0]) ;
1862    r2 = fabs(A.m[0][1])+fabs(A.m[1][1])+fabs(A.m[2][1]) ;
1863    r3 = fabs(A.m[0][2])+fabs(A.m[1][2])+fabs(A.m[2][2]) ;
1864    if( r1 < r2 ) r1 = r2 ;
1865    if( r1 < r3 ) r1 = r3 ;
1866    return r1 ;
1867 }
1868 
1869 /*----------------------------------------------------------------------*/
1870 /*! multiply 2 3x3 matrices
1871 *//*--------------------------------------------------------------------*/
nifti_mat33_mul(mat33 A,mat33 B)1872 mat33 nifti_mat33_mul( mat33 A , mat33 B )  /* multiply 2 3x3 matrices */
1873 {
1874    mat33 C ; int i,j ;
1875    for( i=0 ; i < 3 ; i++ )
1876     for( j=0 ; j < 3 ; j++ )
1877       C.m[i][j] =  A.m[i][0] * B.m[0][j]
1878                  + A.m[i][1] * B.m[1][j]
1879                  + A.m[i][2] * B.m[2][j] ;
1880    return C ;
1881 }
1882 
1883 /*---------------------------------------------------------------------------*/
1884 /*! polar decomposition of a 3x3 matrix
1885 
1886    This finds the closest orthogonal matrix to input A
1887    (in both the Frobenius and L2 norms).
1888 
1889    Algorithm is that from NJ Higham, SIAM J Sci Stat Comput, 7:1160-1174.
1890 *//*-------------------------------------------------------------------------*/
nifti_mat33_polar(mat33 A)1891 mat33 nifti_mat33_polar( mat33 A )
1892 {
1893    mat33 X , Y , Z ;
1894    float alp,bet,gam,gmi , dif=1.0 ;
1895    int k=0 ;
1896 
1897    X = A ;
1898 
1899    /* force matrix to be nonsingular */
1900 
1901    gam = nifti_mat33_determ(X) ;
1902    while( gam == 0.0 ){        /* perturb matrix */
1903      gam = 0.00001 * ( 0.001 + nifti_mat33_rownorm(X) ) ;
1904      X.m[0][0] += gam ; X.m[1][1] += gam ; X.m[2][2] += gam ;
1905      gam = nifti_mat33_determ(X) ;
1906    }
1907 
1908    while(1){
1909      Y = nifti_mat33_inverse(X) ;
1910      if( dif > 0.3 ){     /* far from convergence */
1911        alp = sqrt( nifti_mat33_rownorm(X) * nifti_mat33_colnorm(X) ) ;
1912        bet = sqrt( nifti_mat33_rownorm(Y) * nifti_mat33_colnorm(Y) ) ;
1913        gam = sqrt( bet / alp ) ;
1914        gmi = 1.0 / gam ;
1915      } else {
1916        gam = gmi = 1.0 ;  /* close to convergence */
1917      }
1918      Z.m[0][0] = 0.5 * ( gam*X.m[0][0] + gmi*Y.m[0][0] ) ;
1919      Z.m[0][1] = 0.5 * ( gam*X.m[0][1] + gmi*Y.m[1][0] ) ;
1920      Z.m[0][2] = 0.5 * ( gam*X.m[0][2] + gmi*Y.m[2][0] ) ;
1921      Z.m[1][0] = 0.5 * ( gam*X.m[1][0] + gmi*Y.m[0][1] ) ;
1922      Z.m[1][1] = 0.5 * ( gam*X.m[1][1] + gmi*Y.m[1][1] ) ;
1923      Z.m[1][2] = 0.5 * ( gam*X.m[1][2] + gmi*Y.m[2][1] ) ;
1924      Z.m[2][0] = 0.5 * ( gam*X.m[2][0] + gmi*Y.m[0][2] ) ;
1925      Z.m[2][1] = 0.5 * ( gam*X.m[2][1] + gmi*Y.m[1][2] ) ;
1926      Z.m[2][2] = 0.5 * ( gam*X.m[2][2] + gmi*Y.m[2][2] ) ;
1927 
1928      dif = fabs(Z.m[0][0]-X.m[0][0])+fabs(Z.m[0][1]-X.m[0][1])
1929           +fabs(Z.m[0][2]-X.m[0][2])+fabs(Z.m[1][0]-X.m[1][0])
1930           +fabs(Z.m[1][1]-X.m[1][1])+fabs(Z.m[1][2]-X.m[1][2])
1931           +fabs(Z.m[2][0]-X.m[2][0])+fabs(Z.m[2][1]-X.m[2][1])
1932           +fabs(Z.m[2][2]-X.m[2][2])                          ;
1933 
1934      k = k+1 ;
1935      if( k > 100 || dif < 3.e-6 ) break ;  /* convergence or exhaustion */
1936      X = Z ;
1937    }
1938 
1939    return Z ;
1940 }
1941 
1942 /*---------------------------------------------------------------------------*/
1943 /*! compute the (closest) orientation from a 4x4 ijk->xyz tranformation matrix
1944 
1945    <pre>
1946    Input:  4x4 matrix that transforms (i,j,k) indexes to (x,y,z) coordinates,
1947            where +x=Right, +y=Anterior, +z=Superior.
1948            (Only the upper-left 3x3 corner of R is used herein.)
1949    Output: 3 orientation codes that correspond to the closest "standard"
1950            anatomical orientation of the (i,j,k) axes.
1951    Method: Find which permutation of (x,y,z) has the smallest angle to the
1952            (i,j,k) axes directions, which are the columns of the R matrix.
1953    Errors: The codes returned will be zero.
1954 
1955    For example, an axial volume might get return values of
1956      *icod = NIFTI_R2L   (i axis is mostly Right to Left)
1957      *jcod = NIFTI_P2A   (j axis is mostly Posterior to Anterior)
1958      *kcod = NIFTI_I2S   (k axis is mostly Inferior to Superior)
1959    </pre>
1960 
1961    \see "QUATERNION REPRESENTATION OF ROTATION MATRIX" in nifti1.h
1962 
1963    \see nifti_quatern_to_mat44, nifti_mat44_to_quatern,
1964         nifti_make_orthog_mat44
1965 *//*-------------------------------------------------------------------------*/
nifti_mat44_to_orientation(mat44 R,int * icod,int * jcod,int * kcod)1966 void nifti_mat44_to_orientation( mat44 R , int *icod, int *jcod, int *kcod )
1967 {
1968    float xi,xj,xk , yi,yj,yk , zi,zj,zk , val,detQ,detP ;
1969    mat33 P , Q , M ;
1970    int i,j,k=0,p,q,r , ibest,jbest,kbest,pbest,qbest,rbest ;
1971    float vbest ;
1972 
1973    if( icod == NULL || jcod == NULL || kcod == NULL ) return ; /* bad */
1974 
1975    *icod = *jcod = *kcod = 0 ; /* error returns, if sh*t happens */
1976 
1977    /* load column vectors for each (i,j,k) direction from matrix */
1978 
1979    /*-- i axis --*/ /*-- j axis --*/ /*-- k axis --*/
1980 
1981    xi = R.m[0][0] ; xj = R.m[0][1] ; xk = R.m[0][2] ;
1982    yi = R.m[1][0] ; yj = R.m[1][1] ; yk = R.m[1][2] ;
1983    zi = R.m[2][0] ; zj = R.m[2][1] ; zk = R.m[2][2] ;
1984 
1985    /* normalize column vectors to get unit vectors along each ijk-axis */
1986 
1987    /* normalize i axis */
1988 
1989    val = sqrt( xi*xi + yi*yi + zi*zi ) ;
1990    if( val == 0.0 ) return ;                 /* stupid input */
1991    xi /= val ; yi /= val ; zi /= val ;
1992 
1993    /* normalize j axis */
1994 
1995    val = sqrt( xj*xj + yj*yj + zj*zj ) ;
1996    if( val == 0.0 ) return ;                 /* stupid input */
1997    xj /= val ; yj /= val ; zj /= val ;
1998 
1999    /* orthogonalize j axis to i axis, if needed */
2000 
2001    val = xi*xj + yi*yj + zi*zj ;    /* dot product between i and j */
2002    if( fabs(val) > 1.e-4 ){
2003      xj -= val*xi ; yj -= val*yi ; zj -= val*zi ;
2004      val = sqrt( xj*xj + yj*yj + zj*zj ) ;  /* must renormalize */
2005      if( val == 0.0 ) return ;              /* j was parallel to i? */
2006      xj /= val ; yj /= val ; zj /= val ;
2007    }
2008 
2009    /* normalize k axis; if it is zero, make it the cross product i x j */
2010 
2011    val = sqrt( xk*xk + yk*yk + zk*zk ) ;
2012    if( val == 0.0 ){ xk = yi*zj-zi*yj; yk = zi*xj-zj*xi ; zk=xi*yj-yi*xj ; }
2013    else            { xk /= val ; yk /= val ; zk /= val ; }
2014 
2015    /* orthogonalize k to i */
2016 
2017    val = xi*xk + yi*yk + zi*zk ;    /* dot product between i and k */
2018    if( fabs(val) > 1.e-4 ){
2019      xk -= val*xi ; yk -= val*yi ; zk -= val*zi ;
2020      val = sqrt( xk*xk + yk*yk + zk*zk ) ;
2021      if( val == 0.0 ) return ;      /* bad */
2022      xk /= val ; yk /= val ; zk /= val ;
2023    }
2024 
2025    /* orthogonalize k to j */
2026 
2027    val = xj*xk + yj*yk + zj*zk ;    /* dot product between j and k */
2028    if( fabs(val) > 1.e-4 ){
2029      xk -= val*xj ; yk -= val*yj ; zk -= val*zj ;
2030      val = sqrt( xk*xk + yk*yk + zk*zk ) ;
2031      if( val == 0.0 ) return ;      /* bad */
2032      xk /= val ; yk /= val ; zk /= val ;
2033    }
2034 
2035    Q.m[0][0] = xi ; Q.m[0][1] = xj ; Q.m[0][2] = xk ;
2036    Q.m[1][0] = yi ; Q.m[1][1] = yj ; Q.m[1][2] = yk ;
2037    Q.m[2][0] = zi ; Q.m[2][1] = zj ; Q.m[2][2] = zk ;
2038 
2039    /* at this point, Q is the rotation matrix from the (i,j,k) to (x,y,z) axes */
2040 
2041    detQ = nifti_mat33_determ( Q ) ;
2042    if( detQ == 0.0 ) return ; /* shouldn't happen unless user is a DUFIS */
2043 
2044    /* Build and test all possible +1/-1 coordinate permutation matrices P;
2045       then find the P such that the rotation matrix M=PQ is closest to the
2046       identity, in the sense of M having the smallest total rotation angle. */
2047 
2048    /* Despite the formidable looking 6 nested loops, there are
2049       only 3*3*3*2*2*2 = 216 passes, which will run very quickly. */
2050 
2051    vbest = -666.0 ; ibest=pbest=qbest=rbest=1 ; jbest=2 ; kbest=3 ;
2052    for( i=1 ; i <= 3 ; i++ ){     /* i = column number to use for row #1 */
2053     for( j=1 ; j <= 3 ; j++ ){    /* j = column number to use for row #2 */
2054      if( i == j ) continue ;
2055       for( k=1 ; k <= 3 ; k++ ){  /* k = column number to use for row #3 */
2056        if( i == k || j == k ) continue ;
2057        P.m[0][0] = P.m[0][1] = P.m[0][2] =
2058         P.m[1][0] = P.m[1][1] = P.m[1][2] =
2059          P.m[2][0] = P.m[2][1] = P.m[2][2] = 0.0 ;
2060        for( p=-1 ; p <= 1 ; p+=2 ){    /* p,q,r are -1 or +1      */
2061         for( q=-1 ; q <= 1 ; q+=2 ){   /* and go into rows #1,2,3 */
2062          for( r=-1 ; r <= 1 ; r+=2 ){
2063            P.m[0][i-1] = p ; P.m[1][j-1] = q ; P.m[2][k-1] = r ;
2064            detP = nifti_mat33_determ(P) ;           /* sign of permutation */
2065            if( detP * detQ <= 0.0 ) continue ;  /* doesn't match sign of Q */
2066            M = nifti_mat33_mul(P,Q) ;
2067 
2068            /* angle of M rotation = 2.0*acos(0.5*sqrt(1.0+trace(M)))       */
2069            /* we want largest trace(M) == smallest angle == M nearest to I */
2070 
2071            val = M.m[0][0] + M.m[1][1] + M.m[2][2] ; /* trace */
2072            if( val > vbest ){
2073              vbest = val ;
2074              ibest = i ; jbest = j ; kbest = k ;
2075              pbest = p ; qbest = q ; rbest = r ;
2076            }
2077    }}}}}}
2078 
2079    /* At this point ibest is 1 or 2 or 3; pbest is -1 or +1; etc.
2080 
2081       The matrix P that corresponds is the best permutation approximation
2082       to Q-inverse; that is, P (approximately) takes (x,y,z) coordinates
2083       to the (i,j,k) axes.
2084 
2085       For example, the first row of P (which contains pbest in column ibest)
2086       determines the way the i axis points relative to the anatomical
2087       (x,y,z) axes.  If ibest is 2, then the i axis is along the y axis,
2088       which is direction P2A (if pbest > 0) or A2P (if pbest < 0).
2089 
2090       So, using ibest and pbest, we can assign the output code for
2091       the i axis.  Mutatis mutandis for the j and k axes, of course. */
2092 
2093    switch( ibest*pbest ){
2094      case  1: i = NIFTI_L2R ; break ;
2095      case -1: i = NIFTI_R2L ; break ;
2096      case  2: i = NIFTI_P2A ; break ;
2097      case -2: i = NIFTI_A2P ; break ;
2098      case  3: i = NIFTI_I2S ; break ;
2099      case -3: i = NIFTI_S2I ; break ;
2100    }
2101 
2102    switch( jbest*qbest ){
2103      case  1: j = NIFTI_L2R ; break ;
2104      case -1: j = NIFTI_R2L ; break ;
2105      case  2: j = NIFTI_P2A ; break ;
2106      case -2: j = NIFTI_A2P ; break ;
2107      case  3: j = NIFTI_I2S ; break ;
2108      case -3: j = NIFTI_S2I ; break ;
2109    }
2110 
2111    switch( kbest*rbest ){
2112      case  1: k = NIFTI_L2R ; break ;
2113      case -1: k = NIFTI_R2L ; break ;
2114      case  2: k = NIFTI_P2A ; break ;
2115      case -2: k = NIFTI_A2P ; break ;
2116      case  3: k = NIFTI_I2S ; break ;
2117      case -3: k = NIFTI_S2I ; break ;
2118    }
2119 
2120    *icod = i ; *jcod = j ; *kcod = k ; return ;
2121 }
2122 
2123 /*---------------------------------------------------------------------------*/
2124 /* Routines to swap byte arrays in various ways:
2125     -  2 at a time:  ab               -> ba               [short]
2126     -  4 at a time:  abcd             -> dcba             [int, float]
2127     -  8 at a time:  abcdDCBA         -> ABCDdcba         [long long, double]
2128     - 16 at a time:  abcdefghHGFEDCBA -> ABCDEFGHhgfedcba [long double]
2129 -----------------------------------------------------------------------------*/
2130 
2131 /*----------------------------------------------------------------------*/
2132 /*! swap each byte pair from the given list of n pairs
2133  *
2134  *  Due to alignment of structures at some architectures (e.g. on ARM),
2135  *  stick to char varaibles.
2136  *  Fixes http://bugs.debian.org/446893   Yaroslav <debian@onerussian.com>
2137  *
2138 *//*--------------------------------------------------------------------*/
nifti_swap_2bytes(size_t n,void * ar)2139 void nifti_swap_2bytes( size_t n , void *ar )    /* 2 bytes at a time */
2140 {
2141    register size_t ii ;
2142    unsigned char * cp1 = (unsigned char *)ar, * cp2 ;
2143    unsigned char   tval;
2144 
2145    for( ii=0 ; ii < n ; ii++ ){
2146        cp2 = cp1 + 1;
2147        tval = *cp1;  *cp1 = *cp2;  *cp2 = tval;
2148        cp1 += 2;
2149    }
2150    return ;
2151 }
2152 
2153 /*----------------------------------------------------------------------*/
2154 /*! swap 4 bytes at a time from the given list of n sets of 4 bytes
2155 *//*--------------------------------------------------------------------*/
nifti_swap_4bytes(size_t n,void * ar)2156 void nifti_swap_4bytes( size_t n , void *ar )    /* 4 bytes at a time */
2157 {
2158    register size_t ii ;
2159    unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ;
2160    register unsigned char tval ;
2161 
2162    for( ii=0 ; ii < n ; ii++ ){
2163        cp1 = cp0; cp2 = cp0+3;
2164        tval = *cp1;  *cp1 = *cp2;  *cp2 = tval;
2165        cp1++;  cp2--;
2166        tval = *cp1;  *cp1 = *cp2;  *cp2 = tval;
2167        cp0 += 4;
2168    }
2169    return ;
2170 }
2171 
2172 /*----------------------------------------------------------------------*/
2173 /*! swap 8 bytes at a time from the given list of n sets of 8 bytes
2174  *
2175  *  perhaps use this style for the general Nbytes, as Yaroslav suggests
2176 *//*--------------------------------------------------------------------*/
nifti_swap_8bytes(size_t n,void * ar)2177 void nifti_swap_8bytes( size_t n , void *ar )    /* 8 bytes at a time */
2178 {
2179    register size_t ii ;
2180    unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ;
2181    register unsigned char tval ;
2182 
2183    for( ii=0 ; ii < n ; ii++ ){
2184        cp1 = cp0;  cp2 = cp0+7;
2185        while ( cp2 > cp1 )      /* unroll? */
2186        {
2187            tval = *cp1 ; *cp1 = *cp2 ; *cp2 = tval ;
2188            cp1++; cp2--;
2189        }
2190        cp0 += 8;
2191    }
2192    return ;
2193 }
2194 
2195 /*----------------------------------------------------------------------*/
2196 /*! swap 16 bytes at a time from the given list of n sets of 16 bytes
2197 *//*--------------------------------------------------------------------*/
nifti_swap_16bytes(size_t n,void * ar)2198 void nifti_swap_16bytes( size_t n , void *ar )    /* 16 bytes at a time */
2199 {
2200    register size_t ii ;
2201    unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ;
2202    register unsigned char tval ;
2203 
2204    for( ii=0 ; ii < n ; ii++ ){
2205        cp1 = cp0;  cp2 = cp0+15;
2206        while ( cp2 > cp1 )
2207        {
2208            tval = *cp1 ; *cp1 = *cp2 ; *cp2 = tval ;
2209            cp1++; cp2--;
2210        }
2211        cp0 += 16;
2212    }
2213    return ;
2214 }
2215 
2216 #if 0  /* not important: save for version update     6 Jul 2010 [rickr] */
2217 
2218 /*----------------------------------------------------------------------*/
2219 /*! generic: swap siz bytes at a time from the given list of n sets
2220 *//*--------------------------------------------------------------------*/
2221 void nifti_swap_bytes( size_t n , int siz , void *ar )
2222 {
2223    register size_t ii ;
2224    unsigned char * cp0 = (unsigned char *)ar, * cp1, * cp2 ;
2225    register unsigned char tval ;
2226 
2227    for( ii=0 ; ii < n ; ii++ ){
2228        cp1 = cp0;  cp2 = cp0+(siz-1);
2229        while ( cp2 > cp1 )
2230        {
2231            tval = *cp1 ; *cp1 = *cp2 ; *cp2 = tval ;
2232            cp1++; cp2--;
2233        }
2234        cp0 += siz;
2235    }
2236    return ;
2237 }
2238 #endif
2239 
2240 /*---------------------------------------------------------------------------*/
2241 
2242 /*----------------------------------------------------------------------*/
2243 /*! based on siz, call the appropriate nifti_swap_Nbytes() function
2244 *//*--------------------------------------------------------------------*/
nifti_swap_Nbytes(size_t n,int siz,void * ar)2245 void nifti_swap_Nbytes( size_t n , int siz , void *ar )  /* subsuming case */
2246 {
2247    switch( siz ){
2248      case 2:  nifti_swap_2bytes ( n , ar ) ; break ;
2249      case 4:  nifti_swap_4bytes ( n , ar ) ; break ;
2250      case 8:  nifti_swap_8bytes ( n , ar ) ; break ;
2251      case 16: nifti_swap_16bytes( n , ar ) ; break ;
2252      default:    /* nifti_swap_bytes  ( n , siz, ar ) ; */
2253         fprintf(stderr,"** NIfTI: cannot swap in %d byte blocks\n", siz);
2254         break ;
2255    }
2256    return ;
2257 }
2258 
2259 
2260 /*-------------------------------------------------------------------------*/
2261 /*! Byte swap NIFTI-1 file header in various places and ways.
2262 
2263     If is_nifti, swap all (even UNUSED) fields of NIfTI header.
2264     Else, swap as a nifti_analyze75 struct.
2265 *//*---------------------------------------------------------------------- */
swap_nifti_header(struct nifti_1_header * h,int is_nifti)2266 void swap_nifti_header( struct nifti_1_header *h , int is_nifti )
2267 {
2268 
2269    /* if ANALYZE, swap as such and return */
2270    if( ! is_nifti ) {
2271       nifti_swap_as_analyze((nifti_analyze75 *)h);
2272       return;
2273    }
2274 
2275    /* otherwise, swap all NIFTI fields */
2276 
2277    nifti_swap_4bytes(1, &h->sizeof_hdr);
2278    nifti_swap_4bytes(1, &h->extents);
2279    nifti_swap_2bytes(1, &h->session_error);
2280 
2281    nifti_swap_2bytes(8, h->dim);
2282    nifti_swap_4bytes(1, &h->intent_p1);
2283    nifti_swap_4bytes(1, &h->intent_p2);
2284    nifti_swap_4bytes(1, &h->intent_p3);
2285 
2286    nifti_swap_2bytes(1, &h->intent_code);
2287    nifti_swap_2bytes(1, &h->datatype);
2288    nifti_swap_2bytes(1, &h->bitpix);
2289    nifti_swap_2bytes(1, &h->slice_start);
2290 
2291    nifti_swap_4bytes(8, h->pixdim);
2292 
2293    nifti_swap_4bytes(1, &h->vox_offset);
2294    nifti_swap_4bytes(1, &h->scl_slope);
2295    nifti_swap_4bytes(1, &h->scl_inter);
2296    nifti_swap_2bytes(1, &h->slice_end);
2297 
2298    nifti_swap_4bytes(1, &h->cal_max);
2299    nifti_swap_4bytes(1, &h->cal_min);
2300    nifti_swap_4bytes(1, &h->slice_duration);
2301    nifti_swap_4bytes(1, &h->toffset);
2302    nifti_swap_4bytes(1, &h->glmax);
2303    nifti_swap_4bytes(1, &h->glmin);
2304 
2305    nifti_swap_2bytes(1, &h->qform_code);
2306    nifti_swap_2bytes(1, &h->sform_code);
2307 
2308    nifti_swap_4bytes(1, &h->quatern_b);
2309    nifti_swap_4bytes(1, &h->quatern_c);
2310    nifti_swap_4bytes(1, &h->quatern_d);
2311    nifti_swap_4bytes(1, &h->qoffset_x);
2312    nifti_swap_4bytes(1, &h->qoffset_y);
2313    nifti_swap_4bytes(1, &h->qoffset_z);
2314 
2315    nifti_swap_4bytes(4, h->srow_x);
2316    nifti_swap_4bytes(4, h->srow_y);
2317    nifti_swap_4bytes(4, h->srow_z);
2318 
2319    return ;
2320 }
2321 
2322 /*-------------------------------------------------------------------------*/
2323 /*! Byte swap as an ANALYZE 7.5 header
2324  *
2325  *  return non-zero on failure
2326 *//*---------------------------------------------------------------------- */
nifti_swap_as_analyze(nifti_analyze75 * h)2327 int nifti_swap_as_analyze( nifti_analyze75 * h )
2328 {
2329    if( !h ) return 1;
2330 
2331    nifti_swap_4bytes(1, &h->sizeof_hdr);
2332    nifti_swap_4bytes(1, &h->extents);
2333    nifti_swap_2bytes(1, &h->session_error);
2334 
2335    nifti_swap_2bytes(8, h->dim);
2336    nifti_swap_2bytes(1, &h->unused8);
2337    nifti_swap_2bytes(1, &h->unused9);
2338    nifti_swap_2bytes(1, &h->unused10);
2339    nifti_swap_2bytes(1, &h->unused11);
2340    nifti_swap_2bytes(1, &h->unused12);
2341    nifti_swap_2bytes(1, &h->unused13);
2342    nifti_swap_2bytes(1, &h->unused14);
2343 
2344    nifti_swap_2bytes(1, &h->datatype);
2345    nifti_swap_2bytes(1, &h->bitpix);
2346    nifti_swap_2bytes(1, &h->dim_un0);
2347 
2348    nifti_swap_4bytes(8, h->pixdim);
2349 
2350    nifti_swap_4bytes(1, &h->vox_offset);
2351    nifti_swap_4bytes(1, &h->funused1);
2352    nifti_swap_4bytes(1, &h->funused2);
2353    nifti_swap_4bytes(1, &h->funused3);
2354 
2355    nifti_swap_4bytes(1, &h->cal_max);
2356    nifti_swap_4bytes(1, &h->cal_min);
2357    nifti_swap_4bytes(1, &h->compressed);
2358    nifti_swap_4bytes(1, &h->verified);
2359 
2360    nifti_swap_4bytes(1, &h->glmax);
2361    nifti_swap_4bytes(1, &h->glmin);
2362 
2363    nifti_swap_4bytes(1, &h->views);
2364    nifti_swap_4bytes(1, &h->vols_added);
2365    nifti_swap_4bytes(1, &h->start_field);
2366    nifti_swap_4bytes(1, &h->field_skip);
2367 
2368    nifti_swap_4bytes(1, &h->omax);
2369    nifti_swap_4bytes(1, &h->omin);
2370    nifti_swap_4bytes(1, &h->smax);
2371    nifti_swap_4bytes(1, &h->smin);
2372 
2373    return 0;
2374 }
2375 
2376 /*-------------------------------------------------------------------------*/
2377 /*! OLD VERSION of swap_nifti_header (left for undo/compare operations)
2378 
2379     Byte swap NIFTI-1 file header in various places and ways.
2380 
2381     If is_nifti is nonzero, will also swap the NIFTI-specific
2382     components of the header; otherwise, only the components
2383     common to NIFTI and ANALYZE will be swapped.
2384 *//*---------------------------------------------------------------------- */
old_swap_nifti_header(struct nifti_1_header * h,int is_nifti)2385 void old_swap_nifti_header( struct nifti_1_header *h , int is_nifti )
2386 {
2387    /* this stuff is always present, for ANALYZE and NIFTI */
2388 
2389    swap_4(h->sizeof_hdr) ;
2390    nifti_swap_2bytes( 8 , h->dim ) ;
2391    nifti_swap_4bytes( 8 , h->pixdim ) ;
2392 
2393    swap_2(h->datatype) ;
2394    swap_2(h->bitpix) ;
2395 
2396    swap_4(h->vox_offset); swap_4(h->cal_max); swap_4(h->cal_min);
2397 
2398    /* this stuff is NIFTI specific */
2399 
2400    if( is_nifti ){
2401      swap_4(h->intent_p1); swap_4(h->intent_p2); swap_4(h->intent_p3);
2402      swap_2(h->intent_code);
2403 
2404      swap_2(h->slice_start);    swap_2(h->slice_end);
2405      swap_4(h->scl_slope);      swap_4(h->scl_inter);
2406      swap_4(h->slice_duration); swap_4(h->toffset);
2407 
2408      swap_2(h->qform_code); swap_2(h->sform_code);
2409      swap_4(h->quatern_b); swap_4(h->quatern_c); swap_4(h->quatern_d);
2410      swap_4(h->qoffset_x); swap_4(h->qoffset_y); swap_4(h->qoffset_z);
2411      nifti_swap_4bytes(4,h->srow_x);
2412      nifti_swap_4bytes(4,h->srow_y);
2413      nifti_swap_4bytes(4,h->srow_z);
2414    }
2415    return ;
2416 }
2417 
2418 
2419 #define USE_STAT
2420 #ifdef  USE_STAT
2421 /*---------------------------------------------------------------------------*/
2422 /* Return the file length (0 if file not found or has no contents).
2423    This is a Unix-specific function, since it uses stat().
2424 -----------------------------------------------------------------------------*/
2425 #include <sys/types.h>
2426 #include <sys/stat.h>
2427 
2428 /*---------------------------------------------------------------------------*/
2429 /*! return the size of a file, in bytes
2430 
2431     \return size of file on success, -1 on error or no file
2432 
2433     changed to return int, -1 means no file or error      20 Dec 2004 [rickr]
2434 *//*-------------------------------------------------------------------------*/
nifti_get_filesize(const char * pathname)2435 int nifti_get_filesize( const char *pathname )
2436 {
2437    struct stat buf ; int ii ;
2438 
2439    if( pathname == NULL || *pathname == '\0' ) return -1 ;
2440    ii = stat( pathname , &buf ); if( ii != 0 ) return -1 ;
2441    return (unsigned int)buf.st_size ;
2442 }
2443 
2444 #else  /*---------- non-Unix version of the above, less efficient -----------*/
2445 
nifti_get_filesize(const char * pathname)2446 int nifti_get_filesize( const char *pathname )
2447 {
2448    znzFile fp ; int len ;
2449 
2450    if( pathname == NULL || *pathname == '\0' ) return -1 ;
2451    fp = znzopen(pathname,"rb",0); if( znz_isnull(fp) ) return -1 ;
2452    znzseek(fp,0L,SEEK_END) ; len = znztell(fp) ;
2453    znzclose(fp) ; return len ;
2454 }
2455 
2456 #endif /* USE_STAT */
2457 
2458 
2459 /*----------------------------------------------------------------------*/
2460 /*! return the total volume size, in bytes
2461 
2462     This is computed as nvox * nbyper.
2463 *//*--------------------------------------------------------------------*/
nifti_get_volsize(const nifti_image * nim)2464 size_t nifti_get_volsize(const nifti_image *nim)
2465 {
2466    return nim->nbyper * nim->nvox ; /* total bytes */
2467 }
2468 
2469 
2470 /*--------------------------------------------------------------------------*/
2471 /* Support functions for filenames in read and write
2472    - allows for gzipped files
2473 */
2474 
2475 
2476 /*----------------------------------------------------------------------*/
2477 /*! simple check for file existence
2478 
2479     \return 1 on existence, 0 otherwise
2480 *//*--------------------------------------------------------------------*/
nifti_fileexists(const char * fname)2481 int nifti_fileexists(const char* fname)
2482 {
2483    znzFile fp;
2484    fp = znzopen( fname , "rb" , 1 ) ;
2485    if( !znz_isnull(fp) )  { znzclose(fp);  return 1; }
2486    return 0; /* fp is NULL */
2487 }
2488 
2489 /*----------------------------------------------------------------------*/
2490 /*! return whether the filename is valid
2491 
2492     Note: uppercase extensions are now valid.    27 Apr 2009 [rickr]
2493 
2494     The name is considered valid if the file basename has length greater than
2495     zero, AND one of the valid nifti extensions is provided.
2496     fname input          | return |
2497     ===============================
2498     "myimage"            |  0     |
2499     "myimage.tif"        |  0     |
2500     "myimage.tif.gz"     |  0     |
2501     "myimage.nii"        |  1     |
2502     ".nii"               |  0     |
2503     ".myhiddenimage"     |  0     |
2504     ".myhiddenimage.nii" |  1     |
2505 *//*--------------------------------------------------------------------*/
nifti_is_complete_filename(const char * fname)2506 int nifti_is_complete_filename(const char* fname)
2507 {
2508    char * ext;
2509 
2510    /* check input file(s) for sanity */
2511    if( fname == NULL || *fname == '\0' ){
2512       if ( g_opts.debug > 1 )
2513          fprintf(stderr,"-- empty filename in nifti_validfilename()\n");
2514       return 0;
2515    }
2516 
2517    ext = nifti_find_file_extension(fname);
2518    if ( ext == NULL ) { /*Invalid extension given */
2519       if ( g_opts.debug > 0 )
2520          fprintf(stderr,"-- no nifti valid extension for filename '%s'\n", fname);
2521        return 0;
2522    }
2523 
2524    if ( ext && ext == fname ) {   /* then no filename prefix */
2525       if ( g_opts.debug > 0 )
2526          fprintf(stderr,"-- no prefix for filename '%s'\n", fname);
2527       return 0;
2528    }
2529    return 1;
2530 }
2531 
2532 /*----------------------------------------------------------------------*/
2533 /*! return whether the filename is valid
2534 
2535     Allow uppercase extensions as valid.        27 Apr 2009 [rickr]
2536     Any .gz extension case must match the base extension case.
2537 
2538     The name is considered valid if its length is positive, excluding
2539     any nifti filename extension.
2540     fname input         |  return | result of nifti_makebasename
2541     ====================================================================
2542     "myimage"           |  1      | "myimage"
2543     "myimage.tif"       |  1      | "myimage.tif"
2544     "myimage.tif.gz"    |  1      | "myimage.tif"
2545     "myimage.nii"       |  1      | "myimage"
2546     ".nii"              |  0      | <ERROR - basename has zero length>
2547     ".myhiddenimage"    |  1      | ".myhiddenimage"
2548     ".myhiddenimage.nii |  1      | ".myhiddenimage"
2549 *//*--------------------------------------------------------------------*/
nifti_validfilename(const char * fname)2550 int nifti_validfilename(const char* fname)
2551 {
2552    char * ext;
2553 
2554    /* check input file(s) for sanity */
2555    if( fname == NULL || *fname == '\0' ){
2556       if ( g_opts.debug > 1 )
2557          fprintf(stderr,"-- empty filename in nifti_validfilename()\n");
2558       return 0;
2559    }
2560 
2561    ext = nifti_find_file_extension(fname);
2562 
2563    if ( ext && ext == fname ) {   /* then no filename prefix */
2564       if ( g_opts.debug > 0 )
2565          fprintf(stderr,"-- no prefix for filename '%s'\n", fname);
2566       return 0;
2567    }
2568 
2569    return 1;
2570 }
2571 
2572 /*----------------------------------------------------------------------*/
2573 /*! check the end of the filename for a valid nifti extension
2574 
2575     Valid extensions are currently .nii, .hdr, .img, .nia,
2576     or any of them followed by .gz.  Note that '.' is part of
2577     the extension.
2578 
2579     Uppercase extensions are also valid, but not mixed case.
2580 
2581     \return a pointer to the extension (within the filename), or NULL
2582 *//*--------------------------------------------------------------------*/
nifti_find_file_extension(const char * name)2583 char * nifti_find_file_extension( const char * name )
2584 {
2585    char * ext, extcopy[8];
2586    int    len;
2587    char   extnii[8] = ".nii";   /* modifiable, for possible uppercase */
2588    char   exthdr[8] = ".hdr";   /* (leave space for .gz) */
2589    char   extimg[8] = ".img";
2590    char   extnia[8] = ".nia";
2591    char   extgz[4]  = ".gz";
2592    char * elist[4]  = { NULL, NULL, NULL, NULL};
2593 
2594    /* stupid compiler... */
2595    elist[0] = extnii; elist[1] = exthdr; elist[2] = extimg; elist[3] = extnia;
2596 
2597    if ( ! name ) return NULL;
2598 
2599    len = (int)strlen(name);
2600    if ( len < 4 ) return NULL;
2601 
2602    ext = (char *)name + len - 4;
2603 
2604    /* make manipulation copy, and possibly convert to lowercase */
2605    strcpy(extcopy, ext);
2606    if( g_opts.allow_upper_fext ) make_lowercase(extcopy);
2607 
2608    /* if it look like a basic extension, fail or return it */
2609    if( compare_strlist(extcopy, elist, 4) >= 0 ) {
2610       if( is_mixedcase(ext) ) {
2611          fprintf(stderr,"** mixed case extension '%s' is not valid\n", ext);
2612          return NULL;
2613       }
2614       else return ext;
2615    }
2616 
2617 #ifdef HAVE_ZLIB
2618    if ( len < 7 ) return NULL;
2619 
2620    ext = (char *)name + len - 7;
2621 
2622    /* make manipulation copy, and possibly convert to lowercase */
2623    strcpy(extcopy, ext);
2624    if( g_opts.allow_upper_fext ) make_lowercase(extcopy);
2625 
2626    /* go after .gz extensions using the modifiable strings */
2627    strcat(elist[0], extgz); strcat(elist[1], extgz); strcat(elist[2], extgz);
2628 
2629    if( compare_strlist(extcopy, elist, 3) >= 0 ) {
2630       if( is_mixedcase(ext) ) {
2631          fprintf(stderr,"** mixed case extension '%s' is not valid\n", ext);
2632          return NULL;
2633       }
2634       else return ext;
2635    }
2636 
2637 #endif
2638 
2639    if( g_opts.debug > 1 )
2640       fprintf(stderr,"** find_file_ext: failed for name '%s'\n", name);
2641 
2642    return NULL;
2643 }
2644 
2645 /*----------------------------------------------------------------------*/
2646 /*! return whether the filename ends in ".gz"
2647 *//*--------------------------------------------------------------------*/
nifti_is_gzfile(const char * fname)2648 int nifti_is_gzfile(const char* fname)
2649 {
2650   /* return true if the filename ends with .gz */
2651   if (fname == NULL) { return 0; }
2652 #ifdef HAVE_ZLIB
2653   { /* just so len doesn't generate compile warning */
2654      int len;
2655      len = (int)strlen(fname);
2656      if (len < 3) return 0;  /* so we don't search before the name */
2657      if (fileext_compare(fname + strlen(fname) - 3,".gz")==0) { return 1; }
2658   }
2659 #endif
2660   return 0;
2661 }
2662 
2663 /*----------------------------------------------------------------------*/
2664 /*! return whether the given library was compiled with HAVE_ZLIB set
2665 *//*--------------------------------------------------------------------*/
nifti_compiled_with_zlib(void)2666 int nifti_compiled_with_zlib(void)
2667 {
2668 #ifdef HAVE_ZLIB
2669     return 1;
2670 #else
2671     return 0;
2672 #endif
2673 }
2674 
2675 /*----------------------------------------------------------------------*/
2676 /*! duplicate the filename, while clearing any extension
2677 
2678     This allocates memory for basename which should eventually be freed.
2679 *//*--------------------------------------------------------------------*/
nifti_makebasename(const char * fname)2680 char * nifti_makebasename(const char* fname)
2681 {
2682    char *basename, *ext;
2683 
2684    basename=nifti_strdup(fname);
2685 
2686    ext = nifti_find_file_extension(basename);
2687    if ( ext ) *ext = '\0';  /* clear out extension */
2688 
2689    return basename;  /* in either case */
2690 }
2691 
2692 /*----------------------------------------------------------------------*/
2693 /*! set nifti's global debug level, for status reporting
2694 
2695     - 0    : quiet, nothing is printed to the terminal, but errors
2696     - 1    : normal execution (the default)
2697     - 2, 3 : more details
2698 *//*--------------------------------------------------------------------*/
nifti_set_debug_level(int level)2699 void nifti_set_debug_level( int level )
2700 {
2701     g_opts.debug = level;
2702 }
2703 
2704 /*----------------------------------------------------------------------*/
2705 /*! set nifti's global skip_blank_ext flag            5 Sep 2006 [rickr]
2706 
2707     explicitly set to 0 or 1
2708 *//*--------------------------------------------------------------------*/
nifti_set_skip_blank_ext(int skip)2709 void nifti_set_skip_blank_ext( int skip )
2710 {
2711     g_opts.skip_blank_ext = skip ? 1 : 0;
2712 }
2713 
2714 /*----------------------------------------------------------------------*/
2715 /*! set nifti's global allow_upper_fext flag         28 Apr 2009 [rickr]
2716 
2717     explicitly set to 0 or 1
2718 *//*--------------------------------------------------------------------*/
nifti_set_allow_upper_fext(int allow)2719 void nifti_set_allow_upper_fext( int allow )
2720 {
2721     g_opts.allow_upper_fext = allow ? 1 : 0;
2722 }
2723 
2724 /*----------------------------------------------------------------------*/
2725 /*! check current directory for existing header file
2726 
2727     \return filename of header on success and NULL if no appropriate file
2728             could be found
2729 
2730     If fname has an uppercase extension, check for uppercase files.
2731 
2732     NB: it allocates memory for hdrname which should be freed
2733         when no longer required
2734 *//*-------------------------------------------------------------------*/
nifti_findhdrname(const char * fname)2735 char * nifti_findhdrname(const char* fname)
2736 {
2737    char *basename, *hdrname, *ext;
2738    char  elist[2][5] = { ".hdr", ".nii" };
2739    char  extzip[4]   = ".gz";
2740    int   efirst = 1;    /* init to .nii extension */
2741    int   eisupper = 0;  /* init to lowercase extensions */
2742 
2743    /**- check input file(s) for sanity */
2744    if( !nifti_validfilename(fname) ) return NULL;
2745 
2746    basename = nifti_makebasename(fname);
2747    if( !basename ) return NULL;   /* only on string alloc failure */
2748 
2749    /**- return filename if it has a valid extension and exists
2750          (except if it is an .img file (and maybe .gz)) */
2751    ext = nifti_find_file_extension(fname);
2752 
2753    if( ext ) eisupper = is_uppercase(ext);  /* do we look for uppercase? */
2754 
2755    /* if the file exists and is a valid header name (not .img), return it */
2756    if ( ext && nifti_fileexists(fname) ) {
2757      /* allow for uppercase extension */
2758      if ( fileext_n_compare(ext,".img",4) != 0 ){
2759         hdrname = nifti_strdup(fname);
2760         free(basename);
2761         return hdrname;
2762      } else
2763         efirst = 0;     /* note for below */
2764    }
2765 
2766    /* So the requested name is a basename, contains .img, or does not exist. */
2767    /* In any case, use basename. */
2768 
2769    /**- if .img, look for .hdr, .hdr.gz, .nii, .nii.gz, in that order */
2770    /**- else,    look for .nii, .nii.gz, .hdr, .hdr.gz, in that order */
2771 
2772    /* if we get more extension choices, this could be a loop */
2773 
2774    /* note: efirst is 0 in the case of ".img" */
2775 
2776    /* if the user passed an uppercase entension (.IMG), search for uppercase */
2777    if( eisupper ) {
2778       make_uppercase(elist[0]);
2779       make_uppercase(elist[1]);
2780       make_uppercase(extzip);
2781    }
2782 
2783    hdrname = (char *)calloc(sizeof(char),strlen(basename)+8);
2784    if( !hdrname ){
2785       fprintf(stderr,"** nifti_findhdrname: failed to alloc hdrname\n");
2786       free(basename);
2787       return NULL;
2788    }
2789 
2790    strcpy(hdrname,basename);
2791    strcat(hdrname,elist[efirst]);
2792    if (nifti_fileexists(hdrname)) { free(basename); return hdrname; }
2793 #ifdef HAVE_ZLIB
2794    strcat(hdrname,extzip);
2795    if (nifti_fileexists(hdrname)) { free(basename); return hdrname; }
2796 #endif
2797 
2798    /* okay, try the other possibility */
2799 
2800    efirst = 1 - efirst;
2801 
2802    strcpy(hdrname,basename);
2803    strcat(hdrname,elist[efirst]);
2804    if (nifti_fileexists(hdrname)) { free(basename); return hdrname; }
2805 #ifdef HAVE_ZLIB
2806    strcat(hdrname,extzip);
2807    if (nifti_fileexists(hdrname)) { free(basename); return hdrname; }
2808 #endif
2809 
2810    /**- if nothing has been found, return NULL */
2811    free(basename);
2812    free(hdrname);
2813    return NULL;
2814 }
2815 
2816 
2817 /*------------------------------------------------------------------------*/
2818 /*! check current directory for existing image file
2819 
2820     \param fname filename to check for
2821     \nifti_type  nifti_type for dataset - this determines whether to
2822                  first check for ".nii" or ".img" (since both may exist)
2823 
2824     \return filename of data/img file on success and NULL if no appropriate
2825             file could be found
2826 
2827     If fname has a valid, uppercase extension, apply all extensions as
2828     uppercase.
2829 
2830     NB: it allocates memory for the image filename, which should be freed
2831         when no longer required
2832 *//*---------------------------------------------------------------------*/
nifti_findimgname(const char * fname,int nifti_type)2833 char * nifti_findimgname(const char* fname , int nifti_type)
2834 {
2835    /* store all extensions as strings, in case we need to go uppercase */
2836    char *basename, *imgname, elist[2][5] = { ".nii", ".img" };
2837    char  extzip[4] = ".gz";
2838    char  extnia[5] = ".nia";
2839    char *ext;
2840    int   first;  /* first extension to use */
2841 
2842    /* check input file(s) for sanity */
2843    if( !nifti_validfilename(fname) ) return NULL;
2844 
2845    basename =  nifti_makebasename(fname);
2846    imgname = (char *)calloc(sizeof(char),strlen(basename)+8);
2847    if( !imgname ){
2848       fprintf(stderr,"** nifti_findimgname: failed to alloc imgname\n");
2849       free(basename);
2850       return NULL;
2851    }
2852 
2853    /* if we are looking for uppercase, apply the fact now */
2854    ext = nifti_find_file_extension(fname);
2855    if( ext && is_uppercase(ext) ) {
2856       make_uppercase(elist[0]);
2857       make_uppercase(elist[1]);
2858       make_uppercase(extzip);
2859       make_uppercase(extnia);
2860    }
2861 
2862    /* only valid extension for ASCII type is .nia, handle first */
2863    if( nifti_type == NIFTI_FTYPE_ASCII ){
2864       strcpy(imgname,basename);
2865       strcat(imgname,extnia);
2866       if (nifti_fileexists(imgname)) { free(basename); return imgname; }
2867 
2868    } else {
2869 
2870       /**- test for .nii and .img (don't assume input type from image type) */
2871       /**- if nifti_type = 1, check for .nii first, else .img first         */
2872 
2873       /* if we get 3 or more extensions, can make a loop here... */
2874 
2875       if (nifti_type == NIFTI_FTYPE_NIFTI1_1) first = 0; /* should match .nii */
2876       else                                    first = 1; /* should match .img */
2877 
2878       strcpy(imgname,basename);
2879       strcat(imgname,elist[first]);
2880       if (nifti_fileexists(imgname)) { free(basename); return imgname; }
2881 #ifdef HAVE_ZLIB  /* then also check for .gz */
2882       strcat(imgname,extzip);
2883       if (nifti_fileexists(imgname)) { free(basename); return imgname; }
2884 #endif
2885 
2886       /* failed to find image file with expected extension, try the other */
2887 
2888       strcpy(imgname,basename);
2889       strcat(imgname,elist[1-first]);  /* can do this with only 2 choices */
2890       if (nifti_fileexists(imgname)) { free(basename); return imgname; }
2891 #ifdef HAVE_ZLIB  /* then also check for .gz */
2892       strcat(imgname,extzip);
2893       if (nifti_fileexists(imgname)) { free(basename); return imgname; }
2894 #endif
2895    }
2896 
2897    /**- if nothing has been found, return NULL */
2898    free(basename);
2899    free(imgname);
2900    return NULL;
2901 }
2902 
2903 
2904 /*----------------------------------------------------------------------*/
2905 /*! creates a filename for storing the header, based on nifti_type
2906 
2907    \param   prefix      - this will be copied before the suffix is added
2908    \param   nifti_type  - determines the extension, unless one is in prefix
2909    \param   check       - check for existence (fail condition)
2910    \param   comp        - add .gz for compressed name
2911 
2912    Note that if prefix provides a file suffix, nifti_type is not used.
2913 
2914    NB: this allocates memory which should be freed
2915 
2916    \sa nifti_set_filenames
2917 *//*-------------------------------------------------------------------*/
nifti_makehdrname(const char * prefix,int nifti_type,int check,int comp)2918 char * nifti_makehdrname(const char * prefix, int nifti_type, int check,
2919                          int comp)
2920 {
2921    char * iname, * ext;
2922    char   extnii[5] = ".nii";   /* modifiable, for possible uppercase */
2923    char   exthdr[5] = ".hdr";
2924    char   extimg[5] = ".img";
2925    char   extnia[5] = ".nia";
2926    char   extgz[5]  = ".gz";
2927 
2928    if( !nifti_validfilename(prefix) ) return NULL;
2929 
2930    /* add space for extension, optional ".gz", and null char */
2931    iname = (char *)calloc(sizeof(char),strlen(prefix)+8);
2932    if( !iname ){ fprintf(stderr,"** small malloc failure!\n"); return NULL; }
2933    strcpy(iname, prefix);
2934 
2935    /* use any valid extension */
2936    if( (ext = nifti_find_file_extension(iname)) != NULL ){
2937       /* if uppercase, convert all extensions */
2938       if( is_uppercase(ext) ) {
2939          make_uppercase(extnii);
2940          make_uppercase(exthdr);
2941          make_uppercase(extimg);
2942          make_uppercase(extnia);
2943          make_uppercase(extgz);
2944       }
2945 
2946       if( strncmp(ext,extimg,4) == 0 )
2947          memcpy(ext,exthdr,4);   /* then convert img name to hdr */
2948    }
2949    /* otherwise, make one up */
2950    else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, extnii);
2951    else if( nifti_type == NIFTI_FTYPE_ASCII )    strcat(iname, extnia);
2952    else                                          strcat(iname, exthdr);
2953 
2954 #ifdef HAVE_ZLIB  /* if compression is requested, make sure of suffix */
2955    if( comp && (!ext || !strstr(iname,extgz)) ) strcat(iname,extgz);
2956 #endif
2957 
2958    /* check for existence failure */
2959    if( check && nifti_fileexists(iname) ){
2960       fprintf(stderr,"** failure: header file '%s' already exists\n",iname);
2961       free(iname);
2962       return NULL;
2963    }
2964 
2965    if(g_opts.debug > 2) fprintf(stderr,"+d made header filename '%s'\n", iname);
2966 
2967    return iname;
2968 }
2969 
2970 
2971 /*----------------------------------------------------------------------*/
2972 /*! creates a filename for storing the image, based on nifti_type
2973 
2974    \param   prefix      - this will be copied before the suffix is added
2975    \param   nifti_type  - determines the extension, unless provided by prefix
2976    \param   check       - check for existence (fail condition)
2977    \param   comp        - add .gz for compressed name
2978 
2979    Note that if prefix provides a file suffix, nifti_type is not used.
2980 
2981    NB: it allocates memory which should be freed
2982 
2983    \sa nifti_set_filenames
2984 *//*-------------------------------------------------------------------*/
nifti_makeimgname(const char * prefix,int nifti_type,int check,int comp)2985 char * nifti_makeimgname(const char * prefix, int nifti_type, int check,
2986                          int comp)
2987 {
2988    char * iname, * ext;
2989    char   extnii[5] = ".nii";   /* modifiable, for possible uppercase */
2990    char   exthdr[5] = ".hdr";
2991    char   extimg[5] = ".img";
2992    char   extnia[5] = ".nia";
2993    char   extgz[5]  = ".gz";
2994 
2995    if( !nifti_validfilename(prefix) ) return NULL;
2996 
2997    /* add space for extension, optional ".gz", and null char */
2998    iname = (char *)calloc(sizeof(char),strlen(prefix)+8);
2999    if( !iname ){ fprintf(stderr,"** small malloc failure!\n"); return NULL; }
3000    strcpy(iname, prefix);
3001 
3002    /* use any valid extension */
3003    if( (ext = nifti_find_file_extension(iname)) != NULL ){
3004       /* if uppercase, convert all extensions */
3005       if( is_uppercase(ext) ) {
3006          make_uppercase(extnii);
3007          make_uppercase(exthdr);
3008          make_uppercase(extimg);
3009          make_uppercase(extnia);
3010          make_uppercase(extgz);
3011       }
3012 
3013       if( strncmp(ext,exthdr,4) == 0 )
3014          memcpy(ext,extimg,4);   /* then convert hdr name to img */
3015    }
3016    /* otherwise, make one up */
3017    else if( nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcat(iname, extnii);
3018    else if( nifti_type == NIFTI_FTYPE_ASCII )    strcat(iname, extnia);
3019    else                                          strcat(iname, extimg);
3020 
3021 #ifdef HAVE_ZLIB  /* if compression is requested, make sure of suffix */
3022    if( comp && (!ext || !strstr(iname,extgz)) ) strcat(iname,extgz);
3023 #endif
3024 
3025    /* check for existence failure */
3026    if( check && nifti_fileexists(iname) ){
3027       fprintf(stderr,"** failure: image file '%s' already exists\n",iname);
3028       free(iname);
3029       return NULL;
3030    }
3031 
3032    if( g_opts.debug > 2 ) fprintf(stderr,"+d made image filename '%s'\n",iname);
3033 
3034    return iname;
3035 }
3036 
3037 
3038 /*----------------------------------------------------------------------*/
3039 /*! create and set new filenames, based on prefix and image type
3040 
3041    \param nim            pointer to nifti_image in which to set filenames
3042    \param prefix         (required) prefix for output filenames
3043    \param check          check for previous existence of filename
3044                          (existence is an error condition)
3045    \param set_byte_order flag to set nim->byteorder here
3046                          (this is probably a logical place to do so)
3047 
3048    \return 0 on successful update
3049 
3050    \warning this will free() any existing names and create new ones
3051 
3052    \sa nifti_makeimgname, nifti_makehdrname, nifti_type_and_names_match
3053 *//*--------------------------------------------------------------------*/
nifti_set_filenames(nifti_image * nim,const char * prefix,int check,int set_byte_order)3054 int nifti_set_filenames( nifti_image * nim, const char * prefix, int check,
3055                          int set_byte_order )
3056 {
3057    int comp = nifti_is_gzfile(prefix);
3058 
3059    if( !nim || !prefix ){
3060       fprintf(stderr,"** nifti_set_filenames, bad params %p, %p\n",
3061               (void *)nim,prefix);
3062       return -1;
3063    }
3064 
3065    if( g_opts.debug > 1 )
3066       fprintf(stderr,"+d modifying output filenames using prefix %s\n", prefix);
3067 
3068    if( nim->fname ) free(nim->fname);
3069    if( nim->iname ) free(nim->iname);
3070    nim->fname = nifti_makehdrname(prefix, nim->nifti_type, check, comp);
3071    nim->iname = nifti_makeimgname(prefix, nim->nifti_type, check, comp);
3072    if( !nim->fname || !nim->iname ){
3073       LNI_FERR("nifti_set_filename","failed to set prefix for",prefix);
3074       return -1;
3075    }
3076 
3077    if( set_byte_order ) nim->byteorder = nifti_short_order() ;
3078 
3079    if( nifti_set_type_from_names(nim) < 0 )
3080       return -1;
3081 
3082    if( g_opts.debug > 2 )
3083       fprintf(stderr,"+d have new filenames %s and %s\n",nim->fname,nim->iname);
3084 
3085    return 0;
3086 }
3087 
3088 
3089 /*--------------------------------------------------------------------------*/
3090 /*! check whether nifti_type matches fname and iname for the nifti_image
3091 
3092     - if type 0 or 2, expect .hdr/.img pair
3093     - if type 1, expect .nii (and names must match)
3094 
3095     \param nim       given nifti_image
3096     \param show_warn if set, print a warning message for any mis-match
3097 
3098     \return
3099         -   1 if the values seem to match
3100         -   0 if there is a mis-match
3101         -  -1 if there is not sufficient information to create file(s)
3102 
3103     \sa NIFTI_FTYPE_* codes in nifti1_io.h
3104     \sa nifti_set_type_from_names, is_valid_nifti_type
3105 *//*------------------------------------------------------------------------*/
nifti_type_and_names_match(nifti_image * nim,int show_warn)3106 int nifti_type_and_names_match( nifti_image * nim, int show_warn )
3107 {
3108    char func[] = "nifti_type_and_names_match";
3109    char * ext_h, * ext_i;  /* header and image filename extensions */
3110    int  errs = 0;          /* error counter */
3111 
3112    /* sanity checks */
3113    if( !nim ){
3114       if( show_warn ) fprintf(stderr,"** %s: missing nifti_image\n", func);
3115       return -1;
3116    }
3117    if( !nim->fname ){
3118       if( show_warn ) fprintf(stderr,"** %s: missing header filename\n", func);
3119       errs++;
3120    }
3121    if( !nim->iname ){
3122       if( show_warn ) fprintf(stderr,"** %s: missing image filename\n", func);
3123       errs++;
3124    }
3125    if( !is_valid_nifti_type(nim->nifti_type) ){
3126       if( show_warn )
3127          fprintf(stderr,"** %s: bad nifti_type %d\n", func, nim->nifti_type);
3128       errs++;
3129    }
3130 
3131    if( errs ) return -1;   /* then do not proceed */
3132 
3133    /* get pointers to extensions */
3134    ext_h = nifti_find_file_extension( nim->fname );
3135    ext_i = nifti_find_file_extension( nim->iname );
3136 
3137    /* check for filename extensions */
3138    if( !ext_h ){
3139       if( show_warn )
3140          fprintf(stderr,"-d missing NIFTI extension in header filename, %s\n",
3141                  nim->fname);
3142       errs++;
3143    }
3144    if( !ext_i ){
3145       if( show_warn )
3146          fprintf(stderr,"-d missing NIFTI extension in image filename, %s\n",
3147                  nim->iname);
3148       errs++;
3149    }
3150 
3151    if( errs ) return 0;   /* do not proceed, but this is just a mis-match */
3152 
3153    /* general tests */
3154    if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ){  /* .nii */
3155       if( fileext_n_compare(ext_h,".nii",4) ) {
3156          if( show_warn )
3157             fprintf(stderr,
3158             "-d NIFTI_FTYPE 1, but no .nii extension in header filename, %s\n",
3159             nim->fname);
3160          errs++;
3161       }
3162       if( fileext_n_compare(ext_i,".nii",4) ) {
3163          if( show_warn )
3164             fprintf(stderr,
3165             "-d NIFTI_FTYPE 1, but no .nii extension in image filename, %s\n",
3166             nim->iname);
3167          errs++;
3168       }
3169       if( strcmp(nim->fname, nim->iname) != 0 ){
3170          if( show_warn )
3171             fprintf(stderr,
3172             "-d NIFTI_FTYPE 1, but header and image filenames differ: %s, %s\n",
3173             nim->fname, nim->iname);
3174          errs++;
3175       }
3176    }
3177    else if( (nim->nifti_type == NIFTI_FTYPE_NIFTI1_2) || /* .hdr/.img */
3178             (nim->nifti_type == NIFTI_FTYPE_ANALYZE) )
3179    {
3180       if( fileext_n_compare(ext_h,".hdr",4) != 0 ){
3181          if( show_warn )
3182             fprintf(stderr,"-d no '.hdr' extension, but NIFTI type is %d, %s\n",
3183                     nim->nifti_type, nim->fname);
3184          errs++;
3185       }
3186       if( fileext_n_compare(ext_i,".img",4) != 0 ){
3187          if( show_warn )
3188             fprintf(stderr,"-d no '.img' extension, but NIFTI type is %d, %s\n",
3189                     nim->nifti_type, nim->iname);
3190          errs++;
3191       }
3192    }
3193    /* ignore any other nifti_type */
3194 
3195    return 1;
3196 }
3197 
3198 /* like strcmp, but also check against capitalization of known_ext
3199  * (test as local string, with max length 7) */
fileext_compare(const char * test_ext,const char * known_ext)3200 static int fileext_compare(const char * test_ext, const char * known_ext)
3201 {
3202    char caps[8] = "";
3203    int  c, cmp, len;
3204 
3205    /* if equal, don't need to check case (store to avoid multiple calls) */
3206    cmp = strcmp(test_ext, known_ext);
3207    if( cmp == 0 ) return cmp;
3208 
3209    /* if anything odd, use default */
3210    if( !test_ext || !known_ext ) return cmp;
3211 
3212    len = strlen(known_ext);
3213    if( len > 7 ) return cmp;
3214 
3215    /* if here, strings are different but need to check upper-case */
3216 
3217    for(c = 0; c < len; c++ ) caps[c] = toupper(known_ext[c]);
3218    caps[c] = '\0';
3219 
3220    return strcmp(test_ext, caps);
3221 }
3222 
3223 /* like strncmp, but also check against capitalization of known_ext
3224  * (test as local string, with max length 7) */
fileext_n_compare(const char * test_ext,const char * known_ext,int maxlen)3225 static int fileext_n_compare(const char * test_ext,
3226                              const char * known_ext, int maxlen)
3227 {
3228    char caps[8] = "";
3229    int  c, cmp, len;
3230 
3231    /* if equal, don't need to check case (store to avoid multiple calls) */
3232    cmp = strncmp(test_ext, known_ext, maxlen);
3233    if( cmp == 0 ) return cmp;
3234 
3235    /* if anything odd, use default */
3236    if( !test_ext || !known_ext ) return cmp;
3237 
3238    len = strlen(known_ext);
3239    if( len > maxlen ) len = maxlen;     /* ignore anything past maxlen */
3240    if( len > 7 ) return cmp;
3241 
3242    /* if here, strings are different but need to check upper-case */
3243 
3244    for(c = 0; c < len; c++ ) caps[c] = toupper(known_ext[c]);
3245    caps[c] = '\0';
3246 
3247    return strncmp(test_ext, caps, maxlen);
3248 }
3249 
3250 /* return 1 if there are uppercase but no lowercase */
is_uppercase(const char * str)3251 static int is_uppercase(const char * str)
3252 {
3253    int c, hasupper = 0;
3254 
3255    if( !str || !*str ) return 0;
3256 
3257    for(c = 0; c < strlen(str); c++ ) {
3258       if( islower(str[c]) ) return 0;
3259       if( !hasupper && isupper(str[c]) ) hasupper = 1;
3260    }
3261 
3262    return hasupper;
3263 }
3264 
3265 /* return 1 if there are both uppercase and lowercase characters */
is_mixedcase(const char * str)3266 static int is_mixedcase(const char * str)
3267 {
3268    int c, hasupper = 0, haslower = 0;
3269 
3270    if( !str || !*str ) return 0;
3271 
3272    for(c = 0; c < strlen(str); c++ ) {
3273       if( !haslower && islower(str[c]) ) haslower = 1;
3274       if( !hasupper && isupper(str[c]) ) hasupper = 1;
3275 
3276       if( haslower && hasupper ) return 1;
3277    }
3278 
3279    return 0;
3280 }
3281 
3282 /* convert any lowercase chars to uppercase */
make_uppercase(char * str)3283 static int make_uppercase(char * str)
3284 {
3285    int c;
3286 
3287    if( !str || !*str ) return 0;
3288 
3289    for(c = 0; c < strlen(str); c++ )
3290       if( islower(str[c]) ) str[c] = toupper(str[c]);
3291 
3292    return 0;
3293 }
3294 
3295 /* convert any uppercase chars to lowercase */
make_lowercase(char * str)3296 static int make_lowercase(char * str)
3297 {
3298    int c;
3299 
3300    if( !str || !*str ) return 0;
3301 
3302    for(c = 0; c < strlen(str); c++ )
3303       if( isupper(str[c]) ) str[c] = tolower(str[c]);
3304 
3305    return 0;
3306 }
3307 
3308 /* run strcmp against of list of strings
3309  * return index of equality, if found
3310  * else return -1 */
compare_strlist(const char * str,char ** strlist,int len)3311 static int compare_strlist(const char * str, char ** strlist, int len)
3312 {
3313    int c;
3314    if( len <= 0 || !str || !strlist ) return -1;
3315    for( c = 0; c < len; c++ )
3316       if( strlist[c] && !strcmp(str, strlist[c]) ) return c;
3317    return -1;
3318 }
3319 
3320 /*--------------------------------------------------------------------------*/
3321 /*! check whether the given type is on the "approved" list
3322 
3323     The code is valid if it is non-negative, and does not exceed
3324     NIFTI_MAX_FTYPE.
3325 
3326     \return 1 if nifti_type is valid, 0 otherwise
3327     \sa NIFTI_FTYPE_* codes in nifti1_io.h
3328 *//*------------------------------------------------------------------------*/
is_valid_nifti_type(int nifti_type)3329 int is_valid_nifti_type( int nifti_type )
3330 {
3331    if( nifti_type >= NIFTI_FTYPE_ANALYZE &&   /* smallest type, 0 */
3332        nifti_type <= NIFTI_MAX_FTYPE )
3333       return 1;
3334    return 0;
3335 }
3336 
3337 
3338 /*--------------------------------------------------------------------------*/
3339 /*! check whether the given type is on the "approved" list
3340 
3341     The type is explicitly checked against the NIFTI_TYPE_* list
3342     in nifti1.h.
3343 
3344     \return 1 if dtype is valid, 0 otherwise
3345     \sa NIFTI_TYPE_* codes in nifti1.h
3346 *//*------------------------------------------------------------------------*/
nifti_is_valid_datatype(int dtype)3347 int nifti_is_valid_datatype( int dtype )
3348 {
3349    if( dtype == NIFTI_TYPE_UINT8        ||
3350        dtype == NIFTI_TYPE_INT16        ||
3351        dtype == NIFTI_TYPE_INT32        ||
3352        dtype == NIFTI_TYPE_FLOAT32      ||
3353        dtype == NIFTI_TYPE_COMPLEX64    ||
3354        dtype == NIFTI_TYPE_FLOAT64      ||
3355        dtype == NIFTI_TYPE_RGB24        ||
3356        dtype == NIFTI_TYPE_RGBA32       ||
3357        dtype == NIFTI_TYPE_INT8         ||
3358        dtype == NIFTI_TYPE_UINT16       ||
3359        dtype == NIFTI_TYPE_UINT32       ||
3360        dtype == NIFTI_TYPE_INT64        ||
3361        dtype == NIFTI_TYPE_UINT64       ||
3362        dtype == NIFTI_TYPE_FLOAT128     ||
3363        dtype == NIFTI_TYPE_COMPLEX128   ||
3364        dtype == NIFTI_TYPE_COMPLEX256 ) return 1;
3365    return 0;
3366 }
3367 
3368 
3369 /*--------------------------------------------------------------------------*/
3370 /*! set the nifti_type field based on fname and iname
3371 
3372     Note that nifti_type is changed only when it does not match
3373     the filenames.
3374 
3375     \return 0 on success, -1 on error
3376 
3377     \sa is_valid_nifti_type, nifti_type_and_names_match
3378 *//*------------------------------------------------------------------------*/
nifti_set_type_from_names(nifti_image * nim)3379 int nifti_set_type_from_names( nifti_image * nim )
3380 {
3381    /* error checking first */
3382    if( !nim ){ fprintf(stderr,"** NSTFN: no nifti_image\n");  return -1; }
3383 
3384    if( !nim->fname || !nim->iname ){
3385       fprintf(stderr,"** NSTFN: missing filename(s) fname @ %p, iname @ %p\n",
3386               nim->fname, nim->iname);
3387       return -1;
3388    }
3389 
3390    if( ! nifti_validfilename      ( nim->fname ) ||
3391        ! nifti_validfilename      ( nim->iname ) ||
3392        ! nifti_find_file_extension( nim->fname ) ||
3393        ! nifti_find_file_extension( nim->iname )
3394      ) {
3395       fprintf(stderr,"** NSTFN: invalid filename(s) fname='%s', iname='%s'\n",
3396               nim->fname, nim->iname);
3397       return -1;
3398    }
3399 
3400    if( g_opts.debug > 2 )
3401       fprintf(stderr,"-d verify nifti_type from filenames: %d",nim->nifti_type);
3402 
3403    /* type should be NIFTI_FTYPE_ASCII if extension is .nia */
3404    if( (fileext_compare(nifti_find_file_extension(nim->fname),".nia")==0)){
3405       nim->nifti_type = NIFTI_FTYPE_ASCII;
3406    } else {
3407       /* not too picky here, do what must be done, and then verify */
3408       if( strcmp(nim->fname, nim->iname) == 0 )          /* one file, type 1 */
3409          nim->nifti_type = NIFTI_FTYPE_NIFTI1_1;
3410       else if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ) /* cannot be type 1 */
3411          nim->nifti_type = NIFTI_FTYPE_NIFTI1_2;
3412    }
3413 
3414    if( g_opts.debug > 2 ) fprintf(stderr," -> %d\n",nim->nifti_type);
3415 
3416    if( g_opts.debug > 1 )  /* warn user about anything strange */
3417       nifti_type_and_names_match(nim, 1);
3418 
3419    if( is_valid_nifti_type(nim->nifti_type) ) return 0;  /* success! */
3420 
3421    fprintf(stderr,"** NSTFN: bad nifti_type %d, for '%s' and '%s'\n",
3422            nim->nifti_type, nim->fname, nim->iname);
3423 
3424    return -1;
3425 }
3426 
3427 
3428 /*--------------------------------------------------------------------------*/
3429 /*! Determine if this is a NIFTI-formatted file.
3430 
3431    <pre>
3432    \return  0 if file looks like ANALYZE 7.5 [checks sizeof_hdr field == 348]
3433             1 if file marked as NIFTI (header+data in 1 file)
3434             2 if file marked as NIFTI (header+data in 2 files)
3435            -1 if it can't tell, file doesn't exist, etc.
3436    </pre>
3437 *//*------------------------------------------------------------------------*/
is_nifti_file(const char * hname)3438 int is_nifti_file( const char *hname )
3439 {
3440    struct nifti_1_header nhdr ;
3441    znzFile fp ;
3442    int ii ;
3443    char *tmpname;
3444 
3445    /* bad input name? */
3446 
3447    if( !nifti_validfilename(hname) ) return -1 ;
3448 
3449    /* open file */
3450 
3451    tmpname = nifti_findhdrname(hname);
3452    if( tmpname == NULL ){
3453       if( g_opts.debug > 0 )
3454          fprintf(stderr,"** no header file found for '%s'\n",hname);
3455       return -1;
3456    }
3457    fp = znzopen( tmpname , "rb" , nifti_is_gzfile(tmpname) ) ;
3458    free(tmpname);
3459    if (znz_isnull(fp))                      return -1 ;  /* bad open? */
3460 
3461    /* read header, close file */
3462 
3463    ii = (int)znzread( &nhdr , 1 , sizeof(nhdr) , fp ) ;
3464    znzclose( fp ) ;
3465    if( ii < (int) sizeof(nhdr) )               return -1 ;  /* bad read? */
3466 
3467    /* check for NIFTI-ness */
3468 
3469    if( NIFTI_VERSION(nhdr) != 0 ){
3470      return ( NIFTI_ONEFILE(nhdr) ) ? 1 : 2 ;
3471    }
3472 
3473    /* check for ANALYZE-ness (sizeof_hdr field == 348) */
3474 
3475    ii = nhdr.sizeof_hdr ;
3476    if( ii == (int)sizeof(nhdr) ) return 0 ;  /* matches */
3477 
3478    /* try byte-swapping header */
3479 
3480    swap_4(ii) ;
3481    if( ii == (int)sizeof(nhdr) ) return 0 ;  /* matches */
3482 
3483    return -1 ;                          /* not good */
3484 }
3485 
print_hex_vals(const char * data,int nbytes,FILE * fp)3486 static int print_hex_vals( const char * data, int nbytes, FILE * fp )
3487 {
3488    int c;
3489 
3490    if ( !data || nbytes < 1 || !fp ) return -1;
3491 
3492    fputs("0x", fp);
3493    for ( c = 0; c < nbytes; c++ )
3494       fprintf(fp, " %x", data[c]);
3495 
3496    return 0;
3497 }
3498 
3499 /*----------------------------------------------------------------------*/
3500 /*! display the contents of the nifti_1_header (send to stdout)
3501 
3502    \param info if non-NULL, print this character string
3503    \param hp   pointer to nifti_1_header
3504 *//*--------------------------------------------------------------------*/
disp_nifti_1_header(const char * info,const nifti_1_header * hp)3505 int disp_nifti_1_header( const char * info, const nifti_1_header * hp )
3506 {
3507    int c;
3508 
3509    fputs( "-------------------------------------------------------\n", stdout );
3510    if ( info )  fputs( info, stdout );
3511    if ( !hp  ){ fputs(" ** no nifti_1_header to display!\n",stdout); return 1; }
3512 
3513    fprintf(stdout," nifti_1_header :\n"
3514            "    sizeof_hdr     = %d\n"
3515            "    data_type[10]  = ", hp->sizeof_hdr);
3516    print_hex_vals(hp->data_type, 10, stdout);
3517    fprintf(stdout, "\n"
3518            "    db_name[18]    = ");
3519    print_hex_vals(hp->db_name, 18, stdout);
3520    fprintf(stdout, "\n"
3521            "    extents        = %d\n"
3522            "    session_error  = %d\n"
3523            "    regular        = 0x%x\n"
3524            "    dim_info       = 0x%x\n",
3525       hp->extents, hp->session_error, hp->regular, hp->dim_info );
3526    fprintf(stdout, "    dim[8]         =");
3527    for ( c = 0; c < 8; c++ ) fprintf(stdout," %d", hp->dim[c]);
3528    fprintf(stdout, "\n"
3529            "    intent_p1      = %f\n"
3530            "    intent_p2      = %f\n"
3531            "    intent_p3      = %f\n"
3532            "    intent_code    = %d\n"
3533            "    datatype       = %d\n"
3534            "    bitpix         = %d\n"
3535            "    slice_start    = %d\n"
3536            "    pixdim[8]      =",
3537            hp->intent_p1, hp->intent_p2, hp->intent_p3, hp->intent_code,
3538            hp->datatype, hp->bitpix, hp->slice_start);
3539    /* break pixdim over 2 lines */
3540    for ( c = 0; c < 4; c++ ) fprintf(stdout," %f", hp->pixdim[c]);
3541    fprintf(stdout, "\n                    ");
3542    for ( c = 4; c < 8; c++ ) fprintf(stdout," %f", hp->pixdim[c]);
3543    fprintf(stdout, "\n"
3544            "    vox_offset     = %f\n"
3545            "    scl_slope      = %f\n"
3546            "    scl_inter      = %f\n"
3547            "    slice_end      = %d\n"
3548            "    slice_code     = %d\n"
3549            "    xyzt_units     = 0x%x\n"
3550            "    cal_max        = %f\n"
3551            "    cal_min        = %f\n"
3552            "    slice_duration = %f\n"
3553            "    toffset        = %f\n"
3554            "    glmax          = %d\n"
3555            "    glmin          = %d\n",
3556            hp->vox_offset, hp->scl_slope, hp->scl_inter, hp->slice_end,
3557            hp->slice_code, hp->xyzt_units, hp->cal_max, hp->cal_min,
3558            hp->slice_duration, hp->toffset, hp->glmax, hp->glmin);
3559    fprintf(stdout,
3560            "    descrip        = '%.80s'\n"
3561            "    aux_file       = '%.24s'\n"
3562            "    qform_code     = %d\n"
3563            "    sform_code     = %d\n"
3564            "    quatern_b      = %f\n"
3565            "    quatern_c      = %f\n"
3566            "    quatern_d      = %f\n"
3567            "    qoffset_x      = %f\n"
3568            "    qoffset_y      = %f\n"
3569            "    qoffset_z      = %f\n"
3570            "    srow_x[4]      = %f, %f, %f, %f\n"
3571            "    srow_y[4]      = %f, %f, %f, %f\n"
3572            "    srow_z[4]      = %f, %f, %f, %f\n"
3573            "    intent_name    = '%-.16s'\n"
3574            "    magic          = '%-.4s'\n",
3575            hp->descrip, hp->aux_file, hp->qform_code, hp->sform_code,
3576            hp->quatern_b, hp->quatern_c, hp->quatern_d,
3577            hp->qoffset_x, hp->qoffset_y, hp->qoffset_z,
3578            hp->srow_x[0], hp->srow_x[1], hp->srow_x[2], hp->srow_x[3],
3579            hp->srow_y[0], hp->srow_y[1], hp->srow_y[2], hp->srow_y[3],
3580            hp->srow_z[0], hp->srow_z[1], hp->srow_z[2], hp->srow_z[3],
3581            hp->intent_name, hp->magic);
3582    fputs( "-------------------------------------------------------\n", stdout );
3583    fflush(stdout);
3584 
3585    return 0;
3586 }
3587 
3588 
3589 #undef  ERREX
3590 #define ERREX(msg)                                           \
3591  do{ fprintf(stderr,"** ERROR: nifti_convert_nhdr2nim: %s\n", (msg) ) ;  \
3592      return NULL ; } while(0)
3593 
3594 /*----------------------------------------------------------------------*/
3595 /*! convert a nifti_1_header into a nift1_image
3596 
3597    \return an allocated nifti_image, or NULL on failure
3598 *//*--------------------------------------------------------------------*/
nifti_convert_nhdr2nim(struct nifti_1_header nhdr,const char * fname)3599 nifti_image* nifti_convert_nhdr2nim(struct nifti_1_header nhdr,
3600                                     const char * fname)
3601 {
3602    int   ii , doswap , ioff ;
3603    int   is_nifti , is_onefile ;
3604    nifti_image *nim;
3605 
3606    nim = (nifti_image *)calloc( 1 , sizeof(nifti_image) ) ;
3607    if( !nim ) ERREX("failed to allocate nifti image");
3608 
3609    /* be explicit with pointers */
3610    nim->fname = NULL;
3611    nim->iname = NULL;
3612    nim->data = NULL;
3613 
3614    /**- check if we must swap bytes */
3615 
3616    doswap = need_nhdr_swap(nhdr.dim[0], nhdr.sizeof_hdr); /* swap data flag */
3617 
3618    if( doswap < 0 ){
3619       if( doswap == -1 ) ERREX("bad dim[0]") ;
3620       ERREX("bad sizeof_hdr") ;  /* else */
3621    }
3622 
3623    /**- determine if this is a NIFTI-1 compliant header */
3624 
3625    is_nifti = NIFTI_VERSION(nhdr) ;
3626    /*
3627     * before swapping header, record the Analyze75 orient code
3628     */
3629    if(!is_nifti)
3630      {
3631      /**- in analyze75, the orient code is at the same address as
3632       *   qform_code, but it's just one byte
3633       *   the qform_code will be zero, at which point you can check
3634       *   analyze75_orient if you care to.
3635       */
3636      unsigned char c = *((char *)(&nhdr.qform_code));
3637      nim->analyze75_orient = (analyze_75_orient_code)c;
3638      }
3639    if( doswap ) {
3640       if ( g_opts.debug > 3 ) disp_nifti_1_header("-d ni1 pre-swap: ", &nhdr);
3641       swap_nifti_header( &nhdr , is_nifti ) ;
3642    }
3643 
3644    if ( g_opts.debug > 2 ) disp_nifti_1_header("-d nhdr2nim : ", &nhdr);
3645 
3646    if( nhdr.datatype == DT_BINARY ||
3647        nhdr.datatype == DT_UNKNOWN  )    ERREX("bad datatype") ;
3648 
3649    if( nhdr.dim[1] <= 0 )                ERREX("bad dim[1]") ;
3650 
3651    /* fix bad dim[] values in the defined dimension range */
3652    for( ii=2 ; ii <= nhdr.dim[0] ; ii++ )
3653      if( nhdr.dim[ii] <= 0 ) nhdr.dim[ii] = 1 ;
3654 
3655    /* fix any remaining bad dim[] values, so garbage does not propagate */
3656    /* (only values 0 or 1 seem rational, otherwise set to arbirary 1)   */
3657    for( ii=nhdr.dim[0]+1 ; ii <= 7 ; ii++ )
3658      if( nhdr.dim[ii] != 1 && nhdr.dim[ii] != 0) nhdr.dim[ii] = 1 ;
3659 
3660 #if 0  /* rely on dim[0], do not attempt to modify it   16 Nov 2005 [rickr] */
3661 
3662    /**- get number of dimensions (ignoring dim[0] now) */
3663    for( ii=7 ; ii >= 2 ; ii-- )            /* loop backwards until we  */
3664      if( nhdr.dim[ii] > 1 ) break ;        /* find a dim bigger than 1 */
3665    ndim = ii ;
3666 #endif
3667 
3668    /**- set bad grid spacings to 1.0 */
3669 
3670    for( ii=1 ; ii <= nhdr.dim[0] ; ii++ ){
3671      if( nhdr.pixdim[ii] == 0.0         ||
3672          !IS_GOOD_FLOAT(nhdr.pixdim[ii])  ) nhdr.pixdim[ii] = 1.0 ;
3673    }
3674 
3675   is_onefile = is_nifti && NIFTI_ONEFILE(nhdr) ;
3676 
3677   if( is_nifti ) nim->nifti_type = (is_onefile) ? NIFTI_FTYPE_NIFTI1_1
3678                                                 : NIFTI_FTYPE_NIFTI1_2 ;
3679   else           nim->nifti_type = NIFTI_FTYPE_ANALYZE ;
3680 
3681   ii = nifti_short_order() ;
3682   if( doswap )   nim->byteorder = REVERSE_ORDER(ii) ;
3683   else           nim->byteorder = ii ;
3684 
3685 
3686   /**- set dimensions of data array */
3687 
3688   nim->ndim = nim->dim[0] = nhdr.dim[0];
3689   nim->nx   = nim->dim[1] = nhdr.dim[1];
3690   nim->ny   = nim->dim[2] = nhdr.dim[2];
3691   nim->nz   = nim->dim[3] = nhdr.dim[3];
3692   nim->nt   = nim->dim[4] = nhdr.dim[4];
3693   nim->nu   = nim->dim[5] = nhdr.dim[5];
3694   nim->nv   = nim->dim[6] = nhdr.dim[6];
3695   nim->nw   = nim->dim[7] = nhdr.dim[7];
3696 
3697   for( ii=1, nim->nvox=1; ii <= nhdr.dim[0]; ii++ )
3698      nim->nvox *= nhdr.dim[ii];
3699 
3700   /**- set the type of data in voxels and how many bytes per voxel */
3701 
3702   nim->datatype = nhdr.datatype ;
3703 
3704   nifti_datatype_sizes( nim->datatype , &(nim->nbyper) , &(nim->swapsize) ) ;
3705   if( nim->nbyper == 0 ){ free(nim); ERREX("bad datatype"); }
3706 
3707   /**- set the grid spacings */
3708 
3709   nim->dx = nim->pixdim[1] = nhdr.pixdim[1] ;
3710   nim->dy = nim->pixdim[2] = nhdr.pixdim[2] ;
3711   nim->dz = nim->pixdim[3] = nhdr.pixdim[3] ;
3712   nim->dt = nim->pixdim[4] = nhdr.pixdim[4] ;
3713   nim->du = nim->pixdim[5] = nhdr.pixdim[5] ;
3714   nim->dv = nim->pixdim[6] = nhdr.pixdim[6] ;
3715   nim->dw = nim->pixdim[7] = nhdr.pixdim[7] ;
3716 
3717   /**- compute qto_xyz transformation from pixel indexes (i,j,k) to (x,y,z) */
3718 
3719   if( !is_nifti || nhdr.qform_code <= 0 ){
3720     /**- if not nifti or qform_code <= 0, use grid spacing for qto_xyz */
3721 
3722     nim->qto_xyz.m[0][0] = nim->dx ;  /* grid spacings */
3723     nim->qto_xyz.m[1][1] = nim->dy ;  /* along diagonal */
3724     nim->qto_xyz.m[2][2] = nim->dz ;
3725 
3726     /* off diagonal is zero */
3727 
3728     nim->qto_xyz.m[0][1]=nim->qto_xyz.m[0][2]=nim->qto_xyz.m[0][3] = 0.0;
3729     nim->qto_xyz.m[1][0]=nim->qto_xyz.m[1][2]=nim->qto_xyz.m[1][3] = 0.0;
3730     nim->qto_xyz.m[2][0]=nim->qto_xyz.m[2][1]=nim->qto_xyz.m[2][3] = 0.0;
3731 
3732     /* last row is always [ 0 0 0 1 ] */
3733 
3734     nim->qto_xyz.m[3][0]=nim->qto_xyz.m[3][1]=nim->qto_xyz.m[3][2] = 0.0;
3735     nim->qto_xyz.m[3][3]= 1.0 ;
3736 
3737     nim->qform_code = NIFTI_XFORM_UNKNOWN ;
3738 
3739     if( g_opts.debug > 1 ) fprintf(stderr,"-d no qform provided\n");
3740   } else {
3741     /**- else NIFTI: use the quaternion-specified transformation */
3742 
3743     nim->quatern_b = FIXED_FLOAT( nhdr.quatern_b ) ;
3744     nim->quatern_c = FIXED_FLOAT( nhdr.quatern_c ) ;
3745     nim->quatern_d = FIXED_FLOAT( nhdr.quatern_d ) ;
3746 
3747     nim->qoffset_x = FIXED_FLOAT(nhdr.qoffset_x) ;
3748     nim->qoffset_y = FIXED_FLOAT(nhdr.qoffset_y) ;
3749     nim->qoffset_z = FIXED_FLOAT(nhdr.qoffset_z) ;
3750 
3751     nim->qfac = (nhdr.pixdim[0] < 0.0) ? -1.0 : 1.0 ;  /* left-handedness? */
3752 
3753     nim->qto_xyz = nifti_quatern_to_mat44(
3754                       nim->quatern_b, nim->quatern_c, nim->quatern_d,
3755                       nim->qoffset_x, nim->qoffset_y, nim->qoffset_z,
3756                       nim->dx       , nim->dy       , nim->dz       ,
3757                       nim->qfac                                      ) ;
3758 
3759     nim->qform_code = nhdr.qform_code ;
3760 
3761     if( g_opts.debug > 1 )
3762        nifti_disp_matrix_orient("-d qform orientations:\n", nim->qto_xyz);
3763   }
3764 
3765   /**- load inverse transformation (x,y,z) -> (i,j,k) */
3766 
3767   nim->qto_ijk = nifti_mat44_inverse( nim->qto_xyz ) ;
3768 
3769   /**- load sto_xyz affine transformation, if present */
3770 
3771   if( !is_nifti || nhdr.sform_code <= 0 ){
3772     /**- if not nifti or sform_code <= 0, then no sto transformation */
3773 
3774     nim->sform_code = NIFTI_XFORM_UNKNOWN ;
3775 
3776     if( g_opts.debug > 1 ) fprintf(stderr,"-d no sform provided\n");
3777 
3778   } else {
3779     /**- else set the sto transformation from srow_*[] */
3780 
3781     nim->sto_xyz.m[0][0] = nhdr.srow_x[0] ;
3782     nim->sto_xyz.m[0][1] = nhdr.srow_x[1] ;
3783     nim->sto_xyz.m[0][2] = nhdr.srow_x[2] ;
3784     nim->sto_xyz.m[0][3] = nhdr.srow_x[3] ;
3785 
3786     nim->sto_xyz.m[1][0] = nhdr.srow_y[0] ;
3787     nim->sto_xyz.m[1][1] = nhdr.srow_y[1] ;
3788     nim->sto_xyz.m[1][2] = nhdr.srow_y[2] ;
3789     nim->sto_xyz.m[1][3] = nhdr.srow_y[3] ;
3790 
3791     nim->sto_xyz.m[2][0] = nhdr.srow_z[0] ;
3792     nim->sto_xyz.m[2][1] = nhdr.srow_z[1] ;
3793     nim->sto_xyz.m[2][2] = nhdr.srow_z[2] ;
3794     nim->sto_xyz.m[2][3] = nhdr.srow_z[3] ;
3795 
3796     /* last row is always [ 0 0 0 1 ] */
3797 
3798     nim->sto_xyz.m[3][0]=nim->sto_xyz.m[3][1]=nim->sto_xyz.m[3][2] = 0.0;
3799     nim->sto_xyz.m[3][3]= 1.0 ;
3800 
3801     nim->sto_ijk = nifti_mat44_inverse( nim->sto_xyz ) ;
3802 
3803     nim->sform_code = nhdr.sform_code ;
3804 
3805     if( g_opts.debug > 1 )
3806        nifti_disp_matrix_orient("-d sform orientations:\n", nim->sto_xyz);
3807   }
3808 
3809   /**- set miscellaneous NIFTI stuff */
3810 
3811   if( is_nifti ){
3812     nim->scl_slope   = FIXED_FLOAT( nhdr.scl_slope ) ;
3813     nim->scl_inter   = FIXED_FLOAT( nhdr.scl_inter ) ;
3814 
3815     nim->intent_code = nhdr.intent_code ;
3816 
3817     nim->intent_p1 = FIXED_FLOAT( nhdr.intent_p1 ) ;
3818     nim->intent_p2 = FIXED_FLOAT( nhdr.intent_p2 ) ;
3819     nim->intent_p3 = FIXED_FLOAT( nhdr.intent_p3 ) ;
3820 
3821     nim->toffset   = FIXED_FLOAT( nhdr.toffset ) ;
3822 
3823     memcpy(nim->intent_name,nhdr.intent_name,15); nim->intent_name[15] = '\0';
3824 
3825     nim->xyz_units  = XYZT_TO_SPACE(nhdr.xyzt_units) ;
3826     nim->time_units = XYZT_TO_TIME (nhdr.xyzt_units) ;
3827 
3828     nim->freq_dim  = DIM_INFO_TO_FREQ_DIM ( nhdr.dim_info ) ;
3829     nim->phase_dim = DIM_INFO_TO_PHASE_DIM( nhdr.dim_info ) ;
3830     nim->slice_dim = DIM_INFO_TO_SLICE_DIM( nhdr.dim_info ) ;
3831 
3832     nim->slice_code     = nhdr.slice_code  ;
3833     nim->slice_start    = nhdr.slice_start ;
3834     nim->slice_end      = nhdr.slice_end   ;
3835     nim->slice_duration = FIXED_FLOAT(nhdr.slice_duration) ;
3836   }
3837 
3838   /**- set Miscellaneous ANALYZE stuff */
3839 
3840   nim->cal_min = FIXED_FLOAT(nhdr.cal_min) ;
3841   nim->cal_max = FIXED_FLOAT(nhdr.cal_max) ;
3842 
3843   memcpy(nim->descrip ,nhdr.descrip ,79) ; nim->descrip [79] = '\0' ;
3844   memcpy(nim->aux_file,nhdr.aux_file,23) ; nim->aux_file[23] = '\0' ;
3845 
3846    /**- set ioff from vox_offset (but at least sizeof(header)) */
3847 
3848    is_onefile = is_nifti && NIFTI_ONEFILE(nhdr) ;
3849 
3850    if( is_onefile ){
3851      ioff = (int)nhdr.vox_offset ;
3852      if( ioff < (int) sizeof(nhdr) ) ioff = (int) sizeof(nhdr) ;
3853    } else {
3854      ioff = (int)nhdr.vox_offset ;
3855    }
3856    nim->iname_offset = ioff ;
3857 
3858 
3859    /**- deal with file names if set */
3860    if (fname!=NULL) {
3861        nifti_set_filenames(nim,fname,0,0);
3862        if (nim->iname==NULL)  { ERREX("bad filename"); }
3863    } else {
3864      nim->fname = NULL;
3865      nim->iname = NULL;
3866    }
3867 
3868    /* clear extension fields */
3869    nim->num_ext = 0;
3870    nim->ext_list = NULL;
3871 
3872    return nim;
3873 }
3874 
3875 #undef  ERREX
3876 #define ERREX(msg)                                           \
3877  do{ fprintf(stderr,"** ERROR: nifti_image_open(%s): %s\n",  \
3878              (hname != NULL) ? hname : "(null)" , (msg) ) ;  \
3879      return fptr ; } while(0)
3880 
3881 /***************************************************************
3882  * nifti_image_open
3883  ***************************************************************/
3884 /*! znzFile nifti_image_open( char *hname, char *opts , nifti_image **nim)
3885     \brief Read in NIFTI-1 or ANALYZE-7.5 file (pair) header information into a nifti_image struct.
3886 
3887     - The image data is not read from disk (it may be read later using
3888         nifti_image_load(), for example).
3889     - The image data will be stored in whatever data format the
3890         input data is; no scaling will be applied.
3891     - DT_BINARY data is not supported.
3892     - nifti_image_free() can be used to delete the returned struct,
3893         when you are done with it.
3894 
3895     \param hname filename of dataset .hdr or .nii file
3896     \param opts  options string for opening the header file
3897     \param nim   pointer to pointer to nifti_image struct
3898                  (this routine allocates the nifti_image struct)
3899     \return file pointer (gzippable) to the file with the image data,
3900                  ready for reading.
3901         <br>NULL if something fails badly.
3902     \sa nifti_image_load, nifti_image_free
3903  */
nifti_image_open(const char * hname,char * opts,nifti_image ** nim)3904 znzFile nifti_image_open(const char * hname, char * opts, nifti_image ** nim)
3905 {
3906   znzFile fptr=NULL;
3907   /* open the hdr and reading it in, but do not load the data  */
3908   *nim = nifti_image_read(hname,0);
3909   /* open the image file, ready for reading (compressed works for all reads) */
3910   if( ((*nim) == NULL)      || ((*nim)->iname == NULL) ||
3911       ((*nim)->nbyper <= 0) || ((*nim)->nvox <= 0)       )
3912      ERREX("bad header info") ;
3913 
3914   /* open image data file */
3915   fptr = znzopen( (*nim)->iname, opts, nifti_is_gzfile((*nim)->iname) );
3916   if( znz_isnull(fptr) ) ERREX("Can't open data file") ;
3917 
3918   return fptr;
3919 }
3920 
3921 
3922 /*----------------------------------------------------------------------*/
3923 /*! return an allocated and filled nifti_1_header struct
3924 
3925     Read the binary header from disk, and swap bytes if necessary.
3926 
3927     \return an allocated nifti_1_header struct, or NULL on failure
3928 
3929     \param hname   name of file containing header
3930     \param swapped if not NULL, return whether header bytes were swapped
3931     \param check   flag to check for invalid nifti_1_header
3932 
3933     \warning ASCII header type is not supported
3934 
3935     \sa nifti_image_read, nifti_image_free, nifti_image_read_bricks
3936 *//*--------------------------------------------------------------------*/
nifti_read_header(const char * hname,int * swapped,int check)3937 nifti_1_header * nifti_read_header(const char * hname, int * swapped, int check)
3938 {
3939    nifti_1_header   nhdr, * hptr;
3940    znzFile          fp;
3941    int              bytes, lswap;
3942    char           * hfile;
3943    char             fname[] = { "nifti_read_header" };
3944 
3945    /* determine file name to use for header */
3946    hfile = nifti_findhdrname(hname);
3947    if( hfile == NULL ){
3948       if( g_opts.debug > 0 )
3949          LNI_FERR(fname,"failed to find header file for", hname);
3950       return NULL;
3951    } else if( g_opts.debug > 1 )
3952       fprintf(stderr,"-d %s: found header filename '%s'\n",fname,hfile);
3953 
3954    fp = znzopen( hfile, "rb", nifti_is_gzfile(hfile) );
3955    if( znz_isnull(fp) ){
3956       if( g_opts.debug > 0 ) LNI_FERR(fname,"failed to open header file",hfile);
3957       free(hfile);
3958       return NULL;
3959    }
3960 
3961    free(hfile);  /* done with filename */
3962 
3963    if( has_ascii_header(fp) == 1 ){
3964       znzclose( fp );
3965       if( g_opts.debug > 0 )
3966          LNI_FERR(fname,"ASCII header type not supported",hname);
3967       return NULL;
3968    }
3969 
3970    /* read the binary header */
3971    bytes = (int)znzread( &nhdr, 1, sizeof(nhdr), fp );
3972    znzclose( fp );                      /* we are done with the file now */
3973 
3974    if( bytes < (int)sizeof(nhdr) ){
3975       if( g_opts.debug > 0 ){
3976          LNI_FERR(fname,"bad binary header read for file", hname);
3977          fprintf(stderr,"  - read %d of %d bytes\n",bytes, (int)sizeof(nhdr));
3978       }
3979       return NULL;
3980    }
3981 
3982    /* now just decide on byte swapping */
3983    lswap = need_nhdr_swap(nhdr.dim[0], nhdr.sizeof_hdr); /* swap data flag */
3984    if( check && lswap < 0 ){
3985       LNI_FERR(fname,"bad nifti_1_header for file", hname);
3986       return NULL;
3987    } else if ( lswap < 0 ) {
3988       lswap = 0;  /* if swapping does not help, don't do it */
3989       if(g_opts.debug > 1) fprintf(stderr,"-- swap failure, none applied\n");
3990    }
3991 
3992    if( lswap ) {
3993       if ( g_opts.debug > 3 ) disp_nifti_1_header("-d nhdr pre-swap: ", &nhdr);
3994       swap_nifti_header( &nhdr , NIFTI_VERSION(nhdr) ) ;
3995    }
3996 
3997    if ( g_opts.debug > 2 ) disp_nifti_1_header("-d nhdr post-swap: ", &nhdr);
3998 
3999    if ( check && ! nifti_hdr_looks_good(&nhdr) ){
4000       LNI_FERR(fname,"nifti_1_header looks bad for file", hname);
4001       return NULL;
4002    }
4003 
4004    /* all looks good, so allocate memory for and return the header */
4005    hptr = (nifti_1_header *)malloc(sizeof(nifti_1_header));
4006    if( ! hptr ){
4007       fprintf(stderr,"** nifti_read_hdr: failed to alloc nifti_1_header\n");
4008       return NULL;
4009    }
4010 
4011    if( swapped ) *swapped = lswap;  /* only if they care <sniff!> */
4012 
4013    memcpy(hptr, &nhdr, sizeof(nifti_1_header));
4014 
4015    return hptr;
4016 }
4017 
4018 
4019 /*----------------------------------------------------------------------*/
4020 /*! decide if this nifti_1_header structure looks reasonable
4021 
4022    Check dim[0], dim[1], sizeof_hdr, and datatype.
4023    Check magic string for "n+1".
4024    Maybe more tests will follow.
4025 
4026    \return 1 if the header seems valid, 0 otherwise
4027 
4028    \sa nifti_nim_is_valid, valid_nifti_extensions
4029 *//*--------------------------------------------------------------------*/
nifti_hdr_looks_good(const nifti_1_header * hdr)4030 int nifti_hdr_looks_good(const nifti_1_header * hdr)
4031 {
4032    int is_nifti, c, errs = 0;
4033 
4034    /* check dim[0] and sizeof_hdr */
4035    if( need_nhdr_swap(hdr->dim[0], hdr->sizeof_hdr) < 0 ){
4036       if( g_opts.debug > 0 )
4037          fprintf(stderr,"** bad nhdr fields: dim0, sizeof_hdr = %d, %d\n",
4038                  hdr->dim[0], hdr->sizeof_hdr);
4039       errs++;
4040    }
4041 
4042    /* check the valid dimension sizes (maybe dim[0] is bad) */
4043    for( c = 1; c <= hdr->dim[0] && c <= 7; c++ )
4044       if( hdr->dim[c] <= 0 ){
4045          if( g_opts.debug > 0 )
4046             fprintf(stderr,"** bad nhdr field: dim[%d] = %d\n",c,hdr->dim[c]);
4047          errs++;
4048       }
4049 
4050    is_nifti = NIFTI_VERSION(*hdr);      /* determine header type */
4051 
4052    if( is_nifti ){      /* NIFTI */
4053 
4054       if( ! nifti_datatype_is_valid(hdr->datatype, 1) ){
4055          if( g_opts.debug > 0 )
4056             fprintf(stderr,"** bad NIFTI datatype in hdr, %d\n",hdr->datatype);
4057          errs++;
4058       }
4059 
4060    } else {             /* ANALYZE 7.5 */
4061 
4062       if( g_opts.debug > 1 )  /* maybe tell user it's an ANALYZE hdr */
4063          fprintf(stderr,
4064             "-- nhdr magic field implies ANALYZE: magic = '%.4s'\n",hdr->magic);
4065 
4066       if( ! nifti_datatype_is_valid(hdr->datatype, 0) ){
4067          if( g_opts.debug > 0 )
4068            fprintf(stderr,"** bad ANALYZE datatype in hdr, %d\n",hdr->datatype);
4069          errs++;
4070       }
4071    }
4072 
4073    if( errs ) return 0;  /* problems */
4074 
4075    if( g_opts.debug > 2 ) fprintf(stderr,"-d nifti header looks good\n");
4076 
4077    return 1;   /* looks good */
4078 }
4079 
4080 
4081 /*----------------------------------------------------------------------
4082  * check whether byte swapping is needed
4083  *
4084  * dim[0] should be in [0,7], and sizeof_hdr should be accurate
4085  *
4086  * \returns  > 0 : needs swap
4087  *             0 : does not need swap
4088  *           < 0 : error condition
4089  *----------------------------------------------------------------------*/
need_nhdr_swap(short dim0,int hdrsize)4090 static int need_nhdr_swap( short dim0, int hdrsize )
4091 {
4092    short d0    = dim0;     /* so we won't have to swap them on the stack */
4093    int   hsize = hdrsize;
4094 
4095    if( d0 != 0 ){     /* then use it for the check */
4096       if( d0 > 0 && d0 <= 7 ) return 0;
4097 
4098       nifti_swap_2bytes(1, &d0);        /* swap? */
4099       if( d0 > 0 && d0 <= 7 ) return 1;
4100 
4101       if( g_opts.debug > 1 ){
4102          fprintf(stderr,"** NIFTI: bad swapped d0 = %d, unswapped = ", d0);
4103          nifti_swap_2bytes(1, &d0);        /* swap? */
4104          fprintf(stderr,"%d\n", d0);
4105       }
4106 
4107       return -1;        /* bad, naughty d0 */
4108    }
4109 
4110    /* dim[0] == 0 should not happen, but could, so try hdrsize */
4111    if( hsize == sizeof(nifti_1_header) ) return 0;
4112 
4113    nifti_swap_4bytes(1, &hsize);     /* swap? */
4114    if( hsize == sizeof(nifti_1_header) ) return 1;
4115 
4116    if( g_opts.debug > 1 ){
4117       fprintf(stderr,"** NIFTI: bad swapped hsize = %d, unswapped = ", hsize);
4118       nifti_swap_4bytes(1, &hsize);        /* swap? */
4119       fprintf(stderr,"%d\n", hsize);
4120    }
4121 
4122    return -2;     /* bad, naughty hsize */
4123 }
4124 
4125 
4126 /* use macro LNI_FILE_ERROR instead of ERREX()
4127 #undef  ERREX
4128 #define ERREX(msg)                                           \
4129  do{ fprintf(stderr,"** ERROR: nifti_image_read(%s): %s\n",  \
4130              (hname != NULL) ? hname : "(null)" , (msg) ) ;  \
4131      return NULL ; } while(0)
4132 */
4133 
4134 
4135 /***************************************************************
4136  * nifti_image_read
4137  ***************************************************************/
4138 /*! \brief Read a nifti header and optionally the data, creating a nifti_image.
4139 
4140         - The data buffer will be byteswapped if necessary.
4141         - The data buffer will not be scaled.
4142         - The data buffer is allocated with calloc().
4143 
4144     \param hname filename of the nifti dataset
4145     \param read_data Flag, true=read data blob, false=don't read blob.
4146     \return A pointer to the nifti_image data structure.
4147 
4148     \sa nifti_image_free, nifti_free_extensions, nifti_image_read_bricks
4149 */
nifti_image_read(const char * hname,int read_data)4150 nifti_image *nifti_image_read( const char *hname , int read_data )
4151 {
4152    struct nifti_1_header  nhdr ;
4153    nifti_image           *nim ;
4154    znzFile                fp ;
4155    int                    rv, ii , filesize, remaining;
4156    char                   fname[] = { "nifti_image_read" };
4157    char                  *hfile=NULL;
4158 
4159    if( g_opts.debug > 1 ){
4160       fprintf(stderr,"-d image_read from '%s', read_data = %d",hname,read_data);
4161 #ifdef HAVE_ZLIB
4162       fprintf(stderr,", HAVE_ZLIB = 1\n");
4163 #else
4164       fprintf(stderr,", HAVE_ZLIB = 0\n");
4165 #endif
4166    }
4167 
4168    /**- determine filename to use for header */
4169    hfile = nifti_findhdrname(hname);
4170    if( hfile == NULL ){
4171       if(g_opts.debug > 0)
4172          LNI_FERR(fname,"failed to find header file for", hname);
4173       return NULL;  /* check return */
4174    } else if( g_opts.debug > 1 )
4175       fprintf(stderr,"-d %s: found header filename '%s'\n",fname,hfile);
4176 
4177    if( nifti_is_gzfile(hfile) ) filesize = -1;  /* unknown */
4178    else                         filesize = nifti_get_filesize(hfile);
4179 
4180    fp = znzopen(hfile, "rb", nifti_is_gzfile(hfile));
4181    if( znz_isnull(fp) ){
4182       if( g_opts.debug > 0 ) LNI_FERR(fname,"failed to open header file",hfile);
4183       free(hfile);
4184       return NULL;
4185    }
4186 
4187    rv = has_ascii_header( fp );
4188    if( rv < 0 ){
4189       if( g_opts.debug > 0 ) LNI_FERR(fname,"short header read",hfile);
4190       znzclose( fp );
4191       free(hfile);
4192       return NULL;
4193    }
4194    else if ( rv == 1 )  /* process special file type */
4195       return nifti_read_ascii_image( fp, hfile, filesize, read_data );
4196 
4197    /* else, just process normally */
4198 
4199    /**- read binary header */
4200 
4201    ii = (int)znzread( &nhdr , 1 , sizeof(nhdr) , fp ) ;       /* read the thing */
4202 
4203    /* keep file open so we can check for exts. after nifti_convert_nhdr2nim() */
4204 
4205    if( ii < (int) sizeof(nhdr) ){
4206       if( g_opts.debug > 0 ){
4207          LNI_FERR(fname,"bad binary header read for file", hfile);
4208          fprintf(stderr,"  - read %d of %d bytes\n",ii, (int)sizeof(nhdr));
4209       }
4210       znzclose(fp) ;
4211       free(hfile);
4212       return NULL;
4213    }
4214 
4215    /* create output image struct and set it up */
4216 
4217    /**- convert all nhdr fields to nifti_image fields */
4218    nim = nifti_convert_nhdr2nim(nhdr,hfile);
4219 
4220    if( nim == NULL ){
4221       znzclose( fp ) ;                                   /* close the file */
4222       if( g_opts.debug > 0 )
4223          LNI_FERR(fname,"cannot create nifti image from header",hfile);
4224       free(hfile); /* had to save this for debug message */
4225       return NULL;
4226    }
4227 
4228    if( g_opts.debug > 3 ){
4229       fprintf(stderr,"+d nifti_image_read(), have nifti image:\n");
4230       if( g_opts.debug > 2 ) nifti_image_infodump(nim);
4231    }
4232 
4233    /**- check for extensions (any errors here means no extensions) */
4234    if( NIFTI_ONEFILE(nhdr) ) remaining = nim->iname_offset - sizeof(nhdr);
4235    else                      remaining = filesize - sizeof(nhdr);
4236 
4237    (void)nifti_read_extensions(nim, fp, remaining);
4238 
4239    znzclose( fp ) ;                                      /* close the file */
4240    free(hfile);
4241 
4242    /**- read the data if desired, then bug out */
4243    if( read_data ){
4244       if( nifti_image_load( nim ) < 0 ){
4245          nifti_image_free(nim);          /* take ball, go home. */
4246          return NULL;
4247       }
4248    }
4249    else nim->data = NULL ;
4250 
4251    return nim ;
4252 }
4253 
4254 
4255 /*----------------------------------------------------------------------
4256  * has_ascii_header  - see if the NIFTI header is an ASCII format
4257  *
4258  * If the file starts with the ASCII string "<nifti_image", then
4259  * process the dataset as a type-3 .nia file.
4260  *
4261  * return:  -1 on error, 1 if true, or 0 if false
4262  *
4263  * NOTE: this is NOT part of the NIFTI-1 standard
4264  *----------------------------------------------------------------------*/
has_ascii_header(znzFile fp)4265 static int has_ascii_header( znzFile fp )
4266 {
4267    char  buf[16];
4268    int   nread;
4269 
4270    if( znz_isnull(fp) ) return 0;
4271 
4272    nread = (int)znzread( buf, 1, 12, fp );
4273    buf[12] = '\0';
4274 
4275    if( nread < 12 ) return -1;
4276 
4277    znzrewind(fp);  /* move back to the beginning, and check */
4278 
4279    if( strcmp(buf, "<nifti_image") == 0 ) return 1;
4280 
4281    return 0;
4282 }
4283 
4284 
4285 /*----------------------------------------------------------------------*/
4286 /*! nifti_read_ascii_image  - process as a type-3 .nia image file
4287 
4288    return NULL on failure
4289 
4290    NOTE: this is NOT part of the NIFTI-1 standard
4291 *//*--------------------------------------------------------------------*/
nifti_read_ascii_image(znzFile fp,char * fname,int flen,int read_data)4292 nifti_image * nifti_read_ascii_image(znzFile fp, char *fname, int flen,
4293                                      int read_data)
4294 {
4295    nifti_image * nim;
4296    int           slen, txt_size, remain, rv = 0;
4297    char        * sbuf, lfunc[25] = { "nifti_read_ascii_image" };
4298 
4299    if( nifti_is_gzfile(fname) ){
4300      LNI_FERR(lfunc,"compression not supported for file type NIFTI_FTYPE_ASCII",
4301               fname);
4302      free(fname);  znzclose(fp);  return NULL;
4303    }
4304    slen = flen;  /* slen will be our buffer length */
4305 
4306    if( g_opts.debug > 1 )
4307       fprintf(stderr,"-d %s: have ASCII NIFTI file of size %d\n",fname,slen);
4308 
4309    if( slen > 65530 ) slen = 65530 ;
4310    sbuf = (char *)calloc(sizeof(char),slen+1) ;
4311    if( !sbuf ){
4312       fprintf(stderr,"** %s: failed to alloc %d bytes for sbuf",lfunc,65530);
4313       free(fname);  znzclose(fp);  return NULL;
4314    }
4315    znzread( sbuf , 1 , slen , fp ) ;
4316    nim = nifti_image_from_ascii( sbuf, &txt_size ) ; free( sbuf ) ;
4317    if( nim == NULL ){
4318       LNI_FERR(lfunc,"failed nifti_image_from_ascii()",fname);
4319       free(fname);  znzclose(fp);  return NULL;
4320    }
4321    nim->nifti_type = NIFTI_FTYPE_ASCII ;
4322 
4323    /* compute remaining space for extensions */
4324    remain = flen - txt_size - (int)nifti_get_volsize(nim);
4325    if( remain > 4 ){
4326       /* read extensions (reposition file pointer, first) */
4327       znzseek(fp, txt_size, SEEK_SET);
4328       (void) nifti_read_extensions(nim, fp, remain);
4329    }
4330 
4331    free(fname);
4332    znzclose( fp ) ;
4333 
4334    nim->iname_offset = -1 ;  /* check from the end of the file */
4335 
4336    if( read_data ) rv = nifti_image_load( nim ) ;
4337    else            nim->data = NULL ;
4338 
4339    /* check for nifti_image_load() failure, maybe bail out */
4340    if( read_data && rv != 0 ){
4341       if( g_opts.debug > 1 )
4342          fprintf(stderr,"-d failed image_load, free nifti image struct\n");
4343       free(nim);
4344       return NULL;
4345    }
4346 
4347    return nim ;
4348 }
4349 
4350 
4351 /*----------------------------------------------------------------------
4352  * Read the extensions into the nifti_image struct   08 Dec 2004 [rickr]
4353  *
4354  * This function is called just after the header struct is read in, and
4355  * it is assumed the file pointer has not moved.  The value in remain
4356  * is assumed to be accurate, reflecting the bytes of space for potential
4357  * extensions.
4358  *
4359  * return the number of extensions read in, or < 0 on error
4360  *----------------------------------------------------------------------*/
nifti_read_extensions(nifti_image * nim,znzFile fp,int remain)4361 static int nifti_read_extensions( nifti_image *nim, znzFile fp, int remain )
4362 {
4363    nifti1_extender    extdr;      /* defines extension existence  */
4364    nifti1_extension   extn;       /* single extension to process  */
4365    nifti1_extension * Elist;      /* list of processed extensions */
4366    int                posn, count;
4367 
4368    if( !nim || znz_isnull(fp) ) {
4369       if( g_opts.debug > 0 )
4370          fprintf(stderr,"** nifti_read_extensions: bad inputs (%p,%p)\n",
4371                  (void *)nim, (void *)fp);
4372       return -1;
4373    }
4374 
4375    posn = znztell(fp);
4376 
4377    if( (posn != sizeof(nifti_1_header)) &&
4378        (nim->nifti_type != NIFTI_FTYPE_ASCII) )
4379       fprintf(stderr,"** WARNING: posn not header size (%d, %d)\n",
4380               posn, (int)sizeof(nifti_1_header));
4381 
4382    if( g_opts.debug > 2 )
4383       fprintf(stderr,"-d nre: posn = %d, offset = %d, type = %d, remain = %d\n",
4384               posn, nim->iname_offset, nim->nifti_type, remain);
4385 
4386    if( remain < 16 ){
4387       if( g_opts.debug > 2 ){
4388          if( g_opts.skip_blank_ext )
4389             fprintf(stderr,"-d no extender in '%s' is okay, as "
4390                            "skip_blank_ext is set\n",nim->fname);
4391          else
4392             fprintf(stderr,"-d remain=%d, no space for extensions\n",remain);
4393       }
4394       return 0;
4395    }
4396 
4397    count = (int)znzread( extdr.extension, 1, 4, fp ); /* get extender */
4398 
4399    if( count < 4 ){
4400       if( g_opts.debug > 1 )
4401          fprintf(stderr,"-d file '%s' is too short for an extender\n",
4402                  nim->fname);
4403       return 0;
4404    }
4405 
4406    if( extdr.extension[0] != 1 ){
4407       if( g_opts.debug > 2 )
4408          fprintf(stderr,"-d extender[0] (%d) shows no extensions for '%s'\n",
4409                  extdr.extension[0], nim->fname);
4410       return 0;
4411    }
4412 
4413    remain -= 4;
4414    if( g_opts.debug > 2 )
4415       fprintf(stderr,"-d found valid 4-byte extender, remain = %d\n", remain);
4416 
4417    /* so we expect extensions, but have no idea of how many there may be */
4418 
4419    count = 0;
4420    Elist = NULL;
4421    while (nifti_read_next_extension(&extn, nim, remain, fp) > 0)
4422    {
4423       if( nifti_add_exten_to_list(&extn, &Elist, count+1) < 0 ){
4424          if( g_opts.debug > 0 )
4425             fprintf(stderr,"** failed adding ext %d to list\n", count);
4426          return -1;
4427       }
4428 
4429       /* we have a new extension */
4430       if( g_opts.debug > 1 ){
4431          fprintf(stderr,"+d found extension #%d, code = 0x%x, size = %d\n",
4432                  count, extn.ecode, extn.esize);
4433          if( extn.ecode == NIFTI_ECODE_AFNI && g_opts.debug > 2 ) /* ~XML */
4434             fprintf(stderr,"   AFNI extension: %.*s\n",
4435                     extn.esize-8,extn.edata);
4436          else if( extn.ecode == NIFTI_ECODE_COMMENT && g_opts.debug > 2 )
4437             fprintf(stderr,"   COMMENT extension: %.*s\n",        /* TEXT */
4438                     extn.esize-8,extn.edata);
4439       }
4440       remain -= extn.esize;
4441       count++;
4442    }
4443 
4444    if( g_opts.debug > 2 ) fprintf(stderr,"+d found %d extension(s)\n", count);
4445 
4446    nim->num_ext = count;
4447    nim->ext_list = Elist;
4448 
4449    return count;
4450 }
4451 
4452 
4453 /*----------------------------------------------------------------------*/
4454 /*! nifti_add_extension - add an extension, with a copy of the data
4455 
4456    Add an extension to the nim->ext_list array.
4457    Fill this extension with a copy of the data, noting the
4458        length and extension code.
4459 
4460    \param nim    - nifti_image to add extension to
4461    \param data   - raw extension data
4462    \param length - length of raw extension data
4463    \param ecode  - extension code
4464 
4465    \sa extension codes NIFTI_ECODE_* in nifti1_io.h
4466    \sa nifti_free_extensions, valid_nifti_extensions, nifti_copy_extensions
4467 
4468    \return 0 on success, -1 on error (and free the entire list)
4469 *//*--------------------------------------------------------------------*/
nifti_add_extension(nifti_image * nim,const char * data,int len,int ecode)4470 int nifti_add_extension(nifti_image *nim, const char * data, int len, int ecode)
4471 {
4472    nifti1_extension ext;
4473 
4474    /* error are printed in functions */
4475    if( nifti_fill_extension(&ext, data, len, ecode) )                 return -1;
4476    if( nifti_add_exten_to_list(&ext, &nim->ext_list, nim->num_ext+1)) return -1;
4477 
4478    nim->num_ext++;  /* success, so increment */
4479 
4480    return 0;
4481 }
4482 
4483 
4484 /*----------------------------------------------------------------------*/
4485 /* nifti_add_exten_to_list     - add a new nifti1_extension to the list
4486 
4487    We will append via "malloc, copy and free", because on an error,
4488    the list will revert to the previous one (sorry realloc(), only
4489    quality dolphins get to become part of St@rk!st brand tunafish).
4490 
4491    return 0 on success, -1 on error (and free the entire list)
4492 *//*--------------------------------------------------------------------*/
nifti_add_exten_to_list(nifti1_extension * new_ext,nifti1_extension ** list,int new_length)4493 static int nifti_add_exten_to_list( nifti1_extension *  new_ext,
4494                                     nifti1_extension ** list, int new_length )
4495 {
4496    nifti1_extension * tmplist;
4497 
4498    tmplist = *list;
4499    *list = (nifti1_extension *)malloc(new_length * sizeof(nifti1_extension));
4500 
4501    /* check for failure first */
4502    if( ! *list ){
4503       fprintf(stderr,"** failed to alloc %d extension structs (%d bytes)\n",
4504               new_length, new_length*(int)sizeof(nifti1_extension));
4505       if( !tmplist ) return -1;  /* no old list to lose */
4506 
4507       *list = tmplist;  /* reset list to old one */
4508       return -1;
4509    }
4510 
4511    /* if an old list exists, copy the pointers and free the list */
4512    if( tmplist ){
4513       memcpy(*list, tmplist, (new_length-1)*sizeof(nifti1_extension));
4514       free(tmplist);
4515    }
4516 
4517    /* for some reason, I just don't like struct copy... */
4518    (*list)[new_length-1].esize = new_ext->esize;
4519    (*list)[new_length-1].ecode = new_ext->ecode;
4520    (*list)[new_length-1].edata = new_ext->edata;
4521 
4522    if( g_opts.debug > 2 )
4523       fprintf(stderr,"+d allocated and appended extension #%d to list\n",
4524               new_length);
4525 
4526    return 0;
4527 }
4528 
4529 
4530 /*----------------------------------------------------------------------*/
4531 /* nifti_fill_extension  - given data and length, fill an extension struct
4532 
4533    Allocate memory for data, copy data, set the size and code.
4534 
4535    return 0 on success, -1 on error (and free the entire list)
4536 *//*--------------------------------------------------------------------*/
nifti_fill_extension(nifti1_extension * ext,const char * data,int len,int ecode)4537 static int nifti_fill_extension( nifti1_extension *ext, const char * data,
4538                                 int len, int ecode)
4539 {
4540    int esize;
4541 
4542    if( !ext || !data || len < 0 ){
4543       fprintf(stderr,"** fill_ext: bad params (%p,%p,%d)\n",
4544               (void *)ext, data, len);
4545       return -1;
4546    } else if( ! nifti_is_valid_ecode(ecode) ){
4547       fprintf(stderr,"** fill_ext: invalid ecode %d\n", ecode);
4548       return -1;
4549    }
4550 
4551    /* compute esize, first : len+8, and take ceiling up to a mult of 16 */
4552    esize = len+8;
4553    if( esize & 0xf ) esize = (esize + 0xf) & ~0xf;
4554    ext->esize = esize;
4555 
4556    /* allocate esize-8 (maybe more than len), using calloc for fill */
4557    ext->edata = (char *)calloc(esize-8, sizeof(char));
4558    if( !ext->edata ){
4559       fprintf(stderr,"** NFE: failed to alloc %d bytes for extension\n",len);
4560       return -1;
4561    }
4562 
4563    memcpy(ext->edata, data, len);  /* copy the data, using len */
4564    ext->ecode = ecode;             /* set the ecode */
4565 
4566    if( g_opts.debug > 2 )
4567       fprintf(stderr,"+d alloc %d bytes for ext len %d, ecode %d, esize %d\n",
4568               esize-8, len, ecode, esize);
4569 
4570    return 0;
4571 }
4572 
4573 
4574 /*----------------------------------------------------------------------
4575  * nifti_read_next_extension  - read a single extension from the file
4576  *
4577  * return (>= 0 is okay):
4578  *
4579  *     success      : esize
4580  *     no extension : 0
4581  *     error        : -1
4582  *----------------------------------------------------------------------*/
nifti_read_next_extension(nifti1_extension * nex,nifti_image * nim,int remain,znzFile fp)4583 static int nifti_read_next_extension( nifti1_extension * nex, nifti_image *nim,
4584                                       int remain, znzFile fp )
4585 {
4586    int swap = nim->byteorder != nifti_short_order();
4587    int count, size, code;
4588 
4589    /* first clear nex */
4590    nex->esize = nex->ecode = 0;
4591    nex->edata = NULL;
4592 
4593    if( remain < 16 ){
4594       if( g_opts.debug > 2 )
4595          fprintf(stderr,"-d only %d bytes remain, so no extension\n", remain);
4596       return 0;
4597    }
4598 
4599    /* must start with 4-byte size and code */
4600    count = (int)znzread( &size, 4, 1, fp );
4601    if( count == 1 ) count += (int)znzread( &code, 4, 1, fp );
4602 
4603    if( count != 2 ){
4604       if( g_opts.debug > 2 )
4605          fprintf(stderr,"-d current extension read failed\n");
4606       znzseek(fp, -4*count, SEEK_CUR); /* back up past any read */
4607       return 0;                        /* no extension, no error condition */
4608    }
4609 
4610    if( swap ){
4611       if( g_opts.debug > 2 )
4612          fprintf(stderr,"-d pre-swap exts: code %d, size %d\n", code, size);
4613 
4614       nifti_swap_4bytes(1, &size);
4615       nifti_swap_4bytes(1, &code);
4616    }
4617 
4618    if( g_opts.debug > 2 )
4619       fprintf(stderr,"-d potential extension: code %d, size %d\n", code, size);
4620 
4621    if( !nifti_check_extension(nim, size, code, remain) ){
4622       if( znzseek(fp, -8, SEEK_CUR) < 0 ){      /* back up past any read */
4623          fprintf(stderr,"** failure to back out of extension read!\n");
4624          return -1;
4625       }
4626       return 0;
4627    }
4628 
4629    /* now get the actual data */
4630    nex->esize = size;
4631    nex->ecode = code;
4632 
4633    size -= 8;  /* subtract space for size and code in extension */
4634    nex->edata = (char *)malloc(size * sizeof(char));
4635    if( !nex->edata ){
4636       fprintf(stderr,"** failed to allocate %d bytes for extension\n",size);
4637       return -1;
4638    }
4639 
4640    count = (int)znzread(nex->edata, 1, size, fp);
4641    if( count < size ){
4642       if( g_opts.debug > 0 )
4643          fprintf(stderr,"-d read only %d (of %d) bytes for extension\n",
4644                  count, size);
4645       free(nex->edata);
4646       nex->edata = NULL;
4647       return -1;
4648    }
4649 
4650    /* success! */
4651    if( g_opts.debug > 2 )
4652       fprintf(stderr,"+d successfully read extension, code %d, size %d\n",
4653               nex->ecode, nex->esize);
4654 
4655    return nex->esize;
4656 }
4657 
4658 
4659 /*----------------------------------------------------------------------*/
4660 /*! for each extension, check code, size and data pointer
4661 *//*--------------------------------------------------------------------*/
valid_nifti_extensions(const nifti_image * nim)4662 int valid_nifti_extensions(const nifti_image * nim)
4663 {
4664    nifti1_extension * ext;
4665    int                c, errs;
4666 
4667    if( nim->num_ext <= 0 || nim->ext_list == NULL ){
4668       if( g_opts.debug > 2 ) fprintf(stderr,"-d empty extension list\n");
4669       return 0;
4670    }
4671 
4672    /* for each extension, check code, size and data pointer */
4673    ext = nim->ext_list;
4674    errs = 0;
4675    for ( c = 0; c < nim->num_ext; c++ ){
4676       if( ! nifti_is_valid_ecode(ext->ecode) ) {
4677          if( g_opts.debug > 1 )
4678             fprintf(stderr,"-d ext %d, invalid code %d\n", c, ext->ecode);
4679          errs++;
4680       }
4681 
4682       if( ext->esize <= 0 ){
4683          if( g_opts.debug > 1 )
4684             fprintf(stderr,"-d ext %d, bad size = %d\n", c, ext->esize);
4685          errs++;
4686       } else if( ext->esize & 0xf ){
4687          if( g_opts.debug > 1 )
4688             fprintf(stderr,"-d ext %d, size %d not multiple of 16\n",
4689                     c, ext->esize);
4690          errs++;
4691       }
4692 
4693       if( ext->edata == NULL ){
4694          if( g_opts.debug > 1 ) fprintf(stderr,"-d ext %d, missing data\n", c);
4695          errs++;
4696       }
4697 
4698       ext++;
4699    }
4700 
4701    if( errs > 0 ){
4702       if( g_opts.debug > 0 )
4703          fprintf(stderr,"-d had %d extension errors, none will be written\n",
4704                  errs);
4705       return 0;
4706    }
4707 
4708    /* if we're here, we're good */
4709    return 1;
4710 }
4711 
4712 
4713 /*----------------------------------------------------------------------*/
4714 /*! check whether the extension code is valid
4715 
4716     \return 1 if valid, 0 otherwise
4717 *//*--------------------------------------------------------------------*/
nifti_is_valid_ecode(int ecode)4718 int nifti_is_valid_ecode( int ecode )
4719 {
4720    if( ecode < NIFTI_ECODE_IGNORE  ||   /* minimum code number (0) */
4721        ecode > NIFTI_MAX_ECODE     ||   /* maximum code number     */
4722        ecode & 1 )                      /* cannot be odd           */
4723       return 0;
4724 
4725    return 1;
4726 }
4727 
4728 
4729 /*----------------------------------------------------------------------
4730  * check for valid size and code, as well as can be done
4731  *----------------------------------------------------------------------*/
nifti_check_extension(nifti_image * nim,int size,int code,int rem)4732 static int nifti_check_extension(nifti_image *nim, int size, int code, int rem)
4733 {
4734    /* check for bad code before bad size */
4735    if( ! nifti_is_valid_ecode(code) ) {
4736       if( g_opts.debug > 2 )
4737          fprintf(stderr,"-d invalid extension code %d\n",code);
4738       return 0;
4739    }
4740 
4741    if( size < 16 ){
4742       if( g_opts.debug > 2 )
4743          fprintf(stderr,"-d ext size %d, no extension\n",size);
4744       return 0;
4745    }
4746 
4747    if( size > rem ){
4748       if( g_opts.debug > 2 )
4749          fprintf(stderr,"-d ext size %d, space %d, no extension\n", size, rem);
4750       return 0;
4751    }
4752 
4753    if( size & 0xf ){
4754       if( g_opts.debug > 2 )
4755          fprintf(stderr,"-d nifti extension size %d not multiple of 16\n",size);
4756       return 0;
4757    }
4758 
4759    if( nim->nifti_type == NIFTI_FTYPE_ASCII && size > LNI_MAX_NIA_EXT_LEN ){
4760       if( g_opts.debug > 2 )
4761          fprintf(stderr,"-d NVE, bad nifti_type 3 size %d\n", size);
4762       return 0;
4763    }
4764 
4765    return 1;
4766 }
4767 
4768 
4769 /*----------------------------------------------------------------------
4770  * nifti_image_load_prep  - prepare to read data
4771  *
4772  * Check nifti_image fields, open the file and seek to the appropriate
4773  * offset for reading.
4774  *
4775  * return NULL on failure
4776  *----------------------------------------------------------------------*/
nifti_image_load_prep(nifti_image * nim)4777 static znzFile nifti_image_load_prep( nifti_image *nim )
4778 {
4779    /* set up data space, open data file and seek, then call nifti_read_buffer */
4780    size_t  ntot , ii , ioff;
4781    znzFile fp;
4782    char   *tmpimgname;
4783    char    fname[] = { "nifti_image_load_prep" };
4784 
4785    /**- perform sanity checks */
4786    if( nim == NULL      || nim->iname == NULL ||
4787        nim->nbyper <= 0 || nim->nvox <= 0       )
4788    {
4789       if ( g_opts.debug > 0 ){
4790          if( !nim ) fprintf(stderr,"** ERROR: N_image_load: no nifti image\n");
4791          else fprintf(stderr,"** ERROR: N_image_load: bad params (%p,%d,%u)\n",
4792                       nim->iname, nim->nbyper, (unsigned)nim->nvox);
4793       }
4794       return NULL;
4795    }
4796 
4797    ntot = nifti_get_volsize(nim) ; /* total bytes to read */
4798 
4799    /**- open image data file */
4800 
4801    tmpimgname = nifti_findimgname(nim->iname , nim->nifti_type);
4802    if( tmpimgname == NULL ){
4803       if( g_opts.debug > 0 )
4804          fprintf(stderr,"** no image file found for '%s'\n",nim->iname);
4805       return NULL;
4806    }
4807 
4808    fp = znzopen(tmpimgname, "rb", nifti_is_gzfile(tmpimgname));
4809    if (znz_isnull(fp)){
4810        if(g_opts.debug > 0) LNI_FERR(fname,"cannot open data file",tmpimgname);
4811        free(tmpimgname);
4812        return NULL;  /* bad open? */
4813    }
4814    free(tmpimgname);
4815 
4816    /**- get image offset: a negative offset means to figure from end of file */
4817    if( nim->iname_offset < 0 ){
4818      if( nifti_is_gzfile(nim->iname) ){
4819         if( g_opts.debug > 0 )
4820            LNI_FERR(fname,"negative offset for compressed file",nim->iname);
4821         znzclose(fp);
4822         return NULL;
4823      }
4824      ii = nifti_get_filesize( nim->iname ) ;
4825      if( ii <= 0 ){
4826         if( g_opts.debug > 0 ) LNI_FERR(fname,"empty data file",nim->iname);
4827         znzclose(fp);
4828         return NULL;
4829      }
4830      ioff = (ii > ntot) ? ii-ntot : 0 ;
4831    } else {                              /* non-negative offset   */
4832      ioff = nim->iname_offset ;          /* means use it directly */
4833    }
4834 
4835    /**- seek to the appropriate read position */
4836    if( znzseek(fp , (long)ioff , SEEK_SET) < 0 ){
4837       fprintf(stderr,"** could not seek to offset %u in file '%s'\n",
4838               (unsigned)ioff, nim->iname);
4839       znzclose(fp);
4840       return NULL;
4841    }
4842 
4843    /**- and return the File pointer */
4844    return fp;
4845 }
4846 
4847 
4848 /*----------------------------------------------------------------------
4849  * nifti_image_load
4850  *----------------------------------------------------------------------*/
4851 /*! \fn int nifti_image_load( nifti_image *nim )
4852     \brief Load the image blob into a previously initialized nifti_image.
4853 
4854         - If not yet set, the data buffer is allocated with calloc().
4855         - The data buffer will be byteswapped if necessary.
4856         - The data buffer will not be scaled.
4857 
4858     This function is used to read the image from disk.  It should be used
4859     after a function such as nifti_image_read(), so that the nifti_image
4860     structure is already initialized.
4861 
4862     \param  nim pointer to a nifti_image (previously initialized)
4863     \return 0 on success, -1 on failure
4864     \sa     nifti_image_read, nifti_image_free, nifti_image_unload
4865 */
nifti_image_load(nifti_image * nim)4866 int nifti_image_load( nifti_image *nim )
4867 {
4868    /* set up data space, open data file and seek, then call nifti_read_buffer */
4869    size_t ntot , ii ;
4870    znzFile fp ;
4871 
4872    /**- open the file and position the FILE pointer */
4873    fp = nifti_image_load_prep( nim );
4874 
4875    if( fp == NULL ){
4876       if( g_opts.debug > 0 )
4877          fprintf(stderr,"** nifti_image_load, failed load_prep\n");
4878       return -1;
4879    }
4880 
4881    ntot = nifti_get_volsize(nim);
4882 
4883    /**- if the data pointer is not yet set, get memory space for the image */
4884 
4885    if( nim->data == NULL )
4886    {
4887      nim->data = (void *)calloc(1,ntot) ;  /* create image memory */
4888      if( nim->data == NULL ){
4889         if( g_opts.debug > 0 )
4890            fprintf(stderr,"** failed to alloc %d bytes for image data\n",
4891                    (int)ntot);
4892         znzclose(fp);
4893         return -1;
4894      }
4895    }
4896 
4897    /**- now that everything is set up, do the reading */
4898    ii = nifti_read_buffer(fp,nim->data,ntot,nim);
4899    if( ii < ntot ){
4900       znzclose(fp) ;
4901       free(nim->data) ;
4902       nim->data = NULL ;
4903       return -1 ;  /* errors were printed in nifti_read_buffer() */
4904    }
4905 
4906    /**- close the file */
4907    znzclose( fp ) ;
4908 
4909    return 0 ;
4910 }
4911 
4912 
4913 /* 30 Nov 2004 [rickr]
4914 #undef  ERREX
4915 #define ERREX(msg)                                               \
4916  do{ fprintf(stderr,"** ERROR: nifti_read_buffer: %s\n",(msg)) ;  \
4917      return 0; } while(0)
4918 */
4919 
4920 /*----------------------------------------------------------------------*/
4921 /*! read ntot bytes of data from an open file and byte swaps if necessary
4922 
4923    note that nifti_image is required for information on datatype, bsize
4924    (for any needed byte swapping), etc.
4925 
4926    This function does not allocate memory, so dataptr must be valid.
4927 *//*--------------------------------------------------------------------*/
nifti_read_buffer(znzFile fp,void * dataptr,size_t ntot,nifti_image * nim)4928 size_t nifti_read_buffer(znzFile fp, void* dataptr, size_t ntot,
4929                                 nifti_image *nim)
4930 {
4931   size_t ii;
4932 
4933   if( dataptr == NULL ){
4934      if( g_opts.debug > 0 )
4935         fprintf(stderr,"** ERROR: nifti_read_buffer: NULL dataptr\n");
4936      return -1;
4937   }
4938 
4939   ii = znzread( dataptr , 1 , ntot , fp ) ;             /* data input */
4940 
4941   /* if read was short, fail */
4942   if( ii < ntot ){
4943     if( g_opts.debug > 0 )
4944        fprintf(stderr,"++ WARNING: nifti_read_buffer(%s):\n"
4945                "   data bytes needed = %u\n"
4946                "   data bytes input  = %u\n"
4947                "   number missing    = %u (set to 0)\n",
4948                nim->iname , (unsigned int)ntot ,
4949                (unsigned int)ii , (unsigned int)(ntot-ii) ) ;
4950     /* memset( (char *)(dataptr)+ii , 0 , ntot-ii ) ;  now failure [rickr] */
4951     return -1 ;
4952   }
4953 
4954   if( g_opts.debug > 2 )
4955     fprintf(stderr,"+d nifti_read_buffer: read %u bytes\n", (unsigned)ii);
4956 
4957   /* byte swap array if needed */
4958 
4959   /* ntot/swapsize might not fit as int, use size_t    6 Jul 2010 [rickr] */
4960   if( nim->swapsize > 1 && nim->byteorder != nifti_short_order() ) {
4961     if( g_opts.debug > 1 )
4962        fprintf(stderr,"+d nifti_read_buffer: swapping data bytes...\n");
4963     nifti_swap_Nbytes( ntot / nim->swapsize, nim->swapsize , dataptr ) ;
4964   }
4965 
4966 #ifdef isfinite
4967 {
4968   /* check input float arrays for goodness, and fix bad floats */
4969   int fix_count = 0 ;
4970 
4971   switch( nim->datatype ){
4972 
4973     case NIFTI_TYPE_FLOAT32:
4974     case NIFTI_TYPE_COMPLEX64:{
4975         register float *far = (float *)dataptr ; register size_t jj,nj ;
4976         nj = ntot / sizeof(float) ;
4977         for( jj=0 ; jj < nj ; jj++ )   /* count fixes 30 Nov 2004 [rickr] */
4978            if( !IS_GOOD_FLOAT(far[jj]) ){
4979               far[jj] = 0 ;
4980               fix_count++ ;
4981            }
4982       }
4983       break ;
4984 
4985     case NIFTI_TYPE_FLOAT64:
4986     case NIFTI_TYPE_COMPLEX128:{
4987         register double *far = (double *)dataptr ; register size_t jj,nj ;
4988         nj = ntot / sizeof(double) ;
4989         for( jj=0 ; jj < nj ; jj++ )   /* count fixes 30 Nov 2004 [rickr] */
4990            if( !IS_GOOD_FLOAT(far[jj]) ){
4991               far[jj] = 0 ;
4992               fix_count++ ;
4993            }
4994       }
4995       break ;
4996 
4997   }
4998 
4999   if( g_opts.debug > 1 )
5000      fprintf(stderr,"+d in image, %d bad floats were set to 0\n", fix_count);
5001 }
5002 #endif
5003 
5004   return ii;
5005 }
5006 
5007 /*--------------------------------------------------------------------------*/
5008 /*! Unload the data in a nifti_image struct, but keep the metadata.
5009 *//*------------------------------------------------------------------------*/
nifti_image_unload(nifti_image * nim)5010 void nifti_image_unload( nifti_image *nim )
5011 {
5012    if( nim != NULL && nim->data != NULL ){
5013      free(nim->data) ; nim->data = NULL ;
5014    }
5015    return ;
5016 }
5017 
5018 /*--------------------------------------------------------------------------*/
5019 /*! free 'everything' about a nifti_image struct (including the passed struct)
5020 
5021     free (only fields which are not NULL):
5022       - fname and iname
5023       - data
5024       - any ext_list[i].edata
5025       - ext_list
5026       - nim
5027 *//*------------------------------------------------------------------------*/
nifti_image_free(nifti_image * nim)5028 void nifti_image_free( nifti_image *nim )
5029 {
5030    if( nim == NULL ) return ;
5031    if( nim->fname != NULL ) free(nim->fname) ;
5032    if( nim->iname != NULL ) free(nim->iname) ;
5033    if( nim->data  != NULL ) free(nim->data ) ;
5034    (void)nifti_free_extensions( nim ) ;
5035    free(nim) ; return ;
5036 }
5037 
5038 
5039 /*--------------------------------------------------------------------------*/
5040 /*! free the nifti extensions
5041 
5042     - If any edata pointer is set in the extension list, free() it.
5043     - Free ext_list, if it is set.
5044     - Clear num_ext and ext_list from nim.
5045 
5046     \return 0 on success, -1 on error
5047 
5048     \sa nifti_add_extension, nifti_copy_extensions
5049 *//*------------------------------------------------------------------------*/
nifti_free_extensions(nifti_image * nim)5050 int nifti_free_extensions( nifti_image *nim )
5051 {
5052    int c ;
5053    if( nim == NULL ) return -1;
5054    if( nim->num_ext > 0 && nim->ext_list ){
5055       for( c = 0; c < nim->num_ext; c++ )
5056          if ( nim->ext_list[c].edata ) free(nim->ext_list[c].edata);
5057       free(nim->ext_list);
5058    }
5059    /* or if it is inconsistent, warn the user (if we are not in quiet mode) */
5060    else if ( (nim->num_ext > 0 || nim->ext_list != NULL) && (g_opts.debug > 0) )
5061       fprintf(stderr,"** warning: nifti extension num/ptr mismatch (%d,%p)\n",
5062               nim->num_ext, (void *)nim->ext_list);
5063 
5064    if( g_opts.debug > 2 )
5065       fprintf(stderr,"+d free'd %d extension(s)\n", nim->num_ext);
5066 
5067    nim->num_ext = 0;
5068    nim->ext_list = NULL;
5069 
5070    return 0;
5071 }
5072 
5073 
5074 /*--------------------------------------------------------------------------*/
5075 /*! Print to stdout some info about a nifti_image struct.
5076 *//*------------------------------------------------------------------------*/
nifti_image_infodump(const nifti_image * nim)5077 void nifti_image_infodump( const nifti_image *nim )
5078 {
5079    char *str = nifti_image_to_ascii( nim ) ;
5080    /* stdout -> stderr   2 Dec 2004 [rickr] */
5081    if( str != NULL ){ fputs(str,stderr) ; free(str) ; }
5082    return ;
5083 }
5084 
5085 
5086 /*--------------------------------------------------------------------------
5087  * nifti_write_buffer just check for a null znzFile and call znzwrite
5088  *--------------------------------------------------------------------------*/
5089 /*! \fn size_t nifti_write_buffer(znzFile fp, void *buffer, size_t numbytes)
5090     \brief write numbytes of buffer to file, fp
5091 
5092     \param fp           File pointer (from znzopen) to gzippable nifti datafile
5093     \param buffer       data buffer to be written
5094     \param numbytes     number of bytes in buffer to write
5095     \return number of bytes successfully written
5096 */
nifti_write_buffer(znzFile fp,const void * buffer,size_t numbytes)5097 size_t nifti_write_buffer(znzFile fp, const void *buffer, size_t numbytes)
5098 {
5099    /* Write all the image data at once (no swapping here) */
5100    size_t ss;
5101    if (znz_isnull(fp)){
5102       fprintf(stderr,"** ERROR: nifti_write_buffer: null file pointer\n");
5103       return 0;
5104    }
5105    ss = znzwrite( (void*)buffer , 1 , numbytes , fp ) ;
5106    return ss;
5107 }
5108 
5109 
5110 /*----------------------------------------------------------------------*/
5111 /*! write the nifti_image data to file (from nim->data or from NBL)
5112 
5113    If NBL is not NULL, write the data from that structure.  Otherwise,
5114    write it out from nim->data.  No swapping is done here.
5115 
5116    \param  fp  : File pointer
5117    \param  nim : nifti_image corresponding to the data
5118    \param  NBL : optional source of write data (if NULL use nim->data)
5119 
5120    \return 0 on success, -1 on failure
5121 
5122    Note: the nifti_image byte_order is set as that of the current CPU.
5123          This is because such a conversion was made to the data upon
5124          reading, while byte_order was not set (so the programs would
5125          know what format the data was on disk).  Effectively, since
5126          byte_order should match what is on disk, it should bet set to
5127          that of the current CPU whenever new filenames are assigned.
5128 *//*--------------------------------------------------------------------*/
nifti_write_all_data(znzFile fp,nifti_image * nim,const nifti_brick_list * NBL)5129 int nifti_write_all_data(znzFile fp, nifti_image * nim,
5130                          const nifti_brick_list * NBL)
5131 {
5132    size_t ss;
5133    int    bnum;
5134 
5135    if( !NBL ){ /* just write one buffer and get out of here */
5136       if( nim->data == NULL ){
5137          fprintf(stderr,"** NWAD: no image data to write\n");
5138          return -1;
5139       }
5140 
5141       ss = nifti_write_buffer(fp,nim->data,nim->nbyper * nim->nvox);
5142       if (ss < nim->nbyper * nim->nvox){
5143          fprintf(stderr,
5144             "** ERROR: NWAD: wrote only %u of %u bytes to file\n",
5145             (unsigned)ss, (unsigned)(nim->nbyper * nim->nvox));
5146          return -1;
5147       }
5148 
5149       if( g_opts.debug > 1 )
5150          fprintf(stderr,"+d wrote single image of %u bytes\n", (unsigned)ss);
5151    } else {
5152       if( ! NBL->bricks || NBL->nbricks <= 0 || NBL->bsize <= 0 ){
5153          fprintf(stderr,"** NWAD: no brick data to write (%p,%d,%u)\n",
5154                  (void *)NBL->bricks, NBL->nbricks, (unsigned)NBL->bsize);
5155          return -1;
5156       }
5157 
5158       for( bnum = 0; bnum < NBL->nbricks; bnum++ ){
5159          ss = nifti_write_buffer(fp, NBL->bricks[bnum], NBL->bsize);
5160          if( ss < NBL->bsize ){
5161             fprintf(stderr,
5162               "** NWAD ERROR: wrote %u of %u bytes of brick %d of %d to file",
5163                (unsigned)ss, (unsigned)NBL->bsize, bnum+1, NBL->nbricks);
5164             return -1;
5165          }
5166       }
5167       if( g_opts.debug > 1 )
5168          fprintf(stderr,"+d wrote image of %d brick(s), each of %u bytes\n",
5169                  NBL->nbricks, (unsigned int)NBL->bsize);
5170    }
5171 
5172    /* mark as being in this CPU byte order */
5173    nim->byteorder = nifti_short_order() ;
5174 
5175    return 0;
5176 }
5177 
5178 /* return number of extensions written, or -1 on error */
nifti_write_extensions(znzFile fp,nifti_image * nim)5179 static int nifti_write_extensions(znzFile fp, nifti_image *nim)
5180 {
5181    nifti1_extension * list;
5182    char               extdr[4] = { 0, 0, 0, 0 };
5183    int                c, size, ok = 1;
5184 
5185    if( znz_isnull(fp) || !nim || nim->num_ext < 0 ){
5186       if( g_opts.debug > 0 )
5187          fprintf(stderr,"** nifti_write_extensions, bad params\n");
5188       return -1;
5189    }
5190 
5191    /* if no extensions and user requests it, skip extender */
5192    if( g_opts.skip_blank_ext && (nim->num_ext == 0 || ! nim->ext_list ) ){
5193       if( g_opts.debug > 1 )
5194          fprintf(stderr,"-d no exts and skip_blank_ext set, "
5195                         "so skipping 4-byte extender\n");
5196       return 0;
5197    }
5198 
5199    /* if invalid extension list, clear num_ext */
5200    if( ! valid_nifti_extensions(nim) ) nim->num_ext = 0;
5201 
5202    /* write out extender block */
5203    if( nim->num_ext > 0 ) extdr[0] = 1;
5204    if( nifti_write_buffer(fp, extdr, 4) != 4 ){
5205       fprintf(stderr,"** failed to write extender\n");
5206       return -1;
5207    }
5208 
5209    list = nim->ext_list;
5210    for ( c = 0; c < nim->num_ext; c++ ){
5211       size = (int)nifti_write_buffer(fp, &list->esize, sizeof(int));
5212       ok = (size == (int)sizeof(int));
5213       if( ok ){
5214          size = (int)nifti_write_buffer(fp, &list->ecode, sizeof(int));
5215          ok = (size == (int)sizeof(int));
5216       }
5217       if( ok ){
5218          size = (int)nifti_write_buffer(fp, list->edata, list->esize - 8);
5219          ok = (size == list->esize - 8);
5220       }
5221 
5222       if( !ok ){
5223          fprintf(stderr,"** failed while writing extension #%d\n",c);
5224          return -1;
5225       } else if ( g_opts.debug > 2 )
5226          fprintf(stderr,"+d wrote extension %d of %d bytes\n", c, size);
5227 
5228       list++;
5229    }
5230 
5231    if( g_opts.debug > 1 )
5232       fprintf(stderr,"+d wrote out %d extension(s)\n", nim->num_ext);
5233 
5234    return nim->num_ext;
5235 }
5236 
5237 
5238 /*----------------------------------------------------------------------*/
5239 /*! basic initialization of a nifti_image struct (to a 1x1x1 image)
5240 *//*--------------------------------------------------------------------*/
nifti_simple_init_nim(void)5241 nifti_image* nifti_simple_init_nim(void)
5242 {
5243   nifti_image *nim;
5244   struct nifti_1_header nhdr;
5245   int nbyper, swapsize;
5246 
5247    memset(&nhdr,0,sizeof(nhdr)) ;  /* zero out header, to be safe */
5248 
5249    nhdr.sizeof_hdr = sizeof(nhdr) ;
5250    nhdr.regular    = 'r' ;           /* for some stupid reason */
5251 
5252    nhdr.dim[0] = 3 ;
5253    nhdr.dim[1] = 1 ; nhdr.dim[2] = 1 ; nhdr.dim[3] = 1 ;
5254    nhdr.dim[4] = 0 ;
5255 
5256    nhdr.pixdim[0] = 0.0 ;
5257    nhdr.pixdim[1] = 1.0 ; nhdr.pixdim[2] = 1.0 ;
5258    nhdr.pixdim[3] = 1.0 ;
5259 
5260    nhdr.datatype = DT_FLOAT32 ;
5261    nifti_datatype_sizes( nhdr.datatype , &nbyper, &swapsize );
5262    nhdr.bitpix   = 8 * nbyper ;
5263 
5264    strcpy(nhdr.magic, "n+1");  /* init to single file */
5265 
5266    nim = nifti_convert_nhdr2nim(nhdr,NULL);
5267    nim->fname = NULL;
5268    nim->iname = NULL;
5269    return nim;
5270 }
5271 
5272 
5273 /*----------------------------------------------------------------------*/
5274 /*! basic initialization of a nifti_1_header struct (with given dimensions)
5275 
5276    Return an allocated nifti_1_header struct, based on the given
5277    dimensions and datatype.
5278 
5279    \param arg_dims  : optional dim[8] array (default {3,1,1,1,0,0,0,0})
5280    \param arg_dtype : optional datatype (default DT_FLOAT32)
5281 
5282    \return pointer to allocated nifti_1_header struct
5283 *//*--------------------------------------------------------------------*/
nifti_make_new_header(const int arg_dims[],int arg_dtype)5284 nifti_1_header * nifti_make_new_header(const int arg_dims[], int arg_dtype)
5285 {
5286    nifti_1_header * nhdr;
5287    const int        default_dims[8] = { 3, 1, 1, 1, 0, 0, 0, 0 };
5288    const int      * dim;  /* either passed or default dims  */
5289    int              dtype; /* either passed or default dtype */
5290    int              c, nbyper, swapsize;
5291 
5292    /* if arg_dims is passed, apply it */
5293    if( arg_dims ) dim = arg_dims;
5294    else           dim = default_dims;
5295 
5296    /* validate dim: if there is any problem, apply default_dims */
5297    if( dim[0] < 1 || dim[0] > 7 ) {
5298       fprintf(stderr,"** nifti_simple_hdr_with_dims: bad dim[0]=%d\n",dim[0]);
5299       dim = default_dims;
5300    } else {
5301       for( c = 1; c <= dim[0]; c++ )
5302          if( dim[c] < 1 )
5303          {
5304             fprintf(stderr,
5305                 "** nifti_simple_hdr_with_dims: bad dim[%d]=%d\n",c,dim[c]);
5306             dim = default_dims;
5307             break;
5308          }
5309    }
5310 
5311    /* validate dtype, too */
5312    dtype = arg_dtype;
5313    if( ! nifti_is_valid_datatype(dtype) ) {
5314       fprintf(stderr,"** nifti_simple_hdr_with_dims: bad dtype %d\n",dtype);
5315       dtype = DT_FLOAT32;
5316    }
5317 
5318    /* now populate the header struct */
5319 
5320    if( g_opts.debug > 1 )
5321       fprintf(stderr,"+d nifti_make_new_header, dim[0] = %d, datatype = %d\n",
5322               dim[0], dtype);
5323 
5324    nhdr = (nifti_1_header *)calloc(1,sizeof(nifti_1_header));
5325    if( !nhdr ){
5326       fprintf(stderr,"** nifti_make_new_header: failed to alloc hdr\n");
5327       return NULL;
5328    }
5329 
5330    nhdr->sizeof_hdr = sizeof(nifti_1_header) ;
5331    nhdr->regular    = 'r' ;           /* for some stupid reason */
5332 
5333    /* init dim and pixdim */
5334    nhdr->dim[0] = dim[0] ;
5335    nhdr->pixdim[0] = 0.0;
5336    for( c = 1; c <= dim[0]; c++ ) {
5337       nhdr->dim[c] = dim[c];
5338       nhdr->pixdim[c] = 1.0;
5339    }
5340 
5341    nhdr->datatype = dtype ;
5342    nifti_datatype_sizes( nhdr->datatype , &nbyper, &swapsize );
5343    nhdr->bitpix   = 8 * nbyper ;
5344 
5345    strcpy(nhdr->magic, "n+1");  /* init to single file */
5346 
5347    return nhdr;
5348 }
5349 
5350 
5351 /*----------------------------------------------------------------------*/
5352 /*! basic creation of a nifti_image struct
5353 
5354    Create a nifti_image from the given dimensions and data type.
5355    Optinally, allocate zero-filled data.
5356 
5357    \param dims      : optional dim[8]   (default {3,1,1,1,0,0,0,0})
5358    \param datatype  : optional datatype (default DT_FLOAT32)
5359    \param data_fill : if flag is set, allocate zero-filled data for image
5360 
5361    \return pointer to allocated nifti_image struct
5362 *//*--------------------------------------------------------------------*/
nifti_make_new_nim(const int dims[],int datatype,int data_fill)5363 nifti_image * nifti_make_new_nim(const int dims[], int datatype, int data_fill)
5364 {
5365    nifti_image    * nim;
5366    nifti_1_header * nhdr;
5367 
5368    nhdr = nifti_make_new_header(dims, datatype);
5369    if( !nhdr ) return NULL;  /* error already printed */
5370 
5371    nim = nifti_convert_nhdr2nim(*nhdr,NULL);
5372    free(nhdr);               /* in any case, we are done with this */
5373    if( !nim ){
5374       fprintf(stderr,"** NMNN: nifti_convert_nhdr2nim failure\n");
5375       return NULL;
5376    }
5377 
5378    if( g_opts.debug > 1 )
5379       fprintf(stderr,"+d nifti_make_new_nim, data_fill = %d\n",data_fill);
5380 
5381    if( data_fill ) {
5382       nim->data = calloc(nim->nvox, nim->nbyper);
5383 
5384       /* if we cannot allocate data, take ball and go home */
5385       if( !nim->data ) {
5386          fprintf(stderr,"** NMNN: failed to alloc %u bytes for data\n",
5387                  (unsigned)(nim->nvox*nim->nbyper));
5388          nifti_image_free(nim);
5389          nim = NULL;
5390       }
5391    }
5392 
5393    return nim;
5394 }
5395 
5396 
5397 /*----------------------------------------------------------------------*/
5398 /*! convert a nifti_image structure to a nifti_1_header struct
5399 
5400     No allocation is done, this should be used via structure copy.
5401     As in:
5402     <pre>
5403     nifti_1_header my_header;
5404     my_header = nifti_convert_nim2nhdr(my_nim_pointer);
5405     </pre>
5406 *//*--------------------------------------------------------------------*/
nifti_convert_nim2nhdr(const nifti_image * nim)5407 struct nifti_1_header nifti_convert_nim2nhdr(const nifti_image * nim)
5408 {
5409    struct nifti_1_header nhdr;
5410 
5411    memset(&nhdr,0,sizeof(nhdr)) ;  /* zero out header, to be safe */
5412 
5413 
5414    /**- load the ANALYZE-7.5 generic parts of the header struct */
5415 
5416    nhdr.sizeof_hdr = sizeof(nhdr) ;
5417    nhdr.regular    = 'r' ;             /* for some stupid reason */
5418 
5419    nhdr.dim[0] = nim->ndim ;
5420    nhdr.dim[1] = nim->nx ; nhdr.dim[2] = nim->ny ; nhdr.dim[3] = nim->nz ;
5421    nhdr.dim[4] = nim->nt ; nhdr.dim[5] = nim->nu ; nhdr.dim[6] = nim->nv ;
5422    nhdr.dim[7] = nim->nw ;
5423 
5424    nhdr.pixdim[0] = 0.0 ;
5425    nhdr.pixdim[1] = nim->dx ; nhdr.pixdim[2] = nim->dy ;
5426    nhdr.pixdim[3] = nim->dz ; nhdr.pixdim[4] = nim->dt ;
5427    nhdr.pixdim[5] = nim->du ; nhdr.pixdim[6] = nim->dv ;
5428    nhdr.pixdim[7] = nim->dw ;
5429 
5430    nhdr.datatype = nim->datatype ;
5431    nhdr.bitpix   = 8 * nim->nbyper ;
5432 
5433    if( nim->cal_max > nim->cal_min ){
5434      nhdr.cal_max = nim->cal_max ;
5435      nhdr.cal_min = nim->cal_min ;
5436    }
5437 
5438    if( nim->scl_slope != 0.0 ){
5439      nhdr.scl_slope = nim->scl_slope ;
5440      nhdr.scl_inter = nim->scl_inter ;
5441    }
5442 
5443    if( nim->descrip[0] != '\0' ){
5444      memcpy(nhdr.descrip ,nim->descrip ,79) ; nhdr.descrip[79] = '\0' ;
5445    }
5446    if( nim->aux_file[0] != '\0' ){
5447      memcpy(nhdr.aux_file ,nim->aux_file ,23) ; nhdr.aux_file[23] = '\0' ;
5448    }
5449 
5450    /**- Load NIFTI specific stuff into the header */
5451 
5452    if( nim->nifti_type > NIFTI_FTYPE_ANALYZE ){ /* then not ANALYZE */
5453 
5454      if( nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ) strcpy(nhdr.magic,"n+1") ;
5455      else                                          strcpy(nhdr.magic,"ni1") ;
5456 
5457      nhdr.pixdim[1] = fabs(nhdr.pixdim[1]) ; nhdr.pixdim[2] = fabs(nhdr.pixdim[2]) ;
5458      nhdr.pixdim[3] = fabs(nhdr.pixdim[3]) ; nhdr.pixdim[4] = fabs(nhdr.pixdim[4]) ;
5459      nhdr.pixdim[5] = fabs(nhdr.pixdim[5]) ; nhdr.pixdim[6] = fabs(nhdr.pixdim[6]) ;
5460      nhdr.pixdim[7] = fabs(nhdr.pixdim[7]) ;
5461 
5462      nhdr.intent_code = nim->intent_code ;
5463      nhdr.intent_p1   = nim->intent_p1 ;
5464      nhdr.intent_p2   = nim->intent_p2 ;
5465      nhdr.intent_p3   = nim->intent_p3 ;
5466      if( nim->intent_name[0] != '\0' ){
5467        memcpy(nhdr.intent_name,nim->intent_name,15) ;
5468        nhdr.intent_name[15] = '\0' ;
5469      }
5470 
5471      nhdr.vox_offset  = (float) nim->iname_offset ;
5472      nhdr.xyzt_units  = SPACE_TIME_TO_XYZT( nim->xyz_units, nim->time_units ) ;
5473      nhdr.toffset     = nim->toffset ;
5474 
5475      if( nim->qform_code > 0 ){
5476        nhdr.qform_code = nim->qform_code ;
5477        nhdr.quatern_b  = nim->quatern_b ;
5478        nhdr.quatern_c  = nim->quatern_c ;
5479        nhdr.quatern_d  = nim->quatern_d ;
5480        nhdr.qoffset_x  = nim->qoffset_x ;
5481        nhdr.qoffset_y  = nim->qoffset_y ;
5482        nhdr.qoffset_z  = nim->qoffset_z ;
5483        nhdr.pixdim[0]  = (nim->qfac >= 0.0) ? 1.0 : -1.0 ;
5484      }
5485 
5486      if( nim->sform_code > 0 ){
5487        nhdr.sform_code = nim->sform_code ;
5488        nhdr.srow_x[0]  = nim->sto_xyz.m[0][0] ;
5489        nhdr.srow_x[1]  = nim->sto_xyz.m[0][1] ;
5490        nhdr.srow_x[2]  = nim->sto_xyz.m[0][2] ;
5491        nhdr.srow_x[3]  = nim->sto_xyz.m[0][3] ;
5492        nhdr.srow_y[0]  = nim->sto_xyz.m[1][0] ;
5493        nhdr.srow_y[1]  = nim->sto_xyz.m[1][1] ;
5494        nhdr.srow_y[2]  = nim->sto_xyz.m[1][2] ;
5495        nhdr.srow_y[3]  = nim->sto_xyz.m[1][3] ;
5496        nhdr.srow_z[0]  = nim->sto_xyz.m[2][0] ;
5497        nhdr.srow_z[1]  = nim->sto_xyz.m[2][1] ;
5498        nhdr.srow_z[2]  = nim->sto_xyz.m[2][2] ;
5499        nhdr.srow_z[3]  = nim->sto_xyz.m[2][3] ;
5500      }
5501 
5502      nhdr.dim_info = FPS_INTO_DIM_INFO( nim->freq_dim ,
5503                                         nim->phase_dim , nim->slice_dim ) ;
5504      nhdr.slice_code     = nim->slice_code ;
5505      nhdr.slice_start    = nim->slice_start ;
5506      nhdr.slice_end      = nim->slice_end ;
5507      nhdr.slice_duration = nim->slice_duration ;
5508    }
5509 
5510    return nhdr;
5511 }
5512 
5513 
5514 /*----------------------------------------------------------------------*/
5515 /*! \fn int nifti_copy_extensions(nifti_image * nim_dest, nifti_image * nim_src)
5516     \brief copy the nifti1_extension list from src to dest
5517 
5518     Duplicate the list of nifti1_extensions.  The dest structure must
5519     be clear of extensions.
5520     \return 0 on success, -1 on failure
5521 
5522     \sa nifti_add_extension, nifti_free_extensions
5523 */
nifti_copy_extensions(nifti_image * nim_dest,const nifti_image * nim_src)5524 int nifti_copy_extensions(nifti_image * nim_dest, const nifti_image * nim_src)
5525 {
5526    char   * data;
5527    size_t   bytes;
5528    int      c, size, old_size;
5529 
5530    if( nim_dest->num_ext > 0 || nim_dest->ext_list != NULL ){
5531       fprintf(stderr,"** will not copy extensions over existing ones\n");
5532       return -1;
5533    }
5534 
5535    if( g_opts.debug > 1 )
5536       fprintf(stderr,"+d duplicating %d extension(s)\n", nim_src->num_ext);
5537 
5538    if( nim_src->num_ext <= 0 ) return 0;
5539 
5540    bytes = nim_src->num_ext * sizeof(nifti1_extension);  /* I'm lazy */
5541    nim_dest->ext_list = (nifti1_extension *)malloc(bytes);
5542    if( !nim_dest->ext_list ){
5543       fprintf(stderr,"** failed to allocate %d nifti1_extension structs\n",
5544               nim_src->num_ext);
5545       return -1;
5546    }
5547 
5548    /* copy the extension data */
5549    nim_dest->num_ext = 0;
5550    for( c = 0; c < nim_src->num_ext; c++ ){
5551       size = old_size = nim_src->ext_list[c].esize;
5552       if( size & 0xf ) size = (size + 0xf) & ~0xf; /* make multiple of 16 */
5553       if( g_opts.debug > 2 )
5554          fprintf(stderr,"+d dup'ing ext #%d of size %d (from size %d)\n",
5555                  c, size, old_size);
5556       /* data length is size-8, as esize includes space for esize and ecode */
5557       data = (char *)calloc(size-8,sizeof(char));      /* maybe size > old */
5558       if( !data ){
5559          fprintf(stderr,"** failed to alloc %d bytes for extention\n", size);
5560          if( c == 0 ) { free(nim_dest->ext_list); nim_dest->ext_list = NULL; }
5561          /* otherwise, keep what we have (a.o.t. deleting them all) */
5562          return -1;
5563       }
5564       /* finally, fill the new structure */
5565       nim_dest->ext_list[c].esize = size;
5566       nim_dest->ext_list[c].ecode = nim_src->ext_list[c].ecode;
5567       nim_dest->ext_list[c].edata = data;
5568       memcpy(data, nim_src->ext_list[c].edata, old_size-8);
5569 
5570       nim_dest->num_ext++;
5571    }
5572 
5573    return 0;
5574 }
5575 
5576 
5577 /*----------------------------------------------------------------------*/
5578 /*! compute the total size of all extensions
5579 
5580     \return the total of all esize fields
5581 
5582     Note that each esize includes 4 bytes for ecode, 4 bytes for esize,
5583     and the bytes used for the data.  Each esize also needs to be a
5584     multiple of 16, so it may be greater than the sum of its 3 parts.
5585 *//*--------------------------------------------------------------------*/
nifti_extension_size(nifti_image * nim)5586 int nifti_extension_size(nifti_image *nim)
5587 {
5588    int c, size = 0;
5589 
5590    if( !nim || nim->num_ext <= 0 ) return 0;
5591 
5592    if( g_opts.debug > 2 ) fprintf(stderr,"-d ext sizes:");
5593 
5594    for ( c = 0; c < nim->num_ext; c++ ){
5595       size += nim->ext_list[c].esize;
5596       if( g_opts.debug > 2 ) fprintf(stderr,"  %d",nim->ext_list[c].esize);
5597    }
5598 
5599    if( g_opts.debug > 2 ) fprintf(stderr," (total = %d)\n",size);
5600 
5601    return size;
5602 }
5603 
5604 
5605 /*----------------------------------------------------------------------*/
5606 /*! set the nifti_image iname_offset field, based on nifti_type
5607 
5608     - if writing to 2 files, set offset to 0
5609     - if writing to a single NIFTI-1 file, set the offset to
5610          352 + total extension size, then align to 16-byte boundary
5611     - if writing an ASCII header, set offset to -1
5612 *//*--------------------------------------------------------------------*/
nifti_set_iname_offset(nifti_image * nim)5613 void nifti_set_iname_offset(nifti_image *nim)
5614 {
5615    int offset;
5616 
5617    switch( nim->nifti_type ){
5618 
5619      default:  /* writing into 2 files */
5620        /* we only write files with 0 offset in the 2 file format */
5621        nim->iname_offset = 0 ;
5622      break ;
5623 
5624      /* NIFTI-1 single binary file - always update */
5625      case NIFTI_FTYPE_NIFTI1_1:
5626        offset = nifti_extension_size(nim)+sizeof(struct nifti_1_header)+4;
5627        /* be sure offset is aligned to a 16 byte boundary */
5628        if ( ( offset % 16 ) != 0 )  offset = ((offset + 0xf) & ~0xf);
5629        if( nim->iname_offset != offset ){
5630           if( g_opts.debug > 1 )
5631              fprintf(stderr,"+d changing offset from %d to %d\n",
5632                   nim->iname_offset, offset);
5633           nim->iname_offset = offset;
5634        }
5635      break ;
5636 
5637      /* non-standard case: NIFTI-1 ASCII header + binary data (single file) */
5638      case NIFTI_FTYPE_ASCII:
5639        nim->iname_offset = -1 ;             /* compute offset from filesize */
5640      break ;
5641    }
5642 }
5643 
5644 
5645 /*----------------------------------------------------------------------*/
5646 /*! write the nifti_image dataset to disk, optionally including data
5647 
5648    This is just a front-end for nifti_image_write_hdr_img2.
5649 
5650    \param nim        nifti_image to write to disk
5651    \param write_data write options (see nifti_image_write_hdr_img2)
5652    \param opts       file open options ("wb" from nifti_image_write)
5653 
5654    \sa nifti_image_write, nifti_image_write_hdr_img2, nifti_image_free,
5655        nifti_set_filenames
5656 *//*--------------------------------------------------------------------*/
nifti_image_write_hdr_img(nifti_image * nim,int write_data,const char * opts)5657 znzFile nifti_image_write_hdr_img( nifti_image *nim , int write_data ,
5658                                           const char* opts )
5659 {
5660   return nifti_image_write_hdr_img2(nim,write_data,opts,NULL,NULL);
5661 }
5662 
5663 
5664 #undef  ERREX
5665 #define ERREX(msg)                                                \
5666  do{ fprintf(stderr,"** ERROR: nifti_image_write_hdr_img: %s\n",(msg)) ;  \
5667      return fp ; } while(0)
5668 
5669 
5670 /* ----------------------------------------------------------------------*/
5671 /*! This writes the header (and optionally the image data) to file
5672  *
5673  * If the image data file is left open it returns a valid znzFile handle.
5674  * It also uses imgfile as the open image file is not null, and modifies
5675  * it inside.
5676  *
5677  * \param nim        nifti_image to write to disk
5678  * \param write_opts flags whether to write data and/or close file (see below)
5679  * \param opts       file-open options, probably "wb" from nifti_image_write()
5680  * \param imgfile    optional open znzFile struct, for writing image data
5681                      (may be NULL)
5682  * \param NBL        optional nifti_brick_list, containing the image data
5683                      (may be NULL)
5684  *
5685  * Values for write_opts mode are based on two binary flags
5686  * ( 0/1 for no-write/write data, and 0/2 for close/leave-open files ) :
5687  *    -   0 = do not write data and close (do not open data file)
5688  *    -   1 = write data        and close
5689  *    -   2 = do not write data and leave data file open
5690  *    -   3 = write data        and leave data file open
5691  *
5692  * \sa nifti_image_write, nifti_image_write_hdr_img, nifti_image_free,
5693  *     nifti_set_filenames
5694 *//*---------------------------------------------------------------------*/
nifti_image_write_hdr_img2(nifti_image * nim,int write_opts,const char * opts,znzFile imgfile,const nifti_brick_list * NBL)5695 znzFile nifti_image_write_hdr_img2(nifti_image *nim, int write_opts,
5696                const char * opts, znzFile imgfile, const nifti_brick_list * NBL)
5697 {
5698    struct nifti_1_header nhdr ;
5699    znzFile               fp=NULL;
5700    size_t                ss ;
5701    int                   write_data, leave_open;
5702    char                  func[] = { "nifti_image_write_hdr_img2" };
5703 
5704    write_data = write_opts & 1;  /* just separate the bits now */
5705    leave_open = write_opts & 2;
5706 
5707    if( ! nim                              ) ERREX("NULL input") ;
5708    if( ! nifti_validfilename(nim->fname)  ) ERREX("bad fname input") ;
5709    if( write_data && ! nim->data && ! NBL ) ERREX("no image data") ;
5710 
5711    if( write_data && NBL && ! nifti_NBL_matches_nim(nim, NBL) )
5712       ERREX("NBL does not match nim");
5713 
5714    nifti_set_iname_offset(nim);
5715 
5716    if( g_opts.debug > 1 ){
5717       fprintf(stderr,"-d writing nifti file '%s'...\n", nim->fname);
5718       if( g_opts.debug > 2 )
5719          fprintf(stderr,"-d nifti type %d, offset %d\n",
5720                  nim->nifti_type, nim->iname_offset);
5721    }
5722 
5723    if( nim->nifti_type == NIFTI_FTYPE_ASCII )   /* non-standard case */
5724       return nifti_write_ascii_image(nim,NBL,opts,write_data,leave_open);
5725 
5726    nhdr = nifti_convert_nim2nhdr(nim);    /* create the nifti1_header struct */
5727 
5728    /* if writing to 2 files, make sure iname is set and different from fname */
5729    if( nim->nifti_type != NIFTI_FTYPE_NIFTI1_1 ){
5730        if( nim->iname && strcmp(nim->iname,nim->fname) == 0 ){
5731          free(nim->iname) ; nim->iname = NULL ;
5732        }
5733        if( nim->iname == NULL ){ /* then make a new one */
5734          nim->iname = nifti_makeimgname(nim->fname,nim->nifti_type,0,0);
5735          if( nim->iname == NULL ) return NULL;
5736        }
5737    }
5738 
5739    /* if we have an imgfile and will write the header there, use it */
5740    if( ! znz_isnull(imgfile) && nim->nifti_type == NIFTI_FTYPE_NIFTI1_1 ){
5741       if( g_opts.debug > 2 ) fprintf(stderr,"+d using passed file for hdr\n");
5742       fp = imgfile;
5743    }
5744    else {
5745       if( g_opts.debug > 2 )
5746          fprintf(stderr,"+d opening output file %s [%s]\n",nim->fname,opts);
5747       fp = znzopen( nim->fname , opts , nifti_is_gzfile(nim->fname) ) ;
5748       if( znz_isnull(fp) ){
5749          LNI_FERR(func,"cannot open output file",nim->fname);
5750          return fp;
5751       }
5752    }
5753 
5754    /* write the header and extensions */
5755 
5756    ss = znzwrite(&nhdr , 1 , sizeof(nhdr) , fp); /* write header */
5757    if( ss < sizeof(nhdr) ){
5758       LNI_FERR(func,"bad header write to output file",nim->fname);
5759       znzclose(fp); return fp;
5760    }
5761 
5762    /* partial file exists, and errors have been printed, so ignore return */
5763    if( nim->nifti_type != NIFTI_FTYPE_ANALYZE )
5764       (void)nifti_write_extensions(fp,nim);
5765 
5766    /* if the header is all we want, we are done */
5767    if( ! write_data && ! leave_open ){
5768       if( g_opts.debug > 2 ) fprintf(stderr,"-d header is all we want: done\n");
5769       znzclose(fp); return(fp);
5770    }
5771 
5772    if( nim->nifti_type != NIFTI_FTYPE_NIFTI1_1 ){ /* get a new file pointer */
5773       znzclose(fp);         /* first, close header file */
5774       if( ! znz_isnull(imgfile) ){
5775          if(g_opts.debug > 2) fprintf(stderr,"+d using passed file for img\n");
5776          fp = imgfile;
5777       }
5778       else {
5779          if( g_opts.debug > 2 )
5780             fprintf(stderr,"+d opening img file '%s'\n", nim->iname);
5781          fp = znzopen( nim->iname , opts , nifti_is_gzfile(nim->iname) ) ;
5782          if( znz_isnull(fp) ) ERREX("cannot open image file") ;
5783       }
5784    }
5785 
5786    znzseek(fp, nim->iname_offset, SEEK_SET);  /* in any case, seek to offset */
5787 
5788    if( write_data ) nifti_write_all_data(fp,nim,NBL);
5789    if( ! leave_open ) znzclose(fp);
5790 
5791    return fp;
5792 }
5793 
5794 
5795 /*----------------------------------------------------------------------*/
5796 /*! write a nifti_image to disk in ASCII format
5797 *//*--------------------------------------------------------------------*/
nifti_write_ascii_image(nifti_image * nim,const nifti_brick_list * NBL,const char * opts,int write_data,int leave_open)5798 znzFile nifti_write_ascii_image(nifti_image *nim, const nifti_brick_list * NBL,
5799                               const char *opts, int write_data, int leave_open)
5800 {
5801    znzFile   fp;
5802    char    * hstr;
5803 
5804    hstr = nifti_image_to_ascii( nim ) ;  /* get header in ASCII form */
5805    if( ! hstr ){ fprintf(stderr,"** failed image_to_ascii()\n"); return NULL; }
5806 
5807    fp = znzopen( nim->fname , opts , nifti_is_gzfile(nim->fname) ) ;
5808    if( znz_isnull(fp) ){
5809       free(hstr);
5810       fprintf(stderr,"** failed to open '%s' for ascii write\n",nim->fname);
5811       return fp;
5812    }
5813 
5814    znzputs(hstr,fp);                                               /* header */
5815    nifti_write_extensions(fp,nim);                             /* extensions */
5816 
5817    if ( write_data   ) { nifti_write_all_data(fp,nim,NBL); }         /* data */
5818    if ( ! leave_open ) { znzclose(fp); }
5819    free(hstr);
5820    return fp;  /* returned but may be closed */
5821 }
5822 
5823 
5824 /*--------------------------------------------------------------------------*/
5825 /*! Write a nifti_image to disk.
5826 
5827    Since data is properly byte-swapped upon reading, it is assumed
5828    to be in the byte-order of the current CPU at write time.  Thus,
5829    nim->byte_order should match that of the current CPU.  Note that
5830    the nifti_set_filenames() function takes the flag, set_byte_order.
5831 
5832    The following fields of nim affect how the output appears:
5833     - nifti_type = 0 ==> ANALYZE-7.5 format file pair will be written
5834     - nifti_type = 1 ==> NIFTI-1 format single file will be written
5835                          (data offset will be 352+extensions)
5836     - nifti_type = 2 ==> NIFTI_1 format file pair will be written
5837     - nifti_type = 3 ==> NIFTI_1 ASCII single file will be written
5838     - fname is the name of the output file (header or header+data)
5839     - if a file pair is being written, iname is the name of the data file
5840     - existing files WILL be overwritten with extreme prejudice
5841     - if qform_code > 0, the quatern_*, qoffset_*, and qfac fields determine
5842       the qform output, NOT the qto_xyz matrix; if you want to compute these
5843       fields from the qto_xyz matrix, you can use the utility function
5844       nifti_mat44_to_quatern()
5845 
5846    \sa nifti_image_write_bricks, nifti_image_free, nifti_set_filenames,
5847        nifti_image_write_hdr_img
5848 *//*------------------------------------------------------------------------*/
nifti_image_write(nifti_image * nim)5849 void nifti_image_write( nifti_image *nim )
5850 {
5851    znzFile fp = nifti_image_write_hdr_img(nim,1,"wb");
5852    if( fp ){
5853       if( g_opts.debug > 2 ) fprintf(stderr,"-d niw: done with znzFile\n");
5854       free(fp);
5855    }
5856    if( g_opts.debug > 1 ) fprintf(stderr,"-d nifti_image_write: done\n");
5857 }
5858 
5859 
5860 /*----------------------------------------------------------------------*/
5861 /*! similar to nifti_image_write, but data is in NBL struct, not nim->data
5862 
5863    \sa nifti_image_write, nifti_image_free, nifti_set_filenames, nifti_free_NBL
5864 *//*--------------------------------------------------------------------*/
nifti_image_write_bricks(nifti_image * nim,const nifti_brick_list * NBL)5865 void nifti_image_write_bricks( nifti_image *nim, const nifti_brick_list * NBL )
5866 {
5867    znzFile fp = nifti_image_write_hdr_img2(nim,1,"wb",NULL,NBL);
5868    if( fp ){
5869       if( g_opts.debug > 2 ) fprintf(stderr,"-d niwb: done with znzFile\n");
5870       free(fp);
5871    }
5872    if( g_opts.debug > 1 ) fprintf(stderr,"-d niwb: done writing bricks\n");
5873 }
5874 
5875 
5876 /*----------------------------------------------------------------------*/
5877 /*! copy the nifti_image structure, without data
5878 
5879     Duplicate the structure, including fname, iname and extensions.
5880     Leave the data pointer as NULL.
5881 *//*--------------------------------------------------------------------*/
nifti_copy_nim_info(const nifti_image * src)5882 nifti_image * nifti_copy_nim_info(const nifti_image * src)
5883 {
5884   nifti_image *dest;
5885   dest = (nifti_image *)calloc(1,sizeof(nifti_image));
5886   if( !dest ){
5887      fprintf(stderr,"** NCNI: failed to alloc nifti_image\n");
5888      return NULL;
5889   }
5890   memcpy(dest, src, sizeof(nifti_image));
5891   if( src->fname ) dest->fname = nifti_strdup(src->fname);
5892   if( src->iname ) dest->iname = nifti_strdup(src->iname);
5893   dest->num_ext = 0;
5894   dest->ext_list = NULL;
5895   /* errors will be printed in NCE(), continue in either case */
5896   (void)nifti_copy_extensions(dest, src);
5897 
5898   dest->data = NULL;
5899 
5900   return dest;
5901 }
5902 
5903 
5904 /*------------------------------------------------------------------------*/
5905 /* Un-escape a C string in place -- that is, convert XML escape sequences
5906    back into their characters.  (This can be done in place since the
5907    replacement is always smaller than the input.)  Escapes recognized are:
5908      -  &lt;   ->  <
5909      -  &gt;   ->  >
5910      -  &quot; ->  "
5911      -  &apos; ->  '
5912      -  &amp;  ->  &
5913    Also replace CR LF pair (Microsoft), or CR alone (Macintosh) with
5914    LF (Unix), per the XML standard.
5915    Return value is number of replacements made (if you care).
5916 --------------------------------------------------------------------------*/
5917 
5918 #undef  CR
5919 #undef  LF
5920 #define CR 0x0D
5921 #define LF 0x0A
5922 
unescape_string(char * str)5923 static int unescape_string( char *str )
5924 {
5925    int ii,jj , nn,ll ;
5926 
5927    if( str == NULL ) return 0 ;                /* no string? */
5928    ll = (int)strlen(str) ; if( ll == 0 ) return 0 ;
5929 
5930    /* scan for escapes: &something; */
5931 
5932    for( ii=jj=nn=0 ; ii<ll ; ii++,jj++ ){ /* scan at ii; results go in at jj */
5933 
5934      if( str[ii] == '&' ){  /* start of escape? */
5935 
5936              if( ii+3 < ll        &&   /* &lt; */
5937                  str[ii+1] == 'l' &&
5938                  str[ii+2] == 't' &&
5939                  str[ii+3] == ';'   ){ str[jj] = '<' ; ii += 3 ; nn++ ; }
5940 
5941         else if( ii+3 < ll        &&   /* &gt; */
5942                  str[ii+1] == 'g' &&
5943                  str[ii+2] == 't' &&
5944                  str[ii+3] == ';'   ){ str[jj] = '>' ; ii += 3 ; nn++ ; }
5945 
5946         else if( ii+5 < ll        &&   /* &quot; */
5947                  str[ii+1] == 'q' &&
5948                  str[ii+2] == 'u' &&
5949                  str[ii+3] == 'o' &&
5950                  str[ii+4] == 't' &&
5951                  str[ii+5] == ';'   ){ str[jj] = '"' ; ii += 5 ; nn++ ; }
5952 
5953         else if( ii+5 < ll        &&   /* &apos; */
5954                  str[ii+1] == 'a' &&
5955                  str[ii+2] == 'p' &&
5956                  str[ii+3] == 'o' &&
5957                  str[ii+4] == 's' &&
5958                  str[ii+5] == ';'   ){ str[jj] = '\'' ; ii += 5 ; nn++ ; }
5959 
5960         else if( ii+4 < ll        &&  /* &amp; */
5961                  str[ii+1] == 'a' &&
5962                  str[ii+2] == 'm' &&
5963                  str[ii+3] == 'p' &&
5964                  str[ii+4] == ';'   ){ str[jj] = '&' ; ii += 4 ; nn++ ; }
5965 
5966         /* although the comments above don't mention it,
5967            we also look for XML style numeric escapes
5968            of the forms &#32; (decimal) and &#xfd; (hex) */
5969 
5970         else if( ii+3 < ll        &&
5971                  str[ii+1] == '#' &&
5972                  isdigit(str[ii+2]) ){   /* &#dec; */
5973 
5974            unsigned int val='?' ; int kk=ii+3 ;
5975            while( kk < ll && kk != ';' ) kk++ ;
5976            sscanf( str+ii+2 , "%u" , &val ) ;
5977            str[jj] = (char) val ; ii = kk ; nn++ ;
5978         }
5979 
5980         else if( ii+4 < ll        &&
5981                  str[ii+1] == '#' &&
5982                  str[ii+2] == 'x' &&
5983                  isxdigit(str[ii+3]) ){   /* &#hex; */
5984 
5985            unsigned int val='?' ; int kk=ii+4 ;
5986            while( kk < ll && kk != ';' ) kk++ ;
5987            sscanf( str+ii+3 , "%x" , &val ) ;
5988            str[jj] = (char) val ; ii = kk ; nn++ ;
5989         }
5990 
5991         /* didn't start a recognized escape, so just copy as normal */
5992 
5993         else if( jj < ii ){ str[jj] = str[ii] ; }
5994 
5995      } else if( str[ii] == CR ) {  /* is a carriage return */
5996 
5997         if( str[ii+1] == LF ){ str[jj] = LF ; ii++ ; nn++ ; }  /* CR LF */
5998         else                 { str[jj] = LF ;      ; nn++ ; }  /* CR only */
5999 
6000      } else { /* is a normal character, just copy to output */
6001 
6002              if( jj < ii ){ str[jj] = str[ii] ; }
6003      }
6004 
6005      /* at this point, ii=index of last character used up in scan
6006                        jj=index of last character written to (jj <= ii) */
6007    }
6008 
6009    if( jj < ll ) str[jj] = '\0' ; /* end string properly */
6010 
6011    return nn ;
6012 }
6013 
6014 /*------------------------------------------------------------------------*/
6015 /* Quotize (and escapize) one string, returning a new string.
6016    Approximately speaking, this is the inverse of unescape_string().
6017    The result should be free()-ed when you are done with it.
6018 --------------------------------------------------------------------------*/
6019 
escapize_string(const char * str)6020 static char *escapize_string( const char * str )
6021 {
6022    int ii,jj , lstr,lout ;
6023    char *out ;
6024 
6025    if( str == NULL || (lstr=(int)strlen(str)) == 0 ){      /* 0 length */
6026      out = nifti_strdup("''") ; return out ;                /* string?? */
6027    }
6028 
6029    lout = 4 ;                      /* initialize length of output */
6030    for( ii=0 ; ii < lstr ; ii++ ){ /* count characters for output */
6031      switch( str[ii] ){
6032        case '&':  lout += 5 ; break ;  /* replace '&' with "&amp;" */
6033 
6034        case '<':
6035        case '>':  lout += 4 ; break ;  /* replace '<' with "&lt;" */
6036 
6037        case '"' :
6038        case '\'': lout += 6 ; break ;  /* replace '"' with "&quot;" */
6039 
6040        case CR:
6041        case LF:   lout += 6 ; break ;  /* replace CR with "&#x0d;"
6042                                                   LF with "&#x0a;" */
6043 
6044        default: lout++ ; break ;      /* copy all other chars */
6045      }
6046    }
6047    out = (char *)calloc(1,lout) ;     /* allocate output string */
6048    if( !out ){
6049       fprintf(stderr,"** escapize_string: failed to alloc %d bytes\n",lout);
6050       return NULL;
6051    }
6052    out[0] = '\'' ;                    /* opening quote mark */
6053    for( ii=0,jj=1 ; ii < lstr ; ii++ ){
6054       switch( str[ii] ){
6055          default: out[jj++] = str[ii] ; break ;  /* normal characters */
6056 
6057          case '&':  memcpy(out+jj,"&amp;",5)  ; jj+=5 ; break ;
6058 
6059          case '<':  memcpy(out+jj,"&lt;",4)   ; jj+=4 ; break ;
6060          case '>':  memcpy(out+jj,"&gt;",4)   ; jj+=4 ; break ;
6061 
6062          case '"' : memcpy(out+jj,"&quot;",6) ; jj+=6 ; break ;
6063 
6064          case '\'': memcpy(out+jj,"&apos;",6) ; jj+=6 ; break ;
6065 
6066          case CR:   memcpy(out+jj,"&#x0d;",6) ; jj+=6 ; break ;
6067          case LF:   memcpy(out+jj,"&#x0a;",6) ; jj+=6 ; break ;
6068       }
6069    }
6070    out[jj++] = '\''  ;  /* closing quote mark */
6071    out[jj]   = '\0' ;  /* terminate the string */
6072    return out ;
6073 }
6074 
6075 /*---------------------------------------------------------------------------*/
6076 /*! Dump the information in a NIFTI image header to an XML-ish ASCII string
6077    that can later be converted back into a NIFTI header in
6078    nifti_image_from_ascii().
6079 
6080    The resulting string can be free()-ed when you are done with it.
6081 *//*-------------------------------------------------------------------------*/
nifti_image_to_ascii(const nifti_image * nim)6082 char *nifti_image_to_ascii( const nifti_image *nim )
6083 {
6084    char *buf , *ebuf ; int nbuf ;
6085 
6086    if( nim == NULL ) return NULL ;   /* stupid caller */
6087 
6088    buf = (char *)calloc(1,65534); nbuf = 0; /* longer than needed, to be safe */
6089    if( !buf ){
6090       fprintf(stderr,"** NITA: failed to alloc %d bytes\n",65534);
6091       return NULL;
6092    }
6093 
6094    sprintf( buf , "<nifti_image\n" ) ;   /* XML-ish opener */
6095 
6096    sprintf( buf+strlen(buf) , "  nifti_type = '%s'\n" ,
6097               (nim->nifti_type == NIFTI_FTYPE_NIFTI1_1) ? "NIFTI-1+"
6098              :(nim->nifti_type == NIFTI_FTYPE_NIFTI1_2) ? "NIFTI-1"
6099              :(nim->nifti_type == NIFTI_FTYPE_ASCII   ) ? "NIFTI-1A"
6100              :                         "ANALYZE-7.5" ) ;
6101 
6102    /** Strings that we don't control (filenames, etc.) that might
6103        contain "weird" characters (like quotes) are "escaped":
6104        - A few special characters are replaced by XML-style escapes, using
6105          the function escapize_string().
6106        - On input, function unescape_string() reverses this process.
6107        - The result is that the NIFTI ASCII-format header is XML-compliant. */
6108 
6109    ebuf = escapize_string(nim->fname) ;
6110    sprintf( buf+strlen(buf) , "  header_filename = %s\n",ebuf); free(ebuf);
6111 
6112    ebuf = escapize_string(nim->iname) ;
6113    sprintf( buf+strlen(buf) , "  image_filename = %s\n", ebuf); free(ebuf);
6114 
6115    sprintf( buf+strlen(buf) , "  image_offset = '%d'\n" , nim->iname_offset );
6116 
6117                        sprintf( buf+strlen(buf), "  ndim = '%d'\n", nim->ndim);
6118                        sprintf( buf+strlen(buf), "  nx = '%d'\n",   nim->nx  );
6119    if( nim->ndim > 1 ) sprintf( buf+strlen(buf), "  ny = '%d'\n",   nim->ny  );
6120    if( nim->ndim > 2 ) sprintf( buf+strlen(buf), "  nz = '%d'\n",   nim->nz  );
6121    if( nim->ndim > 3 ) sprintf( buf+strlen(buf), "  nt = '%d'\n",   nim->nt  );
6122    if( nim->ndim > 4 ) sprintf( buf+strlen(buf), "  nu = '%d'\n",   nim->nu  );
6123    if( nim->ndim > 5 ) sprintf( buf+strlen(buf), "  nv = '%d'\n",   nim->nv  );
6124    if( nim->ndim > 6 ) sprintf( buf+strlen(buf), "  nw = '%d'\n",   nim->nw  );
6125                        sprintf( buf+strlen(buf), "  dx = '%g'\n",   nim->dx  );
6126    if( nim->ndim > 1 ) sprintf( buf+strlen(buf), "  dy = '%g'\n",   nim->dy  );
6127    if( nim->ndim > 2 ) sprintf( buf+strlen(buf), "  dz = '%g'\n",   nim->dz  );
6128    if( nim->ndim > 3 ) sprintf( buf+strlen(buf), "  dt = '%g'\n",   nim->dt  );
6129    if( nim->ndim > 4 ) sprintf( buf+strlen(buf), "  du = '%g'\n",   nim->du  );
6130    if( nim->ndim > 5 ) sprintf( buf+strlen(buf), "  dv = '%g'\n",   nim->dv  );
6131    if( nim->ndim > 6 ) sprintf( buf+strlen(buf), "  dw = '%g'\n",   nim->dw  );
6132 
6133    sprintf( buf+strlen(buf) , "  datatype = '%d'\n" , nim->datatype ) ;
6134    sprintf( buf+strlen(buf) , "  datatype_name = '%s'\n" ,
6135                               nifti_datatype_string(nim->datatype) ) ;
6136 
6137    sprintf( buf+strlen(buf) , "  nvox = '%u'\n" , (unsigned)nim->nvox ) ;
6138    sprintf( buf+strlen(buf) , "  nbyper = '%d'\n" , nim->nbyper ) ;
6139 
6140    sprintf( buf+strlen(buf) , "  byteorder = '%s'\n" ,
6141             (nim->byteorder==MSB_FIRST) ? "MSB_FIRST" : "LSB_FIRST" ) ;
6142 
6143    if( nim->cal_min < nim->cal_max ){
6144      sprintf( buf+strlen(buf) , "  cal_min = '%g'\n", nim->cal_min ) ;
6145      sprintf( buf+strlen(buf) , "  cal_max = '%g'\n", nim->cal_max ) ;
6146    }
6147 
6148    if( nim->scl_slope != 0.0 ){
6149      sprintf( buf+strlen(buf) , "  scl_slope = '%g'\n" , nim->scl_slope ) ;
6150      sprintf( buf+strlen(buf) , "  scl_inter = '%g'\n" , nim->scl_inter ) ;
6151    }
6152 
6153    if( nim->intent_code > 0 ){
6154      sprintf( buf+strlen(buf) , "  intent_code = '%d'\n", nim->intent_code ) ;
6155      sprintf( buf+strlen(buf) , "  intent_code_name = '%s'\n" ,
6156                                 nifti_intent_string(nim->intent_code) ) ;
6157      sprintf( buf+strlen(buf) , "  intent_p1 = '%g'\n" , nim->intent_p1 ) ;
6158      sprintf( buf+strlen(buf) , "  intent_p2 = '%g'\n" , nim->intent_p2 ) ;
6159      sprintf( buf+strlen(buf) , "  intent_p3 = '%g'\n" , nim->intent_p3 ) ;
6160 
6161      if( nim->intent_name[0] != '\0' ){
6162        ebuf = escapize_string(nim->intent_name) ;
6163        sprintf( buf+strlen(buf) , "  intent_name = %s\n",ebuf) ;
6164        free(ebuf) ;
6165      }
6166    }
6167 
6168    if( nim->toffset != 0.0 )
6169      sprintf( buf+strlen(buf) , "  toffset = '%g'\n",nim->toffset ) ;
6170 
6171    if( nim->xyz_units > 0 )
6172      sprintf( buf+strlen(buf) ,
6173               "  xyz_units = '%d'\n"
6174               "  xyz_units_name = '%s'\n" ,
6175               nim->xyz_units , nifti_units_string(nim->xyz_units) ) ;
6176 
6177    if( nim->time_units > 0 )
6178      sprintf( buf+strlen(buf) ,
6179               "  time_units = '%d'\n"
6180               "  time_units_name = '%s'\n" ,
6181               nim->time_units , nifti_units_string(nim->time_units) ) ;
6182 
6183    if( nim->freq_dim > 0 )
6184      sprintf( buf+strlen(buf) , "  freq_dim = '%d'\n",nim->freq_dim ) ;
6185    if( nim->phase_dim > 0 )
6186      sprintf( buf+strlen(buf) , "  phase_dim = '%d'\n",nim->phase_dim ) ;
6187    if( nim->slice_dim > 0 )
6188      sprintf( buf+strlen(buf) , "  slice_dim = '%d'\n",nim->slice_dim ) ;
6189    if( nim->slice_code > 0 )
6190      sprintf( buf+strlen(buf) ,
6191               "  slice_code = '%d'\n"
6192               "  slice_code_name = '%s'\n" ,
6193               nim->slice_code , nifti_slice_string(nim->slice_code) ) ;
6194    if( nim->slice_start >= 0 && nim->slice_end > nim->slice_start )
6195      sprintf( buf+strlen(buf) ,
6196               "  slice_start = '%d'\n"
6197               "  slice_end = '%d'\n"  , nim->slice_start , nim->slice_end ) ;
6198    if( nim->slice_duration != 0.0 )
6199      sprintf( buf+strlen(buf) , "  slice_duration = '%g'\n",
6200               nim->slice_duration ) ;
6201 
6202    if( nim->descrip[0] != '\0' ){
6203      ebuf = escapize_string(nim->descrip) ;
6204      sprintf( buf+strlen(buf) , "  descrip = %s\n",ebuf) ;
6205      free(ebuf) ;
6206    }
6207 
6208    if( nim->aux_file[0] != '\0' ){
6209      ebuf = escapize_string(nim->aux_file) ;
6210      sprintf( buf+strlen(buf) , "  aux_file = %s\n",ebuf) ;
6211      free(ebuf) ;
6212    }
6213 
6214    if( nim->qform_code > 0 ){
6215      int i,j,k ;
6216 
6217      sprintf( buf+strlen(buf) ,
6218               "  qform_code = '%d'\n"
6219               "  qform_code_name = '%s'\n"
6220      "  qto_xyz_matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" ,
6221          nim->qform_code      , nifti_xform_string(nim->qform_code) ,
6222          nim->qto_xyz.m[0][0] , nim->qto_xyz.m[0][1] ,
6223          nim->qto_xyz.m[0][2] , nim->qto_xyz.m[0][3] ,
6224          nim->qto_xyz.m[1][0] , nim->qto_xyz.m[1][1] ,
6225          nim->qto_xyz.m[1][2] , nim->qto_xyz.m[1][3] ,
6226          nim->qto_xyz.m[2][0] , nim->qto_xyz.m[2][1] ,
6227          nim->qto_xyz.m[2][2] , nim->qto_xyz.m[2][3] ,
6228          nim->qto_xyz.m[3][0] , nim->qto_xyz.m[3][1] ,
6229          nim->qto_xyz.m[3][2] , nim->qto_xyz.m[3][3]  ) ;
6230 
6231      sprintf( buf+strlen(buf) ,
6232      "  qto_ijk_matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" ,
6233          nim->qto_ijk.m[0][0] , nim->qto_ijk.m[0][1] ,
6234          nim->qto_ijk.m[0][2] , nim->qto_ijk.m[0][3] ,
6235          nim->qto_ijk.m[1][0] , nim->qto_ijk.m[1][1] ,
6236          nim->qto_ijk.m[1][2] , nim->qto_ijk.m[1][3] ,
6237          nim->qto_ijk.m[2][0] , nim->qto_ijk.m[2][1] ,
6238          nim->qto_ijk.m[2][2] , nim->qto_ijk.m[2][3] ,
6239          nim->qto_ijk.m[3][0] , nim->qto_ijk.m[3][1] ,
6240          nim->qto_ijk.m[3][2] , nim->qto_ijk.m[3][3]  ) ;
6241 
6242      sprintf( buf+strlen(buf) ,
6243               "  quatern_b = '%g'\n"
6244               "  quatern_c = '%g'\n"
6245               "  quatern_d = '%g'\n"
6246               "  qoffset_x = '%g'\n"
6247               "  qoffset_y = '%g'\n"
6248               "  qoffset_z = '%g'\n"
6249               "  qfac = '%g'\n" ,
6250          nim->quatern_b , nim->quatern_c , nim->quatern_d ,
6251          nim->qoffset_x , nim->qoffset_y , nim->qoffset_z , nim->qfac ) ;
6252 
6253      nifti_mat44_to_orientation( nim->qto_xyz , &i,&j,&k ) ;
6254      if( i > 0 && j > 0 && k > 0 )
6255        sprintf( buf+strlen(buf) ,
6256                 "  qform_i_orientation = '%s'\n"
6257                 "  qform_j_orientation = '%s'\n"
6258                 "  qform_k_orientation = '%s'\n" ,
6259                 nifti_orientation_string(i) ,
6260                 nifti_orientation_string(j) ,
6261                 nifti_orientation_string(k)  ) ;
6262    }
6263 
6264    if( nim->sform_code > 0 ){
6265      int i,j,k ;
6266 
6267      sprintf( buf+strlen(buf) ,
6268               "  sform_code = '%d'\n"
6269               "  sform_code_name = '%s'\n"
6270      "  sto_xyz_matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" ,
6271          nim->sform_code      , nifti_xform_string(nim->sform_code) ,
6272          nim->sto_xyz.m[0][0] , nim->sto_xyz.m[0][1] ,
6273          nim->sto_xyz.m[0][2] , nim->sto_xyz.m[0][3] ,
6274          nim->sto_xyz.m[1][0] , nim->sto_xyz.m[1][1] ,
6275          nim->sto_xyz.m[1][2] , nim->sto_xyz.m[1][3] ,
6276          nim->sto_xyz.m[2][0] , nim->sto_xyz.m[2][1] ,
6277          nim->sto_xyz.m[2][2] , nim->sto_xyz.m[2][3] ,
6278          nim->sto_xyz.m[3][0] , nim->sto_xyz.m[3][1] ,
6279          nim->sto_xyz.m[3][2] , nim->sto_xyz.m[3][3]  ) ;
6280 
6281      sprintf( buf+strlen(buf) ,
6282      "  sto_ijk matrix = '%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g'\n" ,
6283          nim->sto_ijk.m[0][0] , nim->sto_ijk.m[0][1] ,
6284          nim->sto_ijk.m[0][2] , nim->sto_ijk.m[0][3] ,
6285          nim->sto_ijk.m[1][0] , nim->sto_ijk.m[1][1] ,
6286          nim->sto_ijk.m[1][2] , nim->sto_ijk.m[1][3] ,
6287          nim->sto_ijk.m[2][0] , nim->sto_ijk.m[2][1] ,
6288          nim->sto_ijk.m[2][2] , nim->sto_ijk.m[2][3] ,
6289          nim->sto_ijk.m[3][0] , nim->sto_ijk.m[3][1] ,
6290          nim->sto_ijk.m[3][2] , nim->sto_ijk.m[3][3]  ) ;
6291 
6292      nifti_mat44_to_orientation( nim->sto_xyz , &i,&j,&k ) ;
6293      if( i > 0 && j > 0 && k > 0 )
6294        sprintf( buf+strlen(buf) ,
6295                 "  sform_i_orientation = '%s'\n"
6296                 "  sform_j_orientation = '%s'\n"
6297                 "  sform_k_orientation = '%s'\n" ,
6298                 nifti_orientation_string(i) ,
6299                 nifti_orientation_string(j) ,
6300                 nifti_orientation_string(k)  ) ;
6301    }
6302 
6303    sprintf( buf+strlen(buf) , "  num_ext = '%d'\n", nim->num_ext ) ;
6304 
6305    sprintf( buf+strlen(buf) , "/>\n" ) ;   /* XML-ish closer */
6306 
6307    nbuf = (int)strlen(buf) ;
6308    buf  = (char *)realloc((void *)buf, nbuf+1); /* cut back to proper length */
6309    if( !buf ) fprintf(stderr,"** NITA: failed to realloc %d bytes\n",nbuf+1);
6310    return buf ;
6311 }
6312 
6313 /*---------------------------------------------------------------------------*/
6314 
6315 /*----------------------------------------------------------------------*/
6316 /*! get the byte order for this CPU
6317 
6318     - LSB_FIRST means least significant byte, first (little endian)
6319     - MSB_FIRST means most significant byte, first (big endian)
6320 *//*--------------------------------------------------------------------*/
nifti_short_order(void)6321 int nifti_short_order(void)   /* determine this CPU's byte order */
6322 {
6323    union { unsigned char bb[2] ;
6324            short         ss    ; } fred ;
6325 
6326    fred.bb[0] = 1 ; fred.bb[1] = 0 ;
6327 
6328    return (fred.ss == 1) ? LSB_FIRST : MSB_FIRST ;
6329 }
6330 
6331 /*---------------------------------------------------------------------------*/
6332 
6333 #undef  QQNUM
6334 #undef  QNUM
6335 #undef  QSTR
6336 
6337 /* macro to check lhs string against "n1"; if it matches,
6338    interpret rhs string as a number, and put it into nim->"n2" */
6339 
6340 #define QQNUM(n1,n2) if( strcmp(lhs,#n1)==0 ) nim->n2=strtod(rhs,NULL)
6341 
6342 /* same, but where "n1" == "n2" */
6343 
6344 #define QNUM(nam)    QQNUM(nam,nam)
6345 
6346 /* macro to check lhs string against "nam"; if it matches,
6347    put rhs string into nim->"nam" string, with max length = "ml" */
6348 
6349 #define QSTR(nam,ml) if( strcmp(lhs,#nam) == 0 )                           \
6350                        strncpy(nim->nam,rhs,ml), nim->nam[ml]='\0'
6351 
6352 /*---------------------------------------------------------------------------*/
6353 /*! Take an XML-ish ASCII string and create a NIFTI image header to match.
6354 
6355     NULL is returned if enough information isn't present in the input string.
6356     - The image data can later be loaded with nifti_image_load().
6357     - The struct returned here can be liberated with nifti_image_free().
6358     - Not a lot of error checking is done here to make sure that the
6359       input values are reasonable!
6360 *//*-------------------------------------------------------------------------*/
nifti_image_from_ascii(const char * str,int * bytes_read)6361 nifti_image *nifti_image_from_ascii( const char *str, int * bytes_read )
6362 {
6363    char lhs[1024] , rhs[1024] ;
6364    int ii , spos, nn ;
6365    nifti_image *nim ;              /* will be output */
6366 
6367    if( str == NULL || *str == '\0' ) return NULL ;  /* bad input!? */
6368 
6369    /* scan for opening string */
6370 
6371    spos = 0 ;
6372    ii = sscanf( str+spos , "%1023s%n" , lhs , &nn ) ; spos += nn ;
6373    if( ii == 0 || strcmp(lhs,"<nifti_image") != 0 ) return NULL ;
6374 
6375    /* create empty image struct */
6376 
6377    nim = (nifti_image *)calloc( 1 , sizeof(nifti_image) ) ;
6378    if( !nim ){
6379       fprintf(stderr,"** NIFA: failed to alloc nifti_image\n");
6380       return NULL;
6381    }
6382 
6383    nim->nx = nim->ny = nim->nz = nim->nt
6384            = nim->nu = nim->nv = nim->nw = 1 ;
6385    nim->dx = nim->dy = nim->dz = nim->dt
6386            = nim->du = nim->dv = nim->dw = 0 ;
6387    nim->qfac = 1.0 ;
6388 
6389    nim->byteorder = nifti_short_order() ;
6390 
6391    /* starting at str[spos], scan for "equations" of the form
6392          lhs = 'rhs'
6393       and assign rhs values into the struct component named by lhs */
6394 
6395    while(1){
6396 
6397      while( isspace((int) str[spos]) ) spos++ ;  /* skip whitespace */
6398      if( str[spos] == '\0' ) break ;       /* end of string? */
6399 
6400      /* get lhs string */
6401 
6402      ii = sscanf( str+spos , "%1023s%n" , lhs , &nn ) ; spos += nn ;
6403      if( ii == 0 || strcmp(lhs,"/>") == 0 ) break ;  /* end of input? */
6404 
6405      /* skip whitespace and the '=' marker */
6406 
6407      while( isspace((int) str[spos]) || str[spos] == '=' ) spos++ ;
6408      if( str[spos] == '\0' ) break ;       /* end of string? */
6409 
6410      /* if next character is a quote ', copy everything up to next '
6411         otherwise, copy everything up to next nonblank              */
6412 
6413      if( str[spos] == '\'' ){
6414         ii = spos+1 ;
6415         while( str[ii] != '\0' && str[ii] != '\'' ) ii++ ;
6416         nn = ii-spos-1 ; if( nn > 1023 ) nn = 1023 ;
6417         memcpy(rhs,str+spos+1,nn) ; rhs[nn] = '\0' ;
6418         spos = (str[ii] == '\'') ? ii+1 : ii ;
6419      } else {
6420         ii = sscanf( str+spos , "%1023s%n" , rhs , &nn ) ; spos += nn ;
6421         if( ii == 0 ) break ;  /* nothing found? */
6422      }
6423      unescape_string(rhs) ;  /* remove any XML escape sequences */
6424 
6425      /* Now can do the assignment, based on lhs string.
6426         Start with special cases that don't fit the QNUM/QSTR macros. */
6427 
6428      if( strcmp(lhs,"nifti_type") == 0 ){
6429             if( strcmp(rhs,"ANALYZE-7.5") == 0 )
6430                nim->nifti_type = NIFTI_FTYPE_ANALYZE ;
6431        else if( strcmp(rhs,"NIFTI-1+")    == 0 )
6432                nim->nifti_type = NIFTI_FTYPE_NIFTI1_1 ;
6433        else if( strcmp(rhs,"NIFTI-1")     == 0 )
6434                nim->nifti_type = NIFTI_FTYPE_NIFTI1_2 ;
6435        else if( strcmp(rhs,"NIFTI-1A")    == 0 )
6436                nim->nifti_type = NIFTI_FTYPE_ASCII ;
6437      }
6438      else if( strcmp(lhs,"header_filename") == 0 ){
6439        nim->fname = nifti_strdup(rhs) ;
6440      }
6441      else if( strcmp(lhs,"image_filename") == 0 ){
6442        nim->iname = nifti_strdup(rhs) ;
6443      }
6444      else if( strcmp(lhs,"sto_xyz_matrix") == 0 ){
6445        sscanf( rhs , "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f" ,
6446                &(nim->sto_xyz.m[0][0]) , &(nim->sto_xyz.m[0][1]) ,
6447                &(nim->sto_xyz.m[0][2]) , &(nim->sto_xyz.m[0][3]) ,
6448                &(nim->sto_xyz.m[1][0]) , &(nim->sto_xyz.m[1][1]) ,
6449                &(nim->sto_xyz.m[1][2]) , &(nim->sto_xyz.m[1][3]) ,
6450                &(nim->sto_xyz.m[2][0]) , &(nim->sto_xyz.m[2][1]) ,
6451                &(nim->sto_xyz.m[2][2]) , &(nim->sto_xyz.m[2][3]) ,
6452                &(nim->sto_xyz.m[3][0]) , &(nim->sto_xyz.m[3][1]) ,
6453                &(nim->sto_xyz.m[3][2]) , &(nim->sto_xyz.m[3][3])  ) ;
6454      }
6455      else if( strcmp(lhs,"byteorder") == 0 ){
6456        if( strcmp(rhs,"MSB_FIRST") == 0 ) nim->byteorder = MSB_FIRST ;
6457        if( strcmp(rhs,"LSB_FIRST") == 0 ) nim->byteorder = LSB_FIRST ;
6458      }
6459      else QQNUM(image_offset,iname_offset) ;
6460      else QNUM(datatype) ;
6461      else QNUM(ndim) ;
6462      else QNUM(nx) ;
6463      else QNUM(ny) ;
6464      else QNUM(nz) ;
6465      else QNUM(nt) ;
6466      else QNUM(nu) ;
6467      else QNUM(nv) ;
6468      else QNUM(nw) ;
6469      else QNUM(dx) ;
6470      else QNUM(dy) ;
6471      else QNUM(dz) ;
6472      else QNUM(dt) ;
6473      else QNUM(du) ;
6474      else QNUM(dv) ;
6475      else QNUM(dw) ;
6476      else QNUM(cal_min) ;
6477      else QNUM(cal_max) ;
6478      else QNUM(scl_slope) ;
6479      else QNUM(scl_inter) ;
6480      else QNUM(intent_code) ;
6481      else QNUM(intent_p1) ;
6482      else QNUM(intent_p2) ;
6483      else QNUM(intent_p3) ;
6484      else QSTR(intent_name,15) ;
6485      else QNUM(toffset) ;
6486      else QNUM(xyz_units) ;
6487      else QNUM(time_units) ;
6488      else QSTR(descrip,79) ;
6489      else QSTR(aux_file,23) ;
6490      else QNUM(qform_code) ;
6491      else QNUM(quatern_b) ;
6492      else QNUM(quatern_c) ;
6493      else QNUM(quatern_d) ;
6494      else QNUM(qoffset_x) ;
6495      else QNUM(qoffset_y) ;
6496      else QNUM(qoffset_z) ;
6497      else QNUM(qfac) ;
6498      else QNUM(sform_code) ;
6499      else QNUM(freq_dim) ;
6500      else QNUM(phase_dim) ;
6501      else QNUM(slice_dim) ;
6502      else QNUM(slice_code) ;
6503      else QNUM(slice_start) ;
6504      else QNUM(slice_end) ;
6505      else QNUM(slice_duration) ;
6506      else QNUM(num_ext) ;
6507 
6508    } /* end of while loop */
6509 
6510    if( bytes_read ) *bytes_read = spos+1;         /* "process" last '\n' */
6511 
6512    /* do miscellaneous checking and cleanup */
6513 
6514    if( nim->ndim <= 0 ){ nifti_image_free(nim); return NULL; } /* bad! */
6515 
6516    nifti_datatype_sizes( nim->datatype, &(nim->nbyper), &(nim->swapsize) );
6517    if( nim->nbyper == 0 ){ nifti_image_free(nim); return NULL; } /* bad! */
6518 
6519    nim->dim[0] = nim->ndim ;
6520    nim->dim[1] = nim->nx ; nim->pixdim[1] = nim->dx ;
6521    nim->dim[2] = nim->ny ; nim->pixdim[2] = nim->dy ;
6522    nim->dim[3] = nim->nz ; nim->pixdim[3] = nim->dz ;
6523    nim->dim[4] = nim->nt ; nim->pixdim[4] = nim->dt ;
6524    nim->dim[5] = nim->nu ; nim->pixdim[5] = nim->du ;
6525    nim->dim[6] = nim->nv ; nim->pixdim[6] = nim->dv ;
6526    nim->dim[7] = nim->nw ; nim->pixdim[7] = nim->dw ;
6527 
6528    nim->nvox = (size_t)nim->nx * nim->ny * nim->nz
6529                      * nim->nt * nim->nu * nim->nv * nim->nw ;
6530 
6531    if( nim->qform_code > 0 )
6532      nim->qto_xyz = nifti_quatern_to_mat44(
6533                       nim->quatern_b, nim->quatern_c, nim->quatern_d,
6534                       nim->qoffset_x, nim->qoffset_y, nim->qoffset_z,
6535                       nim->dx       , nim->dy       , nim->dz       ,
6536                       nim->qfac                                      ) ;
6537    else
6538      nim->qto_xyz = nifti_quatern_to_mat44(
6539                       0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 ,
6540                       nim->dx , nim->dy , nim->dz , 0.0 ) ;
6541 
6542 
6543    nim->qto_ijk = nifti_mat44_inverse( nim->qto_xyz ) ;
6544 
6545    if( nim->sform_code > 0 )
6546      nim->sto_ijk = nifti_mat44_inverse( nim->sto_xyz ) ;
6547 
6548    return nim ;
6549 }
6550 
6551 
6552 /*---------------------------------------------------------------------------*/
6553 /*! validate the nifti_image
6554 
6555     \return 1 if the structure seems valid, otherwise 0
6556 
6557     \sa nifti_nim_has_valid_dims, nifti_hdr_looks_good
6558 *//*-------------------------------------------------------------------------*/
nifti_nim_is_valid(nifti_image * nim,int complain)6559 int nifti_nim_is_valid(nifti_image * nim, int complain)
6560 {
6561    int errs = 0;
6562 
6563    if( !nim ){
6564       fprintf(stderr,"** is_valid_nim: nim is NULL\n");
6565       return 0;
6566    }
6567 
6568    if( g_opts.debug > 2 ) fprintf(stderr,"-d nim_is_valid check...\n");
6569 
6570    /**- check that dim[] matches the individual values ndim, nx, ny, ... */
6571    if( ! nifti_nim_has_valid_dims(nim,complain) ){
6572       if( !complain ) return 0;
6573       errs++;
6574    }
6575 
6576    /* might check nbyper, pixdim, q/sforms, swapsize, nifti_type, ... */
6577 
6578    /**- be explicit in return of 0 or 1 */
6579    if( errs > 0 ) return 0;
6580    else           return 1;
6581 }
6582 
6583 /*---------------------------------------------------------------------------*/
6584 /*! validate nifti dimensions
6585 
6586     \return 1 if valid, 0 if not
6587 
6588     \sa nifti_nim_is_valid, nifti_hdr_looks_good
6589 
6590     rely on dim[] as the master
6591 *//*-------------------------------------------------------------------------*/
nifti_nim_has_valid_dims(nifti_image * nim,int complain)6592 int nifti_nim_has_valid_dims(nifti_image * nim, int complain)
6593 {
6594    size_t prod;
6595    int    c, errs = 0;
6596 
6597    /**- start with dim[0]: failure here is considered terminal */
6598    if( nim->dim[0] <= 0 || nim->dim[0] > 7 ){
6599       errs++;
6600       if( complain )
6601          fprintf(stderr,"** NVd: dim[0] (%d) out of range [1,7]\n",nim->dim[0]);
6602       return 0;
6603    }
6604 
6605    /**- check whether ndim equals dim[0] */
6606    if( nim->ndim != nim->dim[0] ){
6607       errs++;
6608       if( ! complain ) return 0;
6609       fprintf(stderr,"** NVd: ndim != dim[0] (%d,%d)\n",nim->ndim,nim->dim[0]);
6610    }
6611 
6612    /**- compare each dim[i] to the proper nx, ny, ... */
6613    if( ( (nim->dim[0] >= 1) && (nim->dim[1] != nim->nx) ) ||
6614        ( (nim->dim[0] >= 2) && (nim->dim[2] != nim->ny) ) ||
6615        ( (nim->dim[0] >= 3) && (nim->dim[3] != nim->nz) ) ||
6616        ( (nim->dim[0] >= 4) && (nim->dim[4] != nim->nt) ) ||
6617        ( (nim->dim[0] >= 5) && (nim->dim[5] != nim->nu) ) ||
6618        ( (nim->dim[0] >= 6) && (nim->dim[6] != nim->nv) ) ||
6619        ( (nim->dim[0] >= 7) && (nim->dim[7] != nim->nw) )   ){
6620       errs++;
6621       if( !complain ) return 0;
6622       fprintf(stderr,"** NVd mismatch: dims    = %d,%d,%d,%d,%d,%d,%d\n"
6623                      "                 nxyz... = %d,%d,%d,%d,%d,%d,%d\n",
6624                      nim->dim[1], nim->dim[2], nim->dim[3],
6625                      nim->dim[4], nim->dim[5], nim->dim[6], nim->dim[7],
6626                      nim->nx, nim->ny, nim->nz,
6627                      nim->nt, nim->nu, nim->nv, nim->nw );
6628    }
6629 
6630    if( g_opts.debug > 2 ){
6631       fprintf(stderr,"-d check dim[%d] =", nim->dim[0]);
6632       for( c = 0; c < 7; c++ ) fprintf(stderr," %d", nim->dim[c]);
6633       fputc('\n', stderr);
6634    }
6635 
6636    /**- check the dimensions, and that their product matches nvox */
6637    prod = 1;
6638    for( c = 1; c <= nim->dim[0]; c++ ){
6639       if( nim->dim[c] > 0)
6640          prod *= nim->dim[c];
6641       else if( nim->dim[c] <= 0 ){
6642          if( !complain ) return 0;
6643          fprintf(stderr,"** NVd: dim[%d] (=%d) <= 0\n",c, nim->dim[c]);
6644          errs++;
6645       }
6646    }
6647    if( prod != nim->nvox ){
6648       if( ! complain ) return 0;
6649       fprintf(stderr,"** NVd: nvox does not match %d-dim product (%u, %u)\n",
6650               nim->dim[0], (unsigned)nim->nvox, (unsigned)prod);
6651       errs++;
6652    }
6653 
6654    /**- if debug, warn about any remaining dim that is neither 0, nor 1 */
6655    /*   (values in dims above dim[0] are undefined, as reminded by Cinly
6656          Ooi and Alle Meije Wink)                   16 Nov 2005 [rickr] */
6657    if( g_opts.debug > 1 )
6658       for( c = nim->dim[0]+1; c <= 7; c++ )
6659          if( nim->dim[c] != 0 && nim->dim[c] != 1 )
6660             fprintf(stderr,"** NVd warning: dim[%d] = %d, but ndim = %d\n",
6661                     c, nim->dim[c], nim->dim[0]);
6662 
6663    if( g_opts.debug > 2 )
6664       fprintf(stderr,"-d nim_has_valid_dims check, errs = %d\n", errs);
6665 
6666    /**- return invalid or valid */
6667    if( errs > 0 ) return 0;
6668    else           return 1;
6669 }
6670 
6671 
6672 /*---------------------------------------------------------------------------*/
6673 /*! read a nifti image, collapsed across dimensions according to dims[8]  <pre>
6674 
6675     This function may be used to read parts of a nifti dataset, such as
6676     the time series for a single voxel, or perhaps a slice.  It is similar
6677     to nifti_image_load(), though the passed 'data' parameter is used for
6678     returning the image, not nim->data.
6679 
6680     \param nim  given nifti_image struct, corresponding to the data file
6681     \param dims given list of dimensions (see below)
6682     \param data pointer to data pointer (if *data is NULL, data will be
6683                 allocated, otherwise not)
6684 
6685     Here, dims is an array of 8 ints, similar to nim->dim[8].  While dims[0]
6686     is unused at this point, the other indices specify which dimensions to
6687     collapse (and at which index), and which not to collapse.  If dims[i] is
6688     set to -1, then that entire dimension will be read in, from index 0 to
6689     index (nim->dim[i] - 1).  If dims[i] >= 0, then only that index will be
6690     read in (so dims[i] must also be < nim->dim[i]).
6691 
6692     Example: given  nim->dim[8] = { 4, 64, 64, 21, 80, 1, 1, 1 } (4-D dataset)
6693 
6694       if dims[8] = { 0,  5,  4, 17, -1, -1, -1, -1 }
6695          -> read time series for voxel i,j,k = 5,4,17
6696 
6697       if dims[8] = { 0, -1, -1, -1, 17, -1, -1, -1 }
6698          -> read single volume at time point 17
6699 
6700     Example: given  nim->dim[8] = { 6, 64, 64, 21, 80, 4, 3, 1 } (6-D dataset)
6701 
6702       if dims[8] = { 0, 5, 4, 17, -1, 2, 1, 0 }
6703          -> read time series for the voxel i,j,k = 5,4,17, and dim 5,6 = 2,1
6704 
6705       if dims[8] = { 0, 5, 4, -1, -1, 0, 0, 0 }
6706          -> read time series for slice at i,j = 5,4, and dim 5,6,7 = 0,0,0
6707             (note that dims[7] is not relevant, but must be 0 or -1)
6708 
6709     If *data is NULL, then *data will be set as a pointer to new memory,
6710     allocated here for the resulting collapsed image data.
6711 
6712       e.g. { int    dims[8] = { 0,  5,  4, 17, -1, -1, -1, -1 };
6713              void * data    = NULL;
6714              ret_val = nifti_read_collapsed_image(nim, dims, &data);
6715              if( ret_val > 0 ){
6716                 process_time_series(data);
6717                 if( data != NULL ) free(data);
6718              }
6719            }
6720 
6721     NOTE: If *data is not NULL, then it will be assumed that it points to
6722           valid memory, sufficient to hold the results.  This is done for
6723           speed and possibly repeated calls to this function.
6724 
6725       e.g. { int    dims[8] = { 0,  -1, -1, -1, -1, -1, -1, -1 };
6726              void * data    = NULL;
6727              for( zslice = 0; zslice < nzslices; zslice++ ){
6728                 dims[3] = zslice;
6729                 ret_val = nifti_read_collapsed_image(nim, dims, &data);
6730                 if( ret_val > 0 ) process_slice(zslice, data);
6731              }
6732              if( data != NULL ) free(data);
6733            }
6734 
6735     \return
6736         -  the total number of bytes read, or < 0 on failure
6737         -  the read and byte-swapped data, in 'data'            </pre>
6738 
6739     \sa nifti_image_read, nifti_image_free, nifti_image_read_bricks
6740         nifti_image_load
6741 *//*-------------------------------------------------------------------------*/
nifti_read_collapsed_image(nifti_image * nim,const int dims[8],void ** data)6742 int nifti_read_collapsed_image( nifti_image * nim, const int dims [8],
6743                                 void ** data )
6744 {
6745    znzFile fp;
6746    int     pivots[8], prods[8], nprods; /* sizes are bounded by dims[], so 8 */
6747    int     c, bytes;
6748 
6749    /** - check pointers for sanity */
6750    if( !nim || !dims || !data ){
6751       fprintf(stderr,"** nifti_RCI: bad params %p, %p, %p\n",
6752               (void *)nim, (void *)dims, (void *)data);
6753       return -1;
6754    }
6755 
6756    if( g_opts.debug > 2 ){
6757       fprintf(stderr,"-d read_collapsed_image:\n        dims =");
6758       for(c = 0; c < 8; c++) fprintf(stderr," %3d", dims[c]);
6759       fprintf(stderr,"\n   nim->dims =");
6760       for(c = 0; c < 8; c++) fprintf(stderr," %3d", nim->dim[c]);
6761       fputc('\n', stderr);
6762    }
6763 
6764    /** - verify that dim[] makes sense */
6765    if( ! nifti_nim_is_valid(nim, g_opts.debug > 0) ){
6766       fprintf(stderr,"** invalid nim (file is '%s')\n", nim->fname );
6767       return -1;
6768    }
6769 
6770    /** - verify that dims[] makes sense for this dataset */
6771    for( c = 1; c <= nim->dim[0]; c++ ){
6772       if( dims[c] >= nim->dim[c] ){
6773          fprintf(stderr,"** nifti_RCI: dims[%d] >= nim->dim[%d] (%d,%d)\n",
6774                  c, c, dims[c], nim->dim[c]);
6775          return -1;
6776       }
6777    }
6778 
6779    /** - prepare pivot list - pivots are fixed indices */
6780    if( make_pivot_list(nim, dims, pivots, prods, &nprods) < 0 ) return -1;
6781 
6782    bytes = rci_alloc_mem(data, prods, nprods, nim->nbyper);
6783    if( bytes < 0 ) return -1;
6784 
6785    /** - open the image file for reading at the appropriate offset */
6786    fp = nifti_image_load_prep( nim );
6787    if( ! fp ){ free(*data);  *data = NULL;  return -1; }     /* failure */
6788 
6789    /** - call the recursive reading function, passing nim, the pivot info,
6790          location to store memory, and file pointer and position */
6791    c = rci_read_data(nim, pivots,prods,nprods,dims,
6792                      (char *)*data, fp, znztell(fp));
6793    znzclose(fp);   /* in any case, close the file */
6794    if( c < 0 ){ free(*data);  *data = NULL;  return -1; }    /* failure */
6795 
6796    if( g_opts.debug > 1 )
6797       fprintf(stderr,"+d read %d bytes of collapsed image from %s\n",
6798               bytes, nim->fname);
6799 
6800    return bytes;
6801 }
6802 
6803 
6804 /* local function to find strides per dimension. assumes 7D size and
6805 ** stride array.
6806 */
6807 static void
compute_strides(int * strides,const int * size,int nbyper)6808 compute_strides(int *strides,const int *size,int nbyper)
6809 {
6810   int i;
6811   strides[0] = nbyper;
6812   for(i = 1; i < 7; i++)
6813     {
6814     strides[i] = size[i-1] * strides[i-1];
6815     }
6816 }
6817 
6818 /*---------------------------------------------------------------------------*/
6819 /*! read an arbitrary subregion from a nifti image
6820 
6821     This function may be used to read a single arbitary subregion of any
6822     rectangular size from a nifti dataset, such as a small 5x5x5 subregion
6823     around the center of a 3D image.
6824 
6825     \param nim  given nifti_image struct, corresponding to the data file
6826     \param start_index the index location of the first voxel that will be returned
6827     \param region_size the size of the subregion to be returned
6828     \param data pointer to data pointer (if *data is NULL, data will be
6829                 allocated, otherwise not)
6830 
6831     Example: given  nim->dim[8] = {3, 64, 64, 64, 1, 1, 1, 1 } (3-D dataset)
6832 
6833       if start_index[7] = { 29,  29, 29, 0, 0, 0, 0 } and
6834          region_size[7] = {  5,   5,  5, 1, 1, 1, 1 }
6835          -> read 5x5x5 region starting with the first voxel location at (29,29,29)
6836 
6837     NOTE: If *data is not NULL, then it will be assumed that it points to
6838           valid memory, sufficient to hold the results.  This is done for
6839           speed and possibly repeated calls to this function.
6840     \return
6841         -  the total number of bytes read, or < 0 on failure
6842         -  the read and byte-swapped data, in 'data'            </pre>
6843 
6844     \sa nifti_image_read, nifti_image_free, nifti_image_read_bricks
6845         nifti_image_load, nifti_read_collapsed_image
6846 *//*-------------------------------------------------------------------------*/
nifti_read_subregion_image(nifti_image * nim,int * start_index,int * region_size,void ** data)6847 int nifti_read_subregion_image( nifti_image * nim,
6848                                 int *start_index,
6849                                 int *region_size,
6850                                 void ** data )
6851 {
6852   znzFile fp;                   /* file to read */
6853   int i,j,k,l,m,n;              /* indices for dims */
6854   long int bytes = 0;           /* total # bytes read */
6855   int total_alloc_size;         /* size of buffer allocation */
6856   char *readptr;                /* where in *data to read next */
6857   int strides[7];               /* strides between dimensions */
6858   int collapsed_dims[8];        /* for read_collapsed_image */
6859   int *image_size;              /* pointer to dimensions in header */
6860   long int initial_offset;
6861   long int offset;              /* seek offset for reading current row */
6862 
6863   /* probably ignored, but set to ndim for consistency*/
6864   collapsed_dims[0] = nim->ndim;
6865 
6866   /* build a dims array for collapsed image read */
6867   for(i = 0; i < nim->ndim; i++)
6868     {
6869     /* if you take the whole extent in this dimension */
6870     if(start_index[i] == 0 &&
6871        region_size[i] == nim->dim[i+1])
6872       {
6873       collapsed_dims[i+1] = -1;
6874       }
6875     /* if you specify a single element in this dimension */
6876     else if(region_size[i] == 1)
6877       {
6878       collapsed_dims[i+1] = start_index[i];
6879       }
6880     else
6881       {
6882       collapsed_dims[i+1] = -2; /* sentinel value */
6883       }
6884     }
6885   /* fill out end of collapsed_dims */
6886   for(i = nim->ndim ; i < 7; i++)
6887     {
6888     collapsed_dims[i+1] = -1;
6889     }
6890 
6891   /* check to see whether collapsed read is possible */
6892   for(i = 1; i <= nim->ndim; i++)
6893     {
6894     if(collapsed_dims[i] == -2)
6895       {
6896       break;
6897       }
6898     }
6899 
6900   /* if you get through all the dimensions without hitting
6901   ** a subrange of size > 1, a collapsed read is possible
6902   */
6903   if(i > nim->ndim)
6904     {
6905     return nifti_read_collapsed_image(nim, collapsed_dims, data);
6906     }
6907 
6908   /* point past first element of dim, which holds nim->ndim */
6909   image_size = &(nim->dim[1]);
6910 
6911   /* check region sizes for sanity */
6912   for(i = 0; i < nim->ndim; i++)
6913     {
6914     if(start_index[i]  + region_size[i] > image_size[i])
6915       {
6916       if(g_opts.debug > 1)
6917         {
6918         fprintf(stderr,"region doesn't fit within image size\n");
6919         }
6920       return -1;
6921       }
6922     }
6923 
6924   /* get the file open */
6925   fp = nifti_image_load_prep( nim );
6926   /* the current offset is just past the nifti header, save
6927    * location so that SEEK_SET can be used below
6928    */
6929   initial_offset = znztell(fp);
6930   /* get strides*/
6931   compute_strides(strides,image_size,nim->nbyper);
6932 
6933   total_alloc_size = nim->nbyper; /* size of pixel */
6934 
6935   /* find alloc size */
6936   for(i = 0; i < nim->ndim; i++)
6937     {
6938     total_alloc_size *= region_size[i];
6939     }
6940   /* allocate buffer, if necessary */
6941   if(*data == 0)
6942     {
6943     *data = (void *)malloc(total_alloc_size);
6944     }
6945 
6946   if(*data == 0)
6947     {
6948     if(g_opts.debug > 1)
6949       {
6950       fprintf(stderr,"allocation of %d bytes failed\n",total_alloc_size);
6951       return -1;
6952       }
6953     }
6954 
6955   /* point to start of data buffer as char * */
6956   readptr = *((char **)data);
6957   {
6958   /* can't assume that start_index and region_size have any more than
6959   ** nim->ndim elements so make local copies, filled out to seven elements
6960   */
6961   int si[7], rs[7];
6962   for(i = 0; i < nim->ndim; i++)
6963     {
6964     si[i] = start_index[i];
6965     rs[i] = region_size[i];
6966     }
6967   for(i = nim->ndim; i < 7; i++)
6968     {
6969     si[i] = 0;
6970     rs[i] = 1;
6971     }
6972   /* loop through subregion and read a row at a time */
6973   for(i = si[6]; i < (si[6] + rs[6]); i++)
6974     {
6975     for(j = si[5]; j < (si[5] + rs[5]); j++)
6976       {
6977       for(k = si[4]; k < (si[4] + rs[4]); k++)
6978         {
6979         for(l = si[3]; l < (si[3] + rs[3]); l++)
6980           {
6981           for(m = si[2]; m < (si[2] + rs[2]); m++)
6982             {
6983             for(n = si[1]; n < (si[1] + rs[1]); n++)
6984               {
6985               int nread,read_amount;
6986               offset = initial_offset +
6987                 (i * strides[6]) +
6988                 (j * strides[5]) +
6989                 (k * strides[4]) +
6990                 (l * strides[3]) +
6991                 (m * strides[2]) +
6992                 (n * strides[1]) +
6993                 (si[0] * strides[0]);
6994               znzseek(fp, offset, SEEK_SET); /* seek to current row */
6995               read_amount = rs[0] * nim->nbyper; /* read a row of the subregion*/
6996               nread = (int)nifti_read_buffer(fp, readptr, read_amount, nim);
6997               if(nread != read_amount)
6998                 {
6999                 if(g_opts.debug > 1)
7000                   {
7001                   fprintf(stderr,"read of %d bytes failed\n",read_amount);
7002                   return -1;
7003                   }
7004                 }
7005               bytes += nread;
7006               readptr += read_amount;
7007               }
7008             }
7009           }
7010         }
7011       }
7012     }
7013   }
7014   return bytes;
7015 }
7016 
7017 
7018 /* read the data from the file pointed to by fp
7019 
7020    - this a recursive function, so start with the base case
7021    - data is now (char *) for easy incrementing
7022 
7023    return 0 on success, < 0 on failure
7024 */
rci_read_data(nifti_image * nim,int * pivots,int * prods,int nprods,const int dims[],char * data,znzFile fp,size_t base_offset)7025 static int rci_read_data(nifti_image * nim, int * pivots, int * prods,
7026       int nprods, const int dims[], char * data, znzFile fp, size_t base_offset)
7027 {
7028    size_t sublen, offset, read_size;
7029    int    c;
7030 
7031    /* bad check first - base_offset may not have been checked */
7032    if( nprods <= 0 ){
7033       fprintf(stderr,"** rci_read_data, bad prods, %d\n", nprods);
7034       return -1;
7035    }
7036 
7037    /* base case: actually read the data */
7038    if( nprods == 1 ){
7039       size_t nread, bytes;
7040 
7041       /* make sure things look good here */
7042       if( *pivots != 0 ){
7043          fprintf(stderr,"** rciRD: final pivot == %d!\n", *pivots);
7044          return -1;
7045       }
7046 
7047       /* so just seek and read (prods[0] * nbyper) bytes from the file */
7048       znzseek(fp, (long)base_offset, SEEK_SET);
7049       bytes = (size_t)prods[0] * nim->nbyper;
7050       nread = nifti_read_buffer(fp, data, bytes, nim);
7051       if( nread != bytes ){
7052          fprintf(stderr,"** rciRD: read only %u of %u bytes from '%s'\n",
7053                  (unsigned)nread, (unsigned)bytes, nim->fname);
7054          return -1;
7055       } else if( g_opts.debug > 3 )
7056          fprintf(stderr,"+d successful read of %u bytes at offset %u\n",
7057                  (unsigned)bytes, (unsigned)base_offset);
7058 
7059       return 0;  /* done with base case - return success */
7060    }
7061 
7062    /* not the base case, so do a set of reduced reads */
7063 
7064    /* compute size of sub-brick: all dimensions below pivot */
7065    for( c = 1, sublen = 1; c < *pivots; c++ ) sublen *= nim->dim[c];
7066 
7067    /* compute number of values to read, i.e. remaining prods */
7068    for( c = 1, read_size = 1; c < nprods; c++ ) read_size *= prods[c];
7069    read_size *= nim->nbyper;  /* and multiply by bytes per voxel */
7070 
7071    /* now repeatedly compute offsets, and recursively read */
7072    for( c = 0; c < prods[0]; c++ ){
7073       /* offset is (c * sub-block size (including pivot dim))   */
7074       /*         + (dims[] index into pivot sub-block)          */
7075       /* the unneeded multiplication is to make this more clear */
7076       offset = (size_t)c * sublen * nim->dim[*pivots] +
7077                (size_t)sublen * dims[*pivots];
7078       offset *= nim->nbyper;
7079 
7080       if( g_opts.debug > 3 )
7081          fprintf(stderr,"-d reading %u bytes, foff %u + %u, doff %u\n",
7082                  (unsigned)read_size, (unsigned)base_offset, (unsigned)offset,
7083                  (unsigned)(c*read_size));
7084 
7085       /* now read the next level down, adding this offset */
7086       if( rci_read_data(nim, pivots+1, prods+1, nprods-1, dims,
7087                     data + c * read_size, fp, base_offset + offset) < 0 )
7088          return -1;
7089    }
7090 
7091    return 0;
7092 }
7093 
7094 
7095 /* allocate memory for all collapsed image data
7096 
7097    If *data is already set, do not allocate, but still calculate
7098    size for debug report.
7099 
7100    return total size on success, and < 0 on failure
7101 */
rci_alloc_mem(void ** data,int prods[8],int nprods,int nbyper)7102 static int rci_alloc_mem(void ** data, int prods[8], int nprods, int nbyper )
7103 {
7104    int size, index;
7105 
7106    if( nbyper < 0 || nprods < 1 || nprods > 8 ){
7107       fprintf(stderr,"** rci_am: bad params, %d, %d\n", nbyper, nprods);
7108       return -1;
7109    }
7110 
7111    for( index = 0, size = 1; index < nprods; index++ )
7112        size *= prods[index];
7113 
7114    size *= nbyper;
7115 
7116    if( ! *data ){   /* then allocate what is needed */
7117       if( g_opts.debug > 1 )
7118          fprintf(stderr,"+d alloc %d (= %d x %d) bytes for collapsed image\n",
7119                  size, size/nbyper, nbyper);
7120 
7121       *data = malloc(size);   /* actually allocate the memory */
7122       if( ! *data ){
7123          fprintf(stderr,"** rci_am: failed to alloc %d bytes for data\n", size);
7124          return -1;
7125       }
7126    } else if( g_opts.debug > 1 )
7127       fprintf(stderr,"-d rci_am: *data already set, need %d (%d x %d) bytes\n",
7128               size, size/nbyper, nbyper);
7129 
7130    return size;
7131 }
7132 
7133 
7134 /* prepare a pivot list for reading
7135 
7136    The pivot points are the indices into dims where the calling function
7137    wants to collapse a dimension.  The last pivot should always be zero
7138    (note that we have space for that in the lists).
7139 */
make_pivot_list(nifti_image * nim,const int dims[],int pivots[],int prods[],int * nprods)7140 static int make_pivot_list(nifti_image * nim, const int dims[], int pivots[],
7141                                               int prods[], int * nprods )
7142 {
7143    int len, index;
7144 
7145    len = 0;
7146    index = nim->dim[0];
7147    while( index > 0 ){
7148       prods[len] = 1;
7149       while( index > 0 && (nim->dim[index] == 1 || dims[index] == -1) ){
7150          prods[len] *= nim->dim[index];
7151          index--;
7152       }
7153       pivots[len] = index;
7154       len++;
7155       index--;  /* fine, let it drop out at -1 */
7156    }
7157 
7158    /* make sure to include 0 as a pivot (instead of just 1, if it is) */
7159    if( pivots[len-1] != 0 ){
7160       pivots[len] = 0;
7161       prods[len] = 1;
7162       len++;
7163    }
7164 
7165    *nprods = len;
7166 
7167    if( g_opts.debug > 2 ){
7168       fprintf(stderr,"+d pivot list created, pivots :");
7169       for(index = 0; index < len; index++) fprintf(stderr," %d", pivots[index]);
7170       fprintf(stderr,", prods :");
7171       for(index = 0; index < len; index++) fprintf(stderr," %d", prods[index]);
7172       fputc('\n',stderr);
7173    }
7174 
7175    return 0;
7176 }
7177 
7178 
7179 #undef ISEND
7180 #define ISEND(c) ( (c)==']' || (c)=='}' || (c)=='\0' )
7181 
7182 /*---------------------------------------------------------------------*/
7183 /*! Get an integer list in the range 0..(nvals-1), from the
7184    character string str.  If we call the output pointer fred,
7185    then fred[0] = number of integers in the list (> 0), and
7186         fred[i] = i-th integer in the list for i=1..fred[0].
7187    If on return, fred == NULL or fred[0] == 0, then something is
7188    wrong, and the caller must deal with that.
7189 
7190    Syntax of input string:
7191      - initial '{' or '[' is skipped, if present
7192      - ends when '}' or ']' or end of string is found
7193      - contains entries separated by commas
7194      - entries have one of these forms:
7195        - a single number
7196        - a dollar sign '$', which means nvals-1
7197        - a sequence of consecutive numbers in the form "a..b" or
7198          "a-b", where "a" and "b" are single numbers (or '$')
7199        - a sequence of evenly spaced numbers in the form
7200          "a..b(c)" or "a-b(c)", where "c" encodes the step
7201      - Example:  "[2,7..4,3..9(2)]" decodes to the list
7202          2 7 6 5 4 3 5 7 9
7203      - entries should be in the range 0..nvals-1
7204 
7205    (borrowed, with permission, from thd_intlist.c)
7206 *//*-------------------------------------------------------------------*/
nifti_get_intlist(int nvals,const char * str)7207 int * nifti_get_intlist( int nvals , const char * str )
7208 {
7209    int *subv = NULL ;
7210    int ii , ipos , nout , slen ;
7211    int ibot,itop,istep , nused ;
7212    char *cpt ;
7213 
7214    /* Meaningless input? */
7215    if( nvals < 1 ) return NULL ;
7216 
7217    /* No selection list? */
7218    if( str == NULL || str[0] == '\0' ) return NULL ;
7219 
7220    /* skip initial '[' or '{' */
7221    subv = (int *)malloc( sizeof(int) * 2 ) ;
7222    if( !subv ) {
7223       fprintf(stderr,"** nifti_get_intlist: failed alloc of 2 ints\n");
7224       return NULL;
7225    }
7226    subv[0] = nout = 0 ;
7227 
7228    ipos = 0 ;
7229    if( str[ipos] == '[' || str[ipos] == '{' ) ipos++ ;
7230 
7231    if( g_opts.debug > 1 )
7232       fprintf(stderr,"-d making int_list (vals = %d) from '%s'\n", nvals, str);
7233 
7234    /**- for each sub-selector until end of input... */
7235 
7236    slen = (int)strlen(str) ;
7237    while( ipos < slen && !ISEND(str[ipos]) ){
7238 
7239      while( isspace((int) str[ipos]) ) ipos++ ;   /* skip blanks */
7240       if( ISEND(str[ipos]) ) break ;         /* done */
7241 
7242       /**- get starting value */
7243 
7244       if( str[ipos] == '$' ){  /* special case */
7245          ibot = nvals-1 ; ipos++ ;
7246       } else {                 /* decode an integer */
7247          ibot = strtol( str+ipos , &cpt , 10 ) ;
7248          if( ibot < 0 ){
7249            fprintf(stderr,"** ERROR: list index %d is out of range 0..%d\n",
7250                    ibot,nvals-1) ;
7251            free(subv) ; return NULL ;
7252          }
7253          if( ibot >= nvals ){
7254            fprintf(stderr,"** ERROR: list index %d is out of range 0..%d\n",
7255                    ibot,nvals-1) ;
7256            free(subv) ; return NULL ;
7257          }
7258          nused = (cpt-(str+ipos)) ;
7259          if( ibot == 0 && nused == 0 ){
7260            fprintf(stderr,"** ERROR: list syntax error '%s'\n",str+ipos) ;
7261            free(subv) ; return NULL ;
7262          }
7263          ipos += nused ;
7264       }
7265 
7266       while( isspace((int) str[ipos]) ) ipos++ ;   /* skip blanks */
7267 
7268       /**- if that's it for this sub-selector, add one value to list */
7269 
7270       if( str[ipos] == ',' || ISEND(str[ipos]) ){
7271          nout++ ;
7272          subv = (int *)realloc( (char *)subv , sizeof(int) * (nout+1) ) ;
7273          if( !subv ) {
7274             fprintf(stderr,"** nifti_get_intlist: failed realloc of %d ints\n",
7275                     nout+1);
7276             return NULL;
7277          }
7278          subv[0]    = nout ;
7279          subv[nout] = ibot ;
7280          if( ISEND(str[ipos]) ) break ; /* done */
7281          ipos++ ; continue ;            /* re-start loop at next sub-selector */
7282       }
7283 
7284       /**- otherwise, must have '..' or '-' as next inputs */
7285 
7286       if( str[ipos] == '-' ){
7287          ipos++ ;
7288       } else if( str[ipos] == '.' && str[ipos+1] == '.' ){
7289          ipos++ ; ipos++ ;
7290       } else {
7291          fprintf(stderr,"** ERROR: index list syntax is bad: '%s'\n",
7292                  str+ipos) ;
7293          free(subv) ; return NULL ;
7294       }
7295 
7296       /**- get ending value for loop now */
7297 
7298       if( str[ipos] == '$' ){  /* special case */
7299          itop = nvals-1 ; ipos++ ;
7300       } else {                 /* decode an integer */
7301          itop = strtol( str+ipos , &cpt , 10 ) ;
7302          if( itop < 0 ){
7303            fprintf(stderr,"** ERROR: index %d is out of range 0..%d\n",
7304                    itop,nvals-1) ;
7305            free(subv) ; return NULL ;
7306          }
7307          if( itop >= nvals ){
7308            fprintf(stderr,"** ERROR: index %d is out of range 0..%d\n",
7309                    itop,nvals-1) ;
7310            free(subv) ; return NULL ;
7311          }
7312          nused = (cpt-(str+ipos)) ;
7313          if( itop == 0 && nused == 0 ){
7314            fprintf(stderr,"** ERROR: index list syntax error '%s'\n",str+ipos) ;
7315            free(subv) ; return NULL ;
7316          }
7317          ipos += nused ;
7318       }
7319 
7320       /**- set default loop step */
7321 
7322       istep = (ibot <= itop) ? 1 : -1 ;
7323 
7324       while( isspace((int) str[ipos]) ) ipos++ ;            /* skip blanks */
7325 
7326       /**- check if we have a non-default loop step */
7327 
7328       if( str[ipos] == '(' ){  /* decode an integer */
7329          ipos++ ;
7330          istep = strtol( str+ipos , &cpt , 10 ) ;
7331          if( istep == 0 ){
7332            fprintf(stderr,"** ERROR: index loop step is 0!\n") ;
7333            free(subv) ; return NULL ;
7334          }
7335          nused = (cpt-(str+ipos)) ;
7336          ipos += nused ;
7337          if( str[ipos] == ')' ) ipos++ ;
7338          if( (ibot-itop)*istep > 0 ){
7339            fprintf(stderr,"** WARNING: index list '%d..%d(%d)' means nothing\n",
7340                    ibot,itop,istep ) ;
7341          }
7342       }
7343 
7344       /**- add values to output */
7345 
7346       for( ii=ibot ; (ii-itop)*istep <= 0 ; ii += istep ){
7347          nout++ ;
7348          subv = (int *)realloc( (char *)subv , sizeof(int) * (nout+1) ) ;
7349          if( !subv ) {
7350             fprintf(stderr,"** nifti_get_intlist: failed realloc of %d ints\n",
7351                     nout+1);
7352             return NULL;
7353          }
7354          subv[0]    = nout ;
7355          subv[nout] = ii ;
7356       }
7357 
7358       /**- check if we have a comma to skip over */
7359 
7360       while( isspace((int) str[ipos]) ) ipos++ ;            /* skip blanks */
7361       if( str[ipos] == ',' ) ipos++ ;                       /* skip commas */
7362 
7363    }  /* end of loop through selector string */
7364 
7365    if( g_opts.debug > 1 ) {
7366       fprintf(stderr,"+d int_list (vals = %d): ", subv[0]);
7367       for( ii = 1; ii <= subv[0]; ii++ ) fprintf(stderr,"%d ", subv[ii]);
7368       fputc('\n',stderr);
7369    }
7370 
7371    if( subv[0] == 0 ){ free(subv); subv = NULL; }
7372    return subv ;
7373 }
7374 
7375 /*---------------------------------------------------------------------*/
7376 /*! Given a NIFTI_TYPE string, such as "NIFTI_TYPE_INT16", return the
7377  *  corresponding integral type code.  The type code is the macro
7378  *  value defined in nifti1.h.
7379 *//*-------------------------------------------------------------------*/
nifti_datatype_from_string(const char * name)7380 int nifti_datatype_from_string( const char * name )
7381 {
7382     int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele);
7383     int c;
7384 
7385     if( !name ) return DT_UNKNOWN;
7386 
7387     for( c = tablen-1; c > 0; c-- )
7388         if( !strcmp(name, nifti_type_list[c].name) )
7389             break;
7390 
7391     return nifti_type_list[c].type;
7392 }
7393 
7394 
7395 /*---------------------------------------------------------------------*/
7396 /*! Given a NIFTI_TYPE value, such as NIFTI_TYPE_INT16, return the
7397  *  corresponding macro label as a string.  The dtype code is the
7398  *  macro value defined in nifti1.h.
7399 *//*-------------------------------------------------------------------*/
nifti_datatype_to_string(int dtype)7400 char * nifti_datatype_to_string( int dtype )
7401 {
7402     int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele);
7403     int c;
7404 
7405     for( c = tablen-1; c > 0; c-- )
7406         if( nifti_type_list[c].type == dtype )
7407             break;
7408 
7409     return nifti_type_list[c].name;
7410 }
7411 
7412 
7413 /*---------------------------------------------------------------------*/
7414 /*! Determine whether dtype is a valid NIFTI_TYPE.
7415  *
7416  *  DT_UNKNOWN is considered invalid
7417  *
7418  *  The only difference 'for_nifti' makes is that DT_BINARY
7419  *  should be invalid for a NIfTI dataset.
7420 *//*-------------------------------------------------------------------*/
nifti_datatype_is_valid(int dtype,int for_nifti)7421 int nifti_datatype_is_valid( int dtype, int for_nifti )
7422 {
7423     int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele);
7424     int c;
7425 
7426     /* special case */
7427     if( for_nifti && dtype == DT_BINARY ) return 0;
7428 
7429     for( c = tablen-1; c > 0; c-- )
7430         if( nifti_type_list[c].type == dtype )
7431             return 1;
7432 
7433     return 0;
7434 }
7435 
7436 
7437 /*---------------------------------------------------------------------*/
7438 /*! Only as a test, verify that the new nifti_type_list table matches
7439  *  the the usage of nifti_datatype_sizes (which could be changed to
7440  *  use the table, if there were interest).
7441  *
7442  *  return the number of errors (so 0 is success, as usual)
7443 *//*-------------------------------------------------------------------*/
nifti_test_datatype_sizes(int verb)7444 int nifti_test_datatype_sizes(int verb)
7445 {
7446     int tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele);
7447     int nbyper, ssize;
7448     int c, errs = 0;
7449 
7450     for( c = 0; c < tablen; c++ )
7451     {
7452         nbyper = ssize = -1;
7453         nifti_datatype_sizes(nifti_type_list[c].type, &nbyper, &ssize);
7454         if( nbyper < 0 || ssize < 0 ||
7455                 nbyper != nifti_type_list[c].nbyper ||
7456                 ssize != nifti_type_list[c].swapsize )
7457         {
7458             if( verb || g_opts.debug > 2 )
7459                 fprintf(stderr, "** type mismatch: %s, %d, %d, %d : %d, %d\n",
7460                     nifti_type_list[c].name, nifti_type_list[c].type,
7461                     nifti_type_list[c].nbyper, nifti_type_list[c].swapsize,
7462                     nbyper, ssize);
7463             errs++;
7464         }
7465     }
7466 
7467     if( errs )
7468         fprintf(stderr,"** nifti_test_datatype_sizes: found %d errors\n",errs);
7469     else if( verb || g_opts.debug > 1 )
7470         fprintf(stderr,"-- nifti_test_datatype_sizes: all OK\n");
7471 
7472     return errs;
7473 }
7474 
7475 
7476 /*---------------------------------------------------------------------*/
7477 /*! Display the nifti_type_list table.
7478  *
7479  *  if which == 1  : display DT_*
7480  *  if which == 2  : display NIFTI_TYPE*
7481  *  else           : display all
7482 *//*-------------------------------------------------------------------*/
nifti_disp_type_list(int which)7483 int nifti_disp_type_list( int which )
7484 {
7485     char * style;
7486     int    tablen = sizeof(nifti_type_list)/sizeof(nifti_type_ele);
7487     int    lwhich, c;
7488 
7489     if     ( which == 1 ){ lwhich = 1; style = "DT_"; }
7490     else if( which == 2 ){ lwhich = 2; style = "NIFTI_TYPE_"; }
7491     else                 { lwhich = 3; style = "ALL"; }
7492 
7493     printf("nifti_type_list entries (%s) :\n"
7494            "  name                    type    nbyper    swapsize\n"
7495            "  ---------------------   ----    ------    --------\n", style);
7496 
7497     for( c = 0; c < tablen; c++ )
7498         if( (lwhich & 1 && nifti_type_list[c].name[0] == 'D')  ||
7499             (lwhich & 2 && nifti_type_list[c].name[0] == 'N')     )
7500             printf("  %-22s %5d     %3d      %5d\n",
7501                    nifti_type_list[c].name,
7502                    nifti_type_list[c].type,
7503                    nifti_type_list[c].nbyper,
7504                    nifti_type_list[c].swapsize);
7505 
7506     return 0;
7507 }
7508 
7509 
7510