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