File: readZimage.cxx

package info (click to toggle)
imview 1.1.8-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,052 kB
  • ctags: 3,797
  • sloc: cpp: 29,842; sh: 2,620; ansic: 1,835; makefile: 756; exp: 112; python: 88
file content (990 lines) | stat: -rw-r--r-- 27,065 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
/*
 * $Id: readZimage.cxx,v 4.1 2004/05/25 06:40:20 hut66au Exp $
 *
 * Imview, the portable image analysis application
 * http://www.cmis.csiro.au/Hugues.Talbot/imview
 * ----------------------------------------------------------
 *
 *  Imview is an attempt to provide an image display application
 *  suitable for professional image analysis. It was started in
 *  1997 and is mostly the result of the efforts of Hugues Talbot,
 *  Image Analysis Project, CSIRO Mathematical and Information
 *  Sciences, with help from others (see the CREDITS files for
 *  more information)
 *
 *  Imview is Copyrighted (C) 1997-2001 by Hugues Talbot and was
 *  supported in parts by the Australian Commonwealth Science and 
 *  Industry Research Organisation. Please see the COPYRIGHT file 
 *  for full details. Imview also includes the contributions of 
 *  many others. Please see the CREDITS file for full details.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 * */

/*------------------------------------------------------------------------
 *
 * Z-image reader.
 *
 * Based on the Z-image reader for XV by the same author
 *
 * Hugues Talbot	14 Jan 1998
 *      
 *-----------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include "imview.hxx"
#include "imSystem.hxx"
#include "../imageIO.hxx"
#include "readZimage.hxx"
#include "../machine.hxx"

extern imageIO *IOBlackBox;



/* prototypes for static functions */
static void *readCHARZimage(FILE *fp, int nx, int ny, int nz);
static void *readINTZimage(FILE *fp, int nx, int ny, int nz, endianness e);
static void *readDOUBLEZimage(FILE *fp, int nx, int ny, int nz, endianness e);
static int needswapint(int *buf, long buflen);
static int swapint(int i);
static int needswapdouble(double *buf, long buflen);
static double swapdouble(double i);

// the `arithmetic exception' signal handler
static void arithExceptHandler(int sig);
// portable longjump buffer
im_jmp_buf AEenv;

int readZImage(const char *fname,
		int imageindex)
{
    int     res, start[3], end[3];
    int     thepixtype, theimgtype, spp, nbcomp;
    void   *buffp;
    
    // call the low-level Z-IMAGE reader
    res = load_zimage(fname, imageindex, start, end,
		      &thepixtype, &theimgtype, &spp, &nbcomp,
		      &buffp);

    if (res == 0) { // all went well
	// the new buffer needs to be set first before
	// the dimensions are changed because the previous buffer
	// might be freed, and we will need its dimensions.
	IOBlackBox->setCurrBuffp((void **)buffp);
	IOBlackBox->setCurrImgWidth(end[0]-start[0]+1);
	IOBlackBox->setCurrImgHeight(end[1]-start[1]+1);
	IOBlackBox->setCurrImgThickness(end[2]-start[2]+1);
	IOBlackBox->setXOffset(start[0]);
	IOBlackBox->setYOffset(start[1]);
	IOBlackBox->setZOffset(start[2]);
	IOBlackBox->setCurrZPos(0); // first plane
	IOBlackBox->setCurrImgType((imgtype)theimgtype);
	IOBlackBox->setCurrPixType((pixtype)thepixtype);
	IOBlackBox->setCurrImgNbComps(nbcomp); // Z-IMAGE supports multiple independent images in a single file
	IOBlackBox->setCurrImgNbSamples(spp);
	IOBlackBox->setImgDesc("Z-IMAGE");
    }

    return res;
}

int readZOverlay(const char *fname)
{
    void *p;
    int   res, start[3], end[3];
    int   thepixtype, theimgtype, imspp, nbcomp;

    // call the low-level Z-IMAGE reader
    res = load_zimage(fname, 0, start, end,
		      &thepixtype, &theimgtype, &imspp, &nbcomp,
		      &p);
    if (res == 0) {
	res = IOBlackBox->renderOverlay(fname, p, imspp, start, end, (pixtype)thepixtype);
	IOBlackBox->freeRawBuffers(p, imspp);
    }

    return res;
}


// This function returns the number of frames
// in a Z-IMAGE file. See description of load_zimage
// to understand what a `frame' is in the context
// of Z-IMAGE. This is in general NOT returning the number
// or components in the image, but rather the
// number of image `groups', or number of multicomponent sets.
// returns a negative number in case of error.
int zimagenbsubfiles(const char *fname)
{
    FILE *fp;
    int   nbread, Zversion, firstcomp;
    int   *firstR, *lastR, *firstC, *lastC, *firstP, *lastP, *imKind;
    int    i, n, nbim;
    long   filesize;
    char   alias[12], kind[10];

    
    fp = im_fopen(fname, "rb");

    if (!fp) {
	dbgprintf("zimagenbsubfiles: cannot read file %s\n", fname);
	return -1;
    }
    
    /* compute file length */
    fseek(fp, 0L, SEEK_END);
    filesize = ftell(fp);
    fseek(fp, 0L, SEEK_SET);

    /* read the Header now */
    nbread = fscanf(fp, "CSIROZ version %d\n", &Zversion);
    if (nbread != 1) {
	errprintf("zimagenbsubfiles: faulty Z-IMAGE format %s\n", fname);
	return(-2);
    }
    /* read the number of images in the file */
    if ((nbread = fscanf(fp, "%d\n", &nbim)) != 1) {
	errprintf("zimagenbsubfiles: can't read nb of components in %s\n", fname);
	return(3);
    }

    /* now read all the data in the headers */
    firstR = new int[nbim];
    lastR =  new int[nbim];
    firstC = new int[nbim];
    lastC =  new int[nbim];
    firstP = new int[nbim];
    lastP =  new int[nbim];
    
    imKind =  new int[nbim];

    /* read component images */
    for (i = 0 ; i < nbim ; i++) {
	if ((nbread = fscanf(fp, "%d %s %d %d %d %d ",
			     &n, alias, firstR+i, lastR+i, firstC+i, lastC+i
	    )) != 6) {
	    delete[] firstR;
	    delete[] lastR;
	    delete[] firstC;
	    delete[] lastC;
	    delete[] firstP;
	    delete[] lastP;
	    delete[] imKind;
	    errprintf("zimagenbsubfiles: error in first part of image header for component %d, file %s\n", i,fname);
	    return(-4);
	} else {
	    /* now try to decide whether this is a 3D image */
	    if ((nbread = fscanf(fp, "%d %d %s\n", firstP+i, lastP+i, kind)) != 3)  {
		/* this is not a 3D image, try again */
		firstP[i] = 0;
		lastP[i] = 0;
		if ((nbread = fscanf(fp, "%s\n", kind)) != 1) {
		    /* now this is an error */
		    delete[] firstR;
		    delete[] lastR;
		    delete[] firstC;
		    delete[] lastC;
		    delete[] firstP;
		    delete[] lastP;
		    delete[] imKind;
		    errprintf("zimagenbsubfiles: error in second part of image header for component %d, file %s\n", i, fname);
		    return(-5);
		}
	    }	
	    if (strcmp(kind, "BINARY") == 0)
		imKind[i] = IM_BINARY;
	    else if ((strcmp(kind, "CHAR") == 0) || (strcmp(kind, "GREY") == 0))
		imKind[i] = IM_UINT1; // UNSIGNED char is the default!
	    else if (strcmp(kind, "INT") == 0)
		imKind[i] = IM_INT;
	    else if (strcmp(kind, "DOUBLE") == 0)
		imKind[i] = IM_DOUBLE;
	    else {
		delete[] firstR;
		delete[] lastR;
		delete[] firstC;
		delete[] lastC;
		delete[] firstP;
		delete[] lastP;
		delete[] imKind;
		errprintf("zimagenbsubfiles: broken header for component %d, file %s\n", i, fname);
		return(-6);
	    }
	}
    }


    int tmpindex = 0, imageindex = 0;
    i = 1;
    do {
	firstcomp = tmpindex;
	while (i < nbim) { 
	    if (imKind[tmpindex] != imKind[i])
		break;
	    if ((lastR[i] != lastR[tmpindex])
		|| (lastC[i] != lastC[tmpindex])
		|| (lastP[i] != lastP[tmpindex]))
		break;
	    if ((firstR[i] != firstR[tmpindex])
		|| (firstC[i] != firstC[tmpindex])
		|| (firstP[i] != firstP[tmpindex]))
		break;
	    i++;
	}
	tmpindex = i;
	imageindex++;
    } while (i < nbim);

    // cleanup
    fclose(fp);
    
    delete[] firstR;
    delete[] lastR;
    delete[] firstC;
    delete[] lastC;
    delete[] firstP;
    delete[] lastP;
    delete[] imKind;
    
    return imageindex;
}

int load_zimage(const char *fname,	 /* input file name  */
		int         imageindex,	 /* index in the image file */
		int         start[3],	 /* coordinates of the starting point */
		int         end[3],	 /* coordinates of the end point */
		int        *thepixtype,	 /* pixel type (BINARY, CHAR, etc) */
		int        *theimgtype,	 /* image type (MULTI, RGB, etc) */
		int        *spp,         /* samples per pixels (read number of components) */
		int        *nbcomp,      /* total number of components in file, including unread ones */
		void      **inbuffp)	 /* pixel data (will be allocated) */
{
/** Reads a multispectral Z-IMAGE file format

    RETURN VALUE:	int 

    DESCRIPTION:

    This function reads a Z-IMAGE file and returns a multispectral
    image in a series of buffers.  The difficulties with Z-IMAGE is
    that the format does not indicate either the bit ordering or the
    image interpretation (RGB, etc). What this function does is try to
    work out both of these with the following strategy (heuristics):
    1) guess the bit ordering for INT and DOUBLE by finding out which
    is yielding the smallest range
    2) guess the photometric interpretation by reading the header
    information and collating together all the sub-images which have
    the same x,y and z dimensions, and the same offsets. If there are
    3 such images, the image is deemed RGB, if there are more than one
    (but not 3), it is deemed a MULTISPECTRAL image, if there is only
    one such image, it is deemed a SINGLE component image.

    If there are more components after the last one that has been
    interpreted as being part of a multispectral image, they are just
    ignored.

    It is possible to read all the sub-images in a file by specifying
    an image index `n' greater than 0. The caller will get the nth
    multispectral set.

    HISTORY:
    Written by Hugues Talbot	19 Jan 1998

    TESTS:

    REFERENCES:

    KEYWORDS:

**/
    FILE *fp;
    char  alias[12], kind[10], marker;
    int   res = 0;
    int   i, nbim, n, firstcomp, lastcomp, nbread, Zversion;
    long  filesize;
    int	 *firstR, *lastR, *firstC, *lastC, *firstP, *lastP;
    int  *imKind;
    void **buffp = 0;
    int   nx, ny, nz;
    long offs = 0;
    endianness e;

    
    fp = im_fopen(fname, "rb");
    if (!fp) {
	dbgprintf("load_zimage: cannot read file %s\n", fname);
	return 1;
    }
    
    /* compute file length */
    fseek(fp, 0L, SEEK_END);
    filesize = ftell(fp);
    fseek(fp, 0L, SEEK_SET);

    /* read the Header now */
    nbread = fscanf(fp, "CSIROZ version %d\n", &Zversion);

    dbgprintf("CSIRO Z version %d\n", Zversion);

    if (nbread != 1) {
	errprintf("load_zimage: faulty Z-IMAGE format %s\n", fname);
	return(2);
    }
    /* read the number of images in the file */
    if ((nbread = fscanf(fp, "%d\n", &nbim)) != 1) {
	errprintf("load_zimage: can't read nb of components in %s\n", fname);
	return(3);
    }

    /* now read all the data in the headers */
    firstR = new int[nbim];
    lastR =  new int[nbim];
    firstC = new int[nbim];
    lastC =  new int[nbim];
    firstP = new int[nbim];
    lastP =  new int[nbim];
    
    imKind =  new int[nbim];

    /* read component images */
    for (i = 0 ; i < nbim ; i++) {
	if ((nbread = fscanf(fp, "%d %s %d %d %d %d ",
			     &n, alias, firstR+i, lastR+i, firstC+i, lastC+i
	    )) != 6) {
	    delete[] firstR;
	    delete[] lastR;
	    delete[] firstC;
	    delete[] lastC;
	    delete[] firstP;
	    delete[] lastP;
	    delete[] imKind;
	    errprintf("load_zimage: error in first part of image header for component %d, file %s\n", i,fname);
	    return(4);
	} else {
	    /* now try to decide whether this is a 3D image */
	    if ((nbread = fscanf(fp, "%d %d %s\n", firstP+i, lastP+i, kind)) != 3)  {
		/* this is not a 3D image, try again */
		firstP[i] = 0;
		lastP[i] = 0;
		if ((nbread = fscanf(fp, "%s\n", kind)) != 1) {
		    /* now this is an error */
		    delete[] firstR;
		    delete[] lastR;
		    delete[] firstC;
		    delete[] lastC;
		    delete[] firstP;
		    delete[] lastP;
		    delete[] imKind;
		    errprintf("load_zimage: error in second part of image header for component %d, file %s\n", i, fname);
		    return(5);
		}
	    }	
	    if (strcmp(kind, "BINARY") == 0)
		imKind[i] = IM_BINARY;
	    else if ((strcmp(kind, "CHAR") == 0) || (strcmp(kind, "GREY") == 0))
		imKind[i] = IM_UINT1; // Unsigned char is the default!
	    else if (strcmp(kind, "INT") == 0)
		imKind[i] = IM_INT;
	    else if (strcmp(kind, "DOUBLE") == 0)
		imKind[i] = IM_DOUBLE;
	    else {
		delete[] firstR;
		delete[] lastR;
		delete[] firstC;
		delete[] lastC;
		delete[] firstP;
		delete[] lastP;
		delete[] imKind;
		errprintf("load_zimage: broken header for component %d, file %s\n", i, fname);
		return(6);
	    }
	}
    }

    // endianness issue
    if (Zversion > 5) {
        if (strncmp(alias, "\"(null)\"", 8) == 0) {
            dbgprintf("File advertises little-endian data\n");
            e = ENDIAN_LITTLE;
        } else {
            dbgprintf("File advertises big-endian data\n");
            e = ENDIAN_BIG;
        }
    } else {
        dbgprintf("Z version too old, unknown data endianness\n");
        e = ENDIAN_UNKNOWN;
    }


    /* now work out what to do */
    if (imageindex >= nbim) {
	dbgprintf("load_zimage: required image index greater than number of components: %d >= %d\n", imageindex, nbim);
	imageindex = 0;
    }
    
    int tmpindex = 0;
    i = 1;
    *nbcomp = 0;
    do {
	firstcomp = tmpindex;
	while (i < nbim) { 
	    if (imKind[tmpindex] != imKind[i])
		break;
	    if ((lastR[i] != lastR[tmpindex])
		|| (lastC[i] != lastC[tmpindex])
		|| (lastP[i] != lastP[tmpindex]))
		break;
	    if ((firstR[i] != firstR[tmpindex])
		|| (firstC[i] != firstC[tmpindex])
		|| (firstP[i] != firstP[tmpindex]))
		break;
	    i++;
	}
	(*nbcomp)++;
	tmpindex = i;
    } while ((imageindex-- > 0) && (i < nbim));

    if ((imageindex != -1) && (i==nbim)) {
	// caller asked for a component beyond the end of the file
	// this is legitimate! just an error code reported
	// cleanup
	fclose(fp);

	delete[] firstR;
	delete[] lastR;
	delete[] firstC;
	delete[] lastC;
	delete[] firstP;
	delete[] lastP;
	delete[] imKind;

	*inbuffp = 0;
	return(7);
    }
    
    lastcomp = i-1;
    *spp = lastcomp-firstcomp+1; // this is the real number of samples per pixel
    *thepixtype = imKind[firstcomp];

    if (*spp == 3)
	*theimgtype = IM_RGB;       // could be IM_HLS, but there is no way of knowing
    else 
	*theimgtype = IM_SPECTRUM;  // this includes single-component images

    start[1] = firstR[firstcomp];
    end[1] = lastR[firstcomp];
    start[0] = firstC[firstcomp];
    end[0] = lastC[firstcomp];
    start[2] = firstP[firstcomp];
    end[2] = lastP[firstcomp];

    nx = end[0] - start[0] +1;
    ny = end[1] - start[1] +1;
    nz = end[2] - start[2] +1;

    // start reading the data
    
    // we must skip over the nth first components,
    // which are of no interest to us...

    dbgprintf("Position in Z file: %ld\n", ftell(fp));
    // apparently Win32 eats the 0 by itself. This is weird
    // but first we have to jump over this nasty '\0'
    if ((marker = skipzero(fp)) != '\0') {
	errprintf("load_zimage: wrong first data byte in file: got %d\n", marker);
	return 8;
    }
    dbgprintf("Position in Z file after eating '\\0': %ld\n", ftell(fp));
    
    for (i = 0 ; i < firstcomp ; i++) {
	int nnx = lastR[i] - firstR[i] + 1;
	int nny = lastC[i] - firstC[i] + 1;
	int nnz = lastP[i] - firstP[i] + 1;
	switch(imKind[i]) {
	  case IM_BINARY:
	  case IM_CHAR:
	  case IM_UINT1:
	    offs = nnx*nny*nnz*sizeof(char);
	    break;
	    
	  case IM_UINT4:
	  case IM_INT4:
	    offs = nnx*nny*nnz*sizeof(int);
	    break;
	    
	  case IM_DOUBLE:
	    offs = nnx*nny*nnz*sizeof(double);
	    break;

	  default:
	    offs = 0;
	    break;
	}
	if ((res = fseek(fp, offs, SEEK_CUR)) != 0) {
	    errprintf("Can't jump over unwanted components\n%s",
		      strerror(errno));
	    // cleanup
	    fclose(fp);
	    delete[] firstR;
	    delete[] lastR;
	    delete[] firstC;
	    delete[] lastC;
	    delete[] firstP;
	    delete[] lastP;
	    delete[] imKind;
	    *inbuffp =  0;
	    return(9);
	}
    }

    dbgprintf("Position in Z file after skipping unwanted components: %ld\n",
	      ftell(fp));
    dbgprintf("Should have skipped %ld bytes\n", offs);
    
    buffp = (void **) malloc(*spp * sizeof(void **));
    
    for (i = firstcomp ; i <= lastcomp ; i++) {
	switch (*thepixtype) {
	  case IM_BINARY:
	  case IM_UINT1:
	  case IM_INT1:
	    buffp[i-firstcomp] = readCHARZimage(fp, nx, ny, nz);
	    break;

	  case IM_UINT4:
	  case IM_INT4:
	    buffp[i-firstcomp] = readINTZimage(fp, nx, ny, nz, e);
	    break;

	  case IM_DOUBLE:
	    buffp[i-firstcomp] = readDOUBLEZimage(fp, nx, ny, nz, e);
	    break;
	    
	  default:
	    errprintf("load_zimage: type %d reader not implemented yet\n", *thepixtype);
	    break;
	}
	if (buffp[i-firstcomp] == 0) {
	    // an error occured
	    for (int j = firstcomp ; j < i ; j++)
		free(buffp[i-firstcomp]);
	    free(buffp);
	    buffp = 0;
	    res = 10;
	}
    }

    // cleanup
    fclose(fp);

    delete[] firstR;
    delete[] lastR;
    delete[] firstC;
    delete[] lastC;
    delete[] firstP;
    delete[] lastP;
    delete[] imKind;

    *inbuffp = buffp;
    return res;
}

endianness checkendian(void)
{
    /* Are we little or big endian?  From Harbison&Steele.  */
    union
    {
        long l;
        char c[sizeof (long)];
    } u;
    u.l = 1;
    if (u.c[sizeof (long) - 1] == 1)
        return(ENDIAN_BIG);
    else
        return(ENDIAN_LITTLE);
}

static void *readCHARZimage(FILE *fp, int nx, int ny, int nz)
{
    uchar *retbuf;
    long imlength, nbread;

    imlength = nx*ny*nz;

    retbuf = (uchar *)malloc(nx*ny*nz * sizeof(uchar)); // stupid malloc, to be compatible with the TIFF reader

    if (retbuf == 0) {
	errprintf("readCHARZimage: not enough memory to load file\n");
	return 0;
    }

    nbread = fread(retbuf, sizeof(uchar), imlength, fp);
    if (nbread != imlength) {
	errprintf("load_zimage: incomplete image\n");
	// this is only a warning, complete with zeroes
	memset(retbuf+nbread, 0, (imlength-nbread)*sizeof(uchar));
    }

    return retbuf;
}



// this is not as easy because of the big-endian vs. little-endian stuff
static void *readINTZimage(FILE *fp, int nx, int ny, int nz, endianness e)
{
    int  *retbuf;
    long  imlength, nbread;

    imlength = nx*ny*nz;

    retbuf = (int *)malloc(nx*ny*nz * sizeof(int)); // stupid malloc, to be compatible with the TIFF reader

    if (retbuf == 0) {
	errprintf("readINTZimage: not enough memory to load file\n");
	return 0;
    }

    nbread = fread(retbuf, sizeof(int), imlength, fp);
    if (nbread != imlength) {
	errprintf("load_zimage: incomplete image\n");
	// this is only a warning, complete with zeroes
	memset(retbuf+nbread, 0, (imlength-nbread)*sizeof(int)); 
    }

    if (((e != ENDIAN_UNKNOWN) && (e != checkendian()))
        || ((e == ENDIAN_UNKNOWN) && (needswapint(retbuf, imlength)))) {
	dbgprintf("Image buffer will be swapped\n");
	swapintbuf(retbuf, imlength); // in-place processing 
    } else
	dbgprintf("Image buffer will not be swapped\n");
    
    return retbuf;
}

// this is not as easy because of the big-endian vs. little-endian stuff
static void *readDOUBLEZimage(FILE *fp,int nx, int ny, int nz, endianness e)
{
    double *retbuf;
    int  ns;
    long imlength, nbread;

    imlength = nx*ny*nz;

    retbuf = (double *)malloc(nx*ny*nz * sizeof(double)); // stupid malloc, to be compatible with the TIFF reader

    if (retbuf == 0) {
	errprintf("readDOUBLEZimage: not enough memory to load file\n");
	return 0;
    }

    nbread = fread(retbuf, sizeof(double), imlength, fp);
    if (nbread != imlength) {
	errprintf("readDOUBLEZimage: incomplete image\n");
	// this is only a warning, complete with zeroes
	memset(retbuf+nbread, 0, (imlength-nbread)*sizeof(double));
    }

    ns = 2;
    if (((e != ENDIAN_UNKNOWN) && (e != checkendian()))
        || ((e == ENDIAN_UNKNOWN) && ((ns = needswapdouble(retbuf, imlength)) == 1))) {
	dbgprintf("Image buffer will be swapped\n");
	swapdoublebuf(retbuf, imlength); // in-place processing 
    } else if (ns == -1) {
        /* if needswapdouble was called but caused SIGFPE on both 
           swapped and unswapped versions */
        errprintf("readDoubleZImage: cannot make sense of image\n because of invalid double precision values present\n");
	free(retbuf);
	retbuf = 0;
    } else {
	dbgprintf("Image buffer will not be swapped\n");
    }

    return retbuf;
}



static int needswapint(int *buf, long buflen)
{
    int *p, swp, *end, minval, maxval;
    int swminval, swmaxval;
    unsigned int range, swrange;
    int sample = trivmin((buflen/503 + 1), 997); // largish prime number

    
    p = buf;
    end = buf+buflen;
    minval = maxval = *p;

    // try the unswapped version
    while (p < end) {
	if (*p > maxval)
	    maxval = *p;
	if (*p < minval)
	    minval = *p;
	p += sample;    // no need to sample all the pixels...
    }
    range = maxval - minval;
    dbgprintf("needswapint: unswapped range = %u\n", range);
	    
    // now do the same thing with swap on
    p = buf;
    swmaxval = swminval = swapint(*p);
    while (p < end) {
	swp = swapint(*p); 
	if (swp > swmaxval)
	    swmaxval = swp;
	if (swp < swminval)
	    swminval = swp;
	p += sample;    // no need to sample all the pixels...
    }
    swrange = swmaxval - swminval;
    dbgprintf("needswapint: swapped range = %u\n", swrange);

    if ((swrange == 0) && (range == 0)) 
	return 0; // we don't know so we don't swap
    else if (swrange < range)
	return 1; // yes, need swapping!
    else if ((swrange == range) && (swmaxval < maxval))
	return 1 ; // yes: still need swapping
    else return 0; // no need to swap
}

static void arithExceptHandler(int sig)
{
    // reset the signal handler
    signal(sig, arithExceptHandler);
    im_longjmp(AEenv, 1);
}

// log are used in there otherwise FP exception
// might be raised when comparing extreme numbers
// that would only be possible with loss of precision
// I.e: comparing 10^-300 and 10^+300

typedef void (signalHandler)(int);

static int needswapdouble(double *buf, long buflen)
{
    volatile void *vp;
    double *p, lp, swp, lswp, *end, minval, maxval; vp = &p; vp = &lp; vp = &swp; vp = &lswp; vp= &end; vp = &minval; vp = &maxval;
    double swminval, swmaxval; vp = &swminval; vp = &swmaxval;
    double range, swrange; vp = &range ; vp = &swrange;
    int sample = trivmin((buflen/503 + 1),997); vp = &sample;// largish prime number 
    bool raisedWhenSwapped, raisedWhenNotSwapped; vp = &raisedWhenSwapped; vp = &raisedWhenNotSwapped;
    int  retval = 0; vp = &retval;
    
    p = buf;
    end = buf+buflen;

    signalHandler *oldHandler = signal(SIGFPE, arithExceptHandler);
    if (oldHandler == SIG_ERR) {
	errprintf("needswapdouble: Could not set up FP exception handler.\n");
	// continue anyway!
    }

    if (im_setjmp(AEenv, 1) == 0) {
	// try the unswapped version
	minval = maxval = 0;
	// look for first non-null pixel, if any 
	while (p < end) {
	    if (*p != 0.0) {
		lp = log(fabs(*p));
		if ((lp > 1000) || (lp < -1000)) {
		    p += sample;
		    continue;
		}
		/* first value found */
		minval = maxval = *p;
		break;
	    }
            ++p;
	}
	while (p < end) {
	    //skip the zeroes
	    if (*p != 0.0) {
		lp = log(fabs(*p));
		if ((lp > 1000) || (lp < -1000)) {
		    p += sample;
		    continue;
		}
	        
		if (lp > maxval)
		    maxval = lp;
		if (lp < minval)
		    minval = lp;
	    }
	    p += sample;    // no need to sample all the pixels...
	}
	range = maxval - minval;
	dbgprintf("needswapdouble: unswapped log range = %g\n", range);
	raisedWhenNotSwapped = false;
    } else {
	// we got there because of an exception:
	raisedWhenNotSwapped = true;
    }
    
    // now do the same thing with swap on
    p = buf;
    swmaxval = swminval = 0;
    if (im_setjmp(AEenv, 1) == 0) {
	// look for first non-null pixel, if any 
	while (p < end) {
	    swp = swapdouble(*p);
	    if (swp != 0.0) {
		lswp = log(fabs(swp));
		if ((lswp > 1000) || (lswp < -1000)) {
		    p += sample;
		    continue;
		}
		/* first value found */
		minval = maxval = lswp;
		break;
	    }
            ++p;
	}
	while (p < end) {
	    swp = swapdouble(*p);
	    // skip over the zeroes
	    if (swp != 0.0) {
		lswp = log(fabs(swp));
		if ((lswp > 1000) || (lswp < -1000)) {
		    p += sample;
		    continue;
		}
		if (lswp > swmaxval)
		    swmaxval = lswp;
		if (lswp < swminval)
		    swminval = lswp;
	    }
	    p += sample;    // no need to sample all the pixels...
	}
	swrange = swmaxval - swminval;
	dbgprintf("needswapdouble: swapped log range = %g\n", swrange);
	raisedWhenSwapped = false;
    } else {
	raisedWhenSwapped = true;
    }

    // reset the FPE handler to its previous state
    if (oldHandler != SIG_ERR) {
	if (signal(SIGFPE, oldHandler) == SIG_ERR) {
	    errprintf("needswapdouble: Could not restore original FP exception handler\n");
	    //continue anyway!
	}
	
    }

    if (raisedWhenSwapped && raisedWhenNotSwapped)
	retval = -1; // this image is basically unreadable
    else if (raisedWhenSwapped)
	retval = 0; // do not swap
    else if (raisedWhenNotSwapped)
	retval = 1; // do swap, then
    else  if (swrange < range)
	retval = 1; // yes, need swapping!
    else if ((swrange == 0) && (range == 0))
	retval = 0; // we have a constant value in the image, we don't swap because it could be anything
    else if ((swrange == range) && (swmaxval < maxval))
	retval = 1 ; // yes: still need swapping
    else retval = 0; // no need to swap

    return retval;
}

static int swapint(int i)
{
    uchar *from, *to;
    int    j;
    
    from = (uchar *)&i;
    to = (uchar *)&j;

    to[0] = from[3];
    to[1] = from[2];
    to[2] = from[1];
    to[3] = from[0];
    
//  j = ((int)(p[0]) << 24) +
//	((int)(p[1]) << 16) +
//	((int)(p[2]) << 8)  +
//	((int)(p[3]));

    return j;
}

static double swapdouble(double d)
{
    uchar *from, *to;
    double b;

    from = (uchar *)&d;
    to   = (uchar *)&b;
    to[0] = from[7];
    to[1] = from[6];
    to[2] = from[5];
    to[3] = from[4];
    to[4] = from[3];
    to[5] = from[2];
    to[6] = from[1];
    to[7] = from[0];
    
    return b;
}


// no questions asked...
// in-place processing
void swapintbuf(int *buf, long buflen)
{
    int *p, *end;

    dbgprintf("Swapping int buffer\n");

    p = buf;
    end = p + buflen;

    while (p < end) {
	*p = swapint(*p);
	p++;
    }

    return;
}

void swapdoublebuf(double *buf, long buflen)
{
    double *p, *end;

    dbgprintf("Swapping double buffer\n");

    p = buf;
    end = p + buflen;

    while (p < end) {
	*p = swapdouble(*p);
	p++;
    }

    return;
}