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