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