File: fits_file.cpp

package info (click to toggle)
dpuser 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,632 kB
  • sloc: cpp: 121,623; ansic: 6,866; lex: 1,113; makefile: 747; yacc: 741; sh: 78
file content (1350 lines) | stat: -rw-r--r-- 33,522 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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
/******************************************************************
 * DPUSER - The Next Generation
 *
 * File:     libfits/fits_file.cpp
 * Purpose:  Fits class methods to read and write fits files
 * Author:   Thomas Ott
 *
 * Revision history
 * ================
 * 05.08.1999: file created
 ******************************************************************/
 
#include "platform.h"
#include "fits.h"

#define SIMPLE_T "SIMPLE  =                    T                                                  "
#define FITS_EMPTY "                                                                                "
#define FITS_END "END                                                                             "
#define FITS_NAXIS0 "NAXIS   = 0                                                                     "
#define FITS_BITPIX8 "BITPIX  = 8                                                                     "
#define EXTENT_T "XTENSION= 'IMAGE   '                                                            "

/*
 * Utility function to correct byte order
 * if we are on a machine with little-endian byte order, we have to swap
 */

bool getByteOrder( void )
{
// Are we little or big endian?  From Harbison&Steele.
  union
  {
    long l;
    char c[sizeof (long)];
  } u;
  u.l = 1;
  return(u.c[sizeof (long) - 1] == 1);
}

void swapBytes(void *dataptr, int b, dpint64 n_elements)
{
    dpint64 i;
    char tempr;
    char *_tmp;

	if (!getByteOrder()) {
        _tmp = (char *)dataptr;
        if (b == C16) {
            for (i = 0; i < n_elements * 8 * 2; i += 8) {
                SWAP(_tmp[i], _tmp[i+7]);
                SWAP(_tmp[i+1], _tmp[i+6]);
                SWAP(_tmp[i+2], _tmp[i+5]);
                SWAP(_tmp[i+3], _tmp[i+4]);
			}
        } else if ((b == R8) || (b == I8)) {
            for (i = 0; i < n_elements * 8; i += 8) {
                SWAP(_tmp[i], _tmp[i+7]);
                SWAP(_tmp[i+1], _tmp[i+6]);
                SWAP(_tmp[i+2], _tmp[i+5]);
                SWAP(_tmp[i+3], _tmp[i+4]);
			}		
        } else if ((b == R4) || (b == I4)) {
            for (i = 0; i < n_elements * 4; i += 4) {
                SWAP(_tmp[i], _tmp[i+3]);
                SWAP(_tmp[i+1], _tmp[i+2]);
			}
        } else if (b == I2) {
            for (i = 0; i < n_elements * 2; i += 2) {
                SWAP(_tmp[i], _tmp[i+1]);
			}
		}
	}
}

/*!
our own fseek function
*/

int Fits::dpseek(long long offset, int whence) {
    if (gz) {
        return gzseek(gfd, offset, whence);
    } else {
#ifdef WIN
        return fseeko64(fd, offset, whence);
#else
        return fseek(fd, offset, whence);
#endif
    }
}

/*!
our own ftell function
*/

long long Fits::dptell() {
    if (gz) {
        return gztell(gfd);
    } else {
#ifdef WIN
        return ftello64(fd);
#else
        return ftell(fd);
#endif
    }
}

/*!
our own fread function
*/

dpint64 Fits::dpread(void *ptr, dpint64 nmemb) {
    if (gz) {
        return gzread(gfd, ptr, nmemb);
    } else {
        return fread(ptr, 1, nmemb, fd);
    }
}

/*!
Open a FITS file for READ ONLY
*/

bool Fits::OpenFITS(const char *fname) {
    char *ff = strdup(fname);
    unsigned char gz_magic_number[2];

    gz = FALSE;

    if ((fd = fopen(ff, "rb")) == NULL) {
        ff = (char*)realloc(ff, (strlen(ff)+4) * sizeof(char));
        strcat(ff, ".gz");
        if ((fd = fopen(ff, "rb")) == NULL) {
            free(ff);
            return fits_error("Could not open file for reading");
        }
    }
    if (fread(gz_magic_number, 1, 2, fd) != 2) {
        free(ff);
        fclose(fd);
        return fits_error("Could not open file for reading");
    }

    if ((gz_magic_number[0] == 0x1f) && (gz_magic_number[1] == 0x8b)) {
        fclose(fd);
        if ((gfd = gzopen(ff, "rb")) == NULL) {
            free(ff);
            return fits_error("Could not open file for reading");
        }
        gz = TRUE;
    } else {
        fseek(fd, 0L, SEEK_SET);
    }

    ro = TRUE;

	free(ff);
	return TRUE;
}

/*!
Open a FITS file for WRITING
*/

bool Fits::CreateFITS(const char *fname) {
    if ((fd = fopen(fname, "wb")) == NULL) {
		return fits_error("Could not open file for writing");
	}
	ro = FALSE;
	return TRUE;
}

/*!
Close a previously opened FITS file. If the file was opened for read/write, append enough 0's so
its total length is an integer multiple of 2880 bytes (FITS standard).
*/

void Fits::CloseFITS() {
    if (ro) {
        if (gz) {
            gzclose(gfd);
        } else {
            fclose(fd);
        }
    } else {
		long pos;
//		char w = (char)0;
		char w[2880];
		
		fseek(fd, 0L, SEEK_END);
		pos = ftell(fd);
//		fwrite(&w, 1, 2880 - (pos % 2880), fd);
        if ((pos % 2880) != 0) {
            fwrite(w, 2880 - (pos % 2880), 1, fd);
        }
		fclose(fd);
		fd = NULL;
	}
}

/*!
Read in data in the FITS file
Partial loading is supported
*/

bool Fits::ReadFITSData(dpint64 x1, dpint64 x2, dpint64 y1, dpint64 y2, dpint64 z1, dpint64 z2) {
    dpint64 b;
    dpint64 n, count;
    dpint64 partial;

	b = abs(filebits) / 8;

// check if values are correct
	if ((x1 > x2) || (y1 > y2) || (z1 > z2)) {
		dp_output("Reading partial data: Wrong arguments.\n");
		return FALSE;
	}
    if ((x2 > (dpint64)naxis[1]) || (y2 > (dpint64)naxis[2]) || (z2 > (dpint64)naxis[3])) {
		dp_output("Reading partial data: Arguments out of bounds.\n");
		return FALSE;
	}

// check which case
	if ((x1 == 0) && (x2 == 0) && (y1 == 0) && (y2 == 0) && (z1 == 0) && (z2 == 0)) {

// read all data
		partial = b * n_elements / 100;
		if (partial < 10000) {
            if (dpread(dataptr, b * n_elements) != n_elements * b) {
				return fits_error("Premature end of data");
			}
		} else {
// read in in smaller chunks so we can display a progress bar
			char *_tmp = (char *)dataptr;
			dpProgress(-100, "");
			for (count = 0; count < 99; count++) {
                if (dpread(_tmp, partial) != partial) {
					dpProgress(0, "");
					return fits_error("Premature end of data");
				}
				_tmp += partial;
				dpProgress(count+1, "reading file...");
			}
			partial = b * n_elements - 99 * partial;
            if (dpread(_tmp, partial) != partial) {
				dpProgress(0, "");
				return fits_error("Premature end of data");
			}
			dpProgress(100, "");
		}
	} else if ((x1 == 0) && (x2 == 0) && (y1 == 0) && (y2 == 0)) {

// read complete images
        dpseek((naxis[1]) * naxis[2] * (z1 - 1) * b, SEEK_CUR);
        if (dpread(dataptr, b * n_elements) != n_elements * b) {
			return fits_error("Premature end of data");
		}
	} else if ((x1 == 0) && (x2 == 0)) {
		char *_tmp = (char *)dataptr;
		long pos = 0;
		
		if (z1 == 0) z1 = 1;
		if (z2 == 0) z2 = naxis[3];
        dpseek((naxis[1]) * naxis[2] * (z1 - 1) * b, SEEK_CUR);
        for (n = (int)z1; n <= (int)z2; n++) {
            dpseek((naxis[1]) * (y1 - 1) * b, SEEK_CUR);
            if (dpread(&_tmp[pos], b * naxis[1] * (y2 - y1 + 1)) != ((dpint64)(naxis[1]) * (y2 - y1 + 1) * b)) {
				return fits_error("Premature end of data");
			}	
			pos += naxis[1] * (y2 - y1 + 1) * b;
            dpseek((naxis[1]) * (naxis[2] - y2) * b, SEEK_CUR);
		}	
	} else {
		char *_tmp = (char *)dataptr;
		char *__tmp;
		long x, y, pos = 0;
		
		if (z1 == 0) z1 = 1;
		if (z2 == 0) z2 = naxis[3];
		if (y1 == 0) y1 = 1;
		if (y2 == 0) y2 = naxis[2];
		if ((__tmp = (char *)malloc(naxis[1] * (y2 - y1 + 1) * b)) == NULL) {
			return fits_error("Read partial: Could not allocate memory");
		}
        dpseek((naxis[1]) * naxis[2] * (z1 - 1) * b, SEEK_CUR);
		for (n = (int)z1; n <= (int)z2; n++) {
            dpseek((naxis[1]) * (y1 - 1) * b, SEEK_CUR);
            if (dpread(__tmp, b * naxis[1] * (y2 - y1 + 1)) != ((dpint64)(naxis[1]) * (y2 - y1 + 1) * b)) {
				return fits_error("Premature end of data");
			}
			for (y = 0; y <= (int)(y2 - y1); y++) {
				for (x = (int)(x1 - 1) * b; x < (int)x2 * b; x++) {
					_tmp[pos] = __tmp[y * naxis[1] * b + x];
					pos++;
				}
			}
            dpseek((naxis[1]) * (naxis[2] - y2) * b, SEEK_CUR);
		}
		free(__tmp);
	}

// swap bytes
	swapBytes(dataptr, filebits, n_elements);

// Deal with SHARP data
	if (isSHARPIdata()) convertSHARPIdata();

// everything ok
	return TRUE;
}

/*!
Read in one image of a FITS cube
*/

bool Fits::ReadFITSCubeImage(int which) {
    dpint64 n, b;

	b = abs(filebits) / 8;
	if (!getHeaderInformation()) return FALSE;
	if (!recreate(naxis[1], naxis[2])) return FALSE;
// seek file position
    if (dpseek(hdr + b * (which - 1) * n_elements, SEEK_SET) == -1) {
		return fits_error("Cannot acces cube image");
	}

// read data
    if ((n = dpread(dataptr, b * n_elements)) != n_elements * b) {
		dp_output("Could only read %li elements.", n);
		return fits_error("Premature end of data");
	}

// swap bytes
	swapBytes(dataptr, filebits, n_elements);
	membits = filebits;

// deal with special SHARP I case
	if (isSHARPIdata()) convertSHARPIdata();

// everything ok
	return TRUE;
}

/*!
Write the data to file.
*/

bool Fits::WriteFITSData(void) {
	if (fd == NULL) return FALSE;
	swapBytes(dataptr, membits, n_elements);
    if (fwrite(dataptr, abs((int)membits / 8), n_elements, fd) != n_elements) {
		swapBytes(dataptr, membits, n_elements);
		CloseFITS();
		return FALSE;
	}
	swapBytes(dataptr, membits, n_elements);
	return TRUE;
}

/*!
Read in a complete FITS file
by default, the image(s) is stored in a float array
*/

bool Fits::ReadFITS(const char *fname, dpint64 x1, dpint64 x2, dpint64 y1, dpint64 y2, dpint64 z1, dpint64 z2) {
    dpint64 mem;
	bool hasrefpix;

// open file
	if (!OpenFITS(fname)) return FALSE;
//	if (!OpenFITS(fname)) throw dpFitsException(3);

// read header
    if ((hdr = ReadFitsHeader()) < 0) return FALSE;

// get Header info and allocate memory
	if (!getHeaderInformation()) return FALSE;
	if ((x1) || (x2)) mem = x2 - x1 + 1;
	else mem = naxis[1];
	if ((y1) || (y2)) mem *= y2 - y1 + 1;
	else mem *= naxis[2];
	if ((z1) || (z2)) mem *= z2 - z1 + 1;
	else mem *= naxis[3];
	mem *= abs(membits / 8);
	if (mem <= 0) return fits_error("ReadFits: invalid range");
	if (!allocateMemory(mem)) return FALSE;

// read data
	if (!ReadFITSData(x1, x2, y1, y2, z1, z2)) return FALSE;

	hasrefpix = hasRefPix();
	if ((x1) || (x2)) {
		naxis[1] = x2 - x1 + 1;
		if ((x1 > 1) && hasrefpix) SetFloatKey("CRPIX1", getCRPIX(1) - (double)(x1 - 1));
	}
	if ((y1) || (y2)) {
		naxis[2] = y2 - y1 + 1;
		if ((y1 > 1) && hasrefpix) SetFloatKey("CRPIX2", getCRPIX(2) - (double)(y1 - 1));
	}
	if ((z1) || (z2)) {
		naxis[3] = z2 - z1 + 1;
		if ((z1 > 1) && hasrefpix) SetFloatKey("CRPIX3", getCRPIX(3) - (double)(z1 - 1));
	}
	deflate();
//	if (naxis[3] < 2) naxis[0] = 2;

// close file
	CloseFITS();

// everything ok
	strncpy(FileName, fname, 255);
    extensionNumber = 0;
	
	return TRUE;
}	


/*!
Read in a complete FITS file
by default, the image(s) is stored in a float array
*/

bool Fits::ReadFITSExtension(const char *fname, int ext, dpint64 x1, dpint64 x2, dpint64 y1, dpint64 y2, dpint64 z1, dpint64 z2)
{
    dpint64 mem;
    bool hasrefpix;

    // open file
    if (!OpenFITS(fname))
        return FALSE;
    //	if (!OpenFITS(fname))
    //      throw dpFitsException(3);

    // read header
    if ((hdr = ReadFitsExtensionHeader(ext)) < 0)
        return FALSE;

    // get Header info and allocate memory
    if (!getHeaderInformation())
        return FALSE;
    if ((x1) || (x2))
        mem = x2 - x1 + 1;
    else
        mem = naxis[1];

    if ((y1) || (y2))
        mem *= y2 - y1 + 1;
    else
        mem *= naxis[2];

    if ((z1) || (z2))
        mem *= z2 - z1 + 1;
    else
        mem *= naxis[3];

    mem *= abs(membits / 8);

    if (mem <= 0)
        return fits_error("ReadFits: invalid range");

    if (!allocateMemory(mem))
        return FALSE;

    // read data only if NAXIS > 0 (no empty data section)
    int val = 0;
    GetIntKey("NAXIS", &val);
    if(val > 0) {
        if (!ReadFITSData(x1, x2, y1, y2, z1, z2)) return FALSE;
    }

    hasrefpix = hasRefPix();
    if ((x1) || (x2)) {
        naxis[1] = x2 - x1 + 1;
        if ((x1 > 1) && hasrefpix)
            SetFloatKey("CRPIX1", getCRPIX(1) - (double)(x1 - 1));
    }
    if ((y1) || (y2)) {
        naxis[2] = y2 - y1 + 1;
        if ((y1 > 1) && hasrefpix)
            SetFloatKey("CRPIX2", getCRPIX(2) - (double)(y1 - 1));
    }
    if ((z1) || (z2)) {
        naxis[3] = z2 - z1 + 1;
        if ((z1 > 1) && hasrefpix)
            SetFloatKey("CRPIX3", getCRPIX(3) - (double)(z1 - 1));
    }
    deflate();
//    if (naxis[3] < 2) naxis[0] = 2;

    // close file
    CloseFITS();

    // everything ok
    strncpy(FileName, fname, 255);
    char tmp[20];
    sprintf(tmp, ", ext #%d", ext);
    strncat(FileName, tmp, 20);
    return TRUE;
    extensionNumber = ext;
}

bool Fits::tfieldWidth(int column, int *bytes, int *repeat, char *type) {
	char key[9];
	char tform[81];
	int c;

	sprintf(key, "TFORM%i", column);
	if (!GetStringKey(key, tform)) return FALSE;
	*repeat = 1;
	c = 0;
	if (isdigit(tform[c])) {
		*repeat = tform[c] - '0';
		c++;
        while (isdigit(tform[c])) {
			*repeat = 10 * (*repeat) + (tform[c] - '0');
			c++;
		}
	}
	switch (tform[c]) {
		case 'I':
			*bytes = 2;
			break;
		case 'J':
		case 'E':
			*bytes = 4;
			break;
		case 'D':
		case 'C':
		case 'P':
        case 'K':
			*bytes = 8;
			break;
		case 'M':
			*bytes = 16;
			break;
		default:
			*bytes = 1;
			break;
	}
	*type = tform[c];
	
	return TRUE;
}
	

/*
read the nth FITS Bintable column and return Fits
*/
bool Fits::GetBintableColumn(int column, Fits &result) {
    int tfields;
    if ((column < 1) ||
        (!GetIntKey("TFIELDS", &tfields)) ||
        (tfields < column))
    {
        return false;
    }
	
    // go through the TFORMi keywords and count the bytes
    int bytes  = 0,
        width  = 0,
        repeat = 0;
    char fieldtype;
    for (int i = 1; i < column; i++) {
        if (!tfieldWidth(i, &width, &repeat, &fieldtype)) {
            return false;
        }
		bytes += repeat * width;
	}
    if (!tfieldWidth(column, &width, &repeat, &fieldtype)) {
        return false;
    }
	width *= repeat;
	
    FitsBitpix bits = NA;
	switch (fieldtype) {
		case 'A':
		case 'B':
		case 'L': bits = I1; break;
		case 'I': bits = I2; break;
		case 'J': bits = I4; break;
        case 'K': bits = I8; break;
		case 'E': bits = R4; break;
		case 'D': bits = R8; break;
        case 'C':
        case 'M': bits = C16; break;
		default: bits = NA; break;
	}
    if (bits == NA) {
        return false;
    }

    // take care that vectors are setup correctly here
    int xDim = 0, yDim = 0;
    if (repeat == 1) {
        xDim = Naxis(2);
        yDim = repeat;
    } else {
        xDim = repeat;
        yDim = Naxis(2);
    }

    result.create(xDim, yDim, bits);
	
    int c = 0;
    for (int y = 0; y < Naxis(2); y++) {
        for (int x = bytes; x < bytes + width; x++) {
			result.i1data[c] = i1data[C_I(x, y)];
			c++;
		}
	}

    if (fieldtype != 'C') {
        swapBytes(result.dataptr, result.membits, result.Nelements());
    } else {
        swapBytes(result.dataptr, R4, result.Nelements() * 2);
        int i, j;
        for (i = result.Nelements() * 2 - 1, j = result.Nelements() - 1; i >= 0; i -= 2, j--) {
            result.cdata[j].i = (double)result.r4data[i];
            result.cdata[j].r = (double)result.r4data[i-1];
        }
    }
	
    double value;
    char key[9];
	sprintf(key, "TSCAL%i", column);
    if (GetFloatKey(key, &value)) {
        result.bscale = value;
    }
	sprintf(key, "TZERO%i", column);
    if (GetFloatKey(key, &value)) {
        result.bzero = value;
    }

// check for TDIMi
    char tdim[81];
    sprintf(key, "TDIM%i", column);
    if (GetStringKey(key, tdim)) {
        if (tdim[0] == '(') {
            int xdim = 1, ydim = 1, zdim = 1;
            int count = 0;
            count = sscanf(tdim, "(%i,%i", &xdim, &ydim);
            if (count == 2) {
                if (result.Naxis(2) > 1) zdim = result.Naxis(2);
                if (result.Nelements() == xdim * ydim * zdim) {
                    result.setNaxis(0, (zdim > 1 ? 3 : 2));
                    result.setNaxis(1, xdim);
                    result.setNaxis(2, ydim);
                    result.setNaxis(3, zdim);

                    result.extensionType = BINTABLEIMAGE;
                } else {
                    result.extensionType = BINTABLE;
                }
            }
        }
    } else {
        result.extensionType = BINTABLE;
    }

	result.updateHeader();

    // get column name
    sprintf(key, "TTYPE%i", column);
    GetStringKey(key, result.columnName);
	
    return true;
}

/*
read the nth FITS Bintable column and return dpStringList
*/
bool Fits::GetBintableColumn(int column, dpStringList &result) {
    bool retValue = false;
    int tfields;
    if ((column < 1) ||
        (!GetIntKey("TFIELDS", &tfields)) ||
        (tfields < column))
    {
        return false;
    }

    // go through the TFORMi keywords and count the bytes
    int bytes  = 0,
        width  = 0,
        repeat = 0;
    char fieldtype;
    for (int i = 1; i < column; i++) {
        if (!tfieldWidth(i, &width, &repeat, &fieldtype)) {
            return false;
        }
        bytes += repeat * width;
    }
    if (!tfieldWidth(column, &width, &repeat, &fieldtype)) {
        return false;
    }
    width *= repeat;

    if (fieldtype == 'A') {
        for (int y = 0; y < Naxis(2); y++) {
            dpString t;
            for (int x = bytes; x < bytes + width; x++) {
                t.append(1, (char)i1data[C_I(x, y)]);
            }
            result.push_back(t);
        }
        retValue = true;
    }

    // get column name
    char key[9],
         value[72];
    sprintf(key, "TTYPE%i", column);

    GetStringKey(key, value);
    result.setColumnName(value);

    return retValue;
}

nodeEnum Fits::GetBintableType(int column) {
    int tfields;
    if ((column < 1) ||
        (!GetIntKey("TFIELDS", &tfields)) ||
        (tfields < column))
    {
        return typeUnknown;
    }

    // go through the TFORMi keywords and count the bytes
    int bytes  = 0,
        width  = 0,
        repeat = 0;
    char fieldtype;
    for (int i = 1; i < column; i++) {
        if (!tfieldWidth(i, &width, &repeat, &fieldtype)) {
            return typeUnknown;
        }
        bytes += repeat * width;
    }
    if (!tfieldWidth(column, &width, &repeat, &fieldtype)) {
        return typeUnknown;
    }
    width *= repeat;

    nodeEnum type = typeUnknown;
    switch (fieldtype) {
        case 'A':
            type = typeStrarr;
            break;
        case 'B':
        case 'L':
        case 'I':
        case 'J':
        case 'K':
        case 'E':
        case 'D':
        case 'C':
        case 'M':
            type = typeFits;
            break;
        default:
            type = typeUnknown;
            break;
    }

    return type;
}

/*
When using this function, create a new Fits and delete it afterwards!
Otherwise header information for the first (primary) header could be corrupted.
*/
int  Fits::CountExtensions(const char *fname) {
    int ext = 1;

    // open file
    if (!OpenFITS(fname))
        return -1;

    // read header
    while (ReadFitsExtensionHeader(ext, TRUE) > 0) {
        ext++;
    }


    // close file
    CloseFITS();

    return ext-1;
}

/*
When using this function, create a new Fits and delete it afterwards!
Otherwise header information for the first (primary) header could be corrupted.
*/
int Fits::FindExtensionByName(const char *fname, const char *extname) {
	int ext = 1;
	char extensionName[81];

	if (!OpenFITS(fname))
		return -1;

// read header
    while (ReadFitsExtensionHeader(ext, TRUE) > 0) {
		if (GetStringKey("EXTNAME", extensionName)) {
			dpString s(extensionName);
			s.strtrim(0);
			if (strcasecmp(extname, s.c_str()) == 0) {
				CloseFITS();
				return ext;
			}
		}
		ext++;
	}
	CloseFITS();

	return -1;
}

/*
When using this function, create a new Fits and delete it afterwards!
Otherwise header information for the first (primary) header could be corrupted.
*/
dpStringList Fits::ListFitsExtensions(const char *fname) {
	int ext = 1;
	char extensionName[81];
	dpStringList result;

	if (!OpenFITS(fname))
		return result;

// read header
    while (ReadFitsExtensionHeader(ext, TRUE) > 0) {
		if (GetStringKey("EXTNAME", extensionName)) {
			dpString s(extensionName);
			s.strtrim(0);
			result.append(s);
        } else {
            result.append(dpString::number(ext));
        }
		ext++;
	}
	CloseFITS();

	return result;
}

int Fits::FindColumnByName(const char *colname) {
	char columnName[81], columnKey[9];
	int rv = -1;
	int i = 1;
	bool found = FALSE;

	i = 1;
	while (!found) {
		sprintf(columnKey, "TTYPE%i", i);
		if (!GetStringKey(columnKey, columnName)) {
				return -1;
		}
		dpString s(columnName);
		s.strtrim(0);
		found = (strcasecmp(colname, s.c_str()) == 0);
		if (found) {
			return i;
		}
		i++;
		if (i > 999) {
			return -1;
		}
	}

	return -1;
}

dpStringList Fits::ListTableColumns(const char *fname, const int extension) {
	int column = 1;
	char columnKey[9];
	char columnName[81];
	dpStringList result;
	bool found = TRUE;

	if (!OpenFITS(fname))
		return result;

// read header
    if (ReadFitsExtensionHeader(extension, TRUE) > 0) {
		while (found) {
			sprintf(columnKey, "TTYPE%i", column);
			if (GetStringKey(columnKey, columnName)) {
				dpString s(columnName);
				s.strtrim(0);
				result.append(s);
			} else {
				found = FALSE;
			}
			column++;
			if (column > 999) {
				found = FALSE;
			}
		}
	}
	CloseFITS();

	return result;
}

int Fits::CountTableColumns(const char *fname, const int extension) {
    int  column = 1;
    char columnKey[9],
         columnName[81];
    bool found = TRUE;

    if (!OpenFITS(fname))
        return -1;

    // read header
    if (ReadFitsExtensionHeader(extension, TRUE) > 0) {
        while (found) {
            sprintf(columnKey, "TTYPE%i", column);
            if (!GetStringKey(columnKey, columnName)) {
                found = FALSE;
            }
            column++;
            if (column > 999) {
                found = FALSE;
            }
        }
    }
    CloseFITS();

    return column-1;
}

/*!
Write a fits file
*/

bool Fits::WriteFITS(const char *fname) {
// open file
	if (!CreateFITS(fname)) return FALSE;

// write header
	if (!updateHeader()) return FALSE;
    if (!WriteFitsHeader(fd)) return FALSE;

// write data
    if (!WriteFITSData()) return FALSE;

// close file
	CloseFITS();

// everything ok
	strncpy(FileName, fname, 255);
	return TRUE;
}

/*!
Write a FITS extension
*/
bool Fits::WriteFITSExtension(const char *fname) {
    char s[7];
    dpint64 pos;
    char w[2880];
    int i;

// Check of file exists already, and is a uncompressed FITS file
    if ((fd = fopen(fname, "rb")) != NULL) {
        // Yes. Is this a FITS file?
        fread(s, 1, 6, fd);
        s[6] = 0;
        fclose(fd);
        if (strncmp(s, "SIMPLE", 6) != 0) {
            return FALSE;
        }
    }
    if ((fd = fopen(fname, "ab")) == NULL) {
        return FALSE;
    }
    ro = FALSE;
    fseek(fd, 0L, SEEK_END);

// we are at the end of the file already. See if we have to pad 0's...
    pos = ftell(fd);
    if (pos == 0) {
        fwrite(SIMPLE_T, 80, 1, fd);
        fwrite(FITS_NAXIS0, 80, 1, fd);
        fwrite(FITS_BITPIX8, 80, 1, fd);
        fwrite(FITS_END, 80, 1, fd);
        for (i = 0; i < 32; i++) fwrite(FITS_EMPTY, 80, 1, fd);
// write an empty primary FITS header
    } else if ((pos % 2880) != 0) {
        fwrite(w, 2880 - (pos % 2880), 1, fd);
    }
// Set PCOUNT and GCOUNT header keys (required by the FITS standard)
    SetIntKey("PCOUNT", 0, "size of special data area");
    SetIntKey("GCOUNT", 1, "one data group (required keyword)");

// Write the new header
    fwrite(EXTENT_T, 1, 80, fd);
    fwrite(header+80, 1, HeaderLength-80, fd);

//...and the data
    if (!WriteFITSData()) {
        return FALSE;
    }

    CloseFITS();

    return TRUE;
}

/*!
Update Header values
*/

bool Fits::updateHeader() {
	SetIntKey("BITPIX", (int)membits);
	SetIntKey("NAXIS", naxis[0]);
	if (naxis[0] > 0) {
		SetIntKey("NAXIS1", naxis[1]);
	} else DeleteKey("NAXIS1");
	if (naxis[0] > 1) {
		SetIntKey("NAXIS2", naxis[2]);
	} else DeleteKey("NAXIS2");
	if (naxis[0] > 2)
		SetIntKey("NAXIS3", naxis[3]);
	else DeleteKey("NAXIS3");
	if (membits > 0) {
		SetFloatKey("BSCALE", bscale);
		SetFloatKey("BZERO", bzero);
	} else {
		DeleteKey("BSCALE");
		DeleteKey("BZERO");
	}
/*
	if ((naxis[0] > 1) && (hasRefPix())) {
		char value[10];
		DeleteKey("CD1_1");
		DeleteKey("CD1_2");
		DeleteKey("CD2_1");
		DeleteKey("CD2_2");
		SetFloatKey("CROTA1", crot);
		SetFloatKey("CROTA2", crot);
		if (strlen(crtype) > 0) {
			sprintf(value, "RA--%s", crtype);
			SetStringKey("CTYPE1", value);
			sprintf(value, "DEC-%s", crtype);
			SetStringKey("CTYPE2", value);
		}
	} else {
		char key[10];
		for (int i = naxis[0]+1; i <= MAXNAXIS; i++) {
			sprintf(key, "CRPIX%i", i);
			DeleteKey(key);
			sprintf(key, "CRVAL%i", i);
			DeleteKey(key);
			sprintf(key, "CDELT%i", i);
			DeleteKey(key);
			sprintf(key, "CTYPE%i", i);
			DeleteKey(key);
			sprintf(key, "CUNIT%i", i);
			DeleteKey(key);
		}
		DeleteKey("CD1_1");
		DeleteKey("CD1_2");
		DeleteKey("CD2_1");
		DeleteKey("CD2_2");
	}
*/
	return TRUE;
}

/*!
Update local variables to that of the FITS header
*/

bool Fits::getHeaderInformation() {
	int iv, i, intvalue;
	double v;
	
	if (!GetIntKey("BITPIX", &iv)) return FALSE;
	filebits = membits = (FitsBitpix)iv;
	if (!GetIntKey("NAXIS", &intvalue)) return FALSE;
    naxis[0] = (dpint64)intvalue;
	for (i = 0; i < MAXNAXIS; i++) {
		naxis[i + 1] = 1;
	}
	intvalue = 0;
	GetIntKey("NAXIS1", &intvalue);
    if (intvalue > 1) naxis[1] = (dpint64)intvalue;
	intvalue = 0;
	GetIntKey("NAXIS2", &intvalue);
    if (intvalue > 1) naxis[2] = (dpint64)intvalue;
	intvalue = 0;
	GetIntKey("NAXIS3", &intvalue);
    if (intvalue > 1) naxis[3] = (dpint64)intvalue;
	if (!GetFloatKey("BSCALE", &v)) bscale = 1.0;
	else bscale = v;
	if (!GetFloatKey("BZERO", &v)) bzero = 0.0;
	else bzero = v;

// Paranoia
	if (naxis[3] < 2) {
		naxis[3] = 1;
		naxis[0] = 2;
	}
// even more paranoia
	if (naxis[0] > MAXNAXIS) naxis[0] = MAXNAXIS;

	if (naxis[0] == 2) naxis[3] = 1;
	if (bscale == 0.0) {
		bscale = 1.0;
		bzero = 0.0;
	}

// more precise, at least for the first two axis
	wcsinfo info;
	info = readWCSinfo(*this);
//	crot = info.rot;
	
//	if (info.xinc != getCDELT(1)) SetFloatKey("CDELT1", info.xinc);
//	if (info.yinc != getCDELT(2)) SetFloatKey("CDELT2", info.yinc);
	
	strncpy(crtype, info.type, 9);

	return TRUE;
}

/*!
Find out if the header represents SHARP I data: This is the case, if:
1> The keys INSTRUME and BITPIX do exist and have "SHARPI  " and 16, respectively
2> The keys BSCALE and BZERO don't exist.
*/

bool Fits::isSHARPIdata() {
	char instrument[81], imagetyp[81];
	double bscale, bzero;
	int bitpix;

	if ((GetStringKey("INSTRUME", instrument)) && (GetIntKey("BITPIX", &bitpix)) && (GetStringKey("IMAGETYP", imagetyp))) {
		if ((!GetFloatKey("BSCALE", &bscale)) && (!GetFloatKey("BZERO", &bzero))) {
			instrument[5] = 0;
			if ((strcmp(instrument, "SHARP") == 0) && (strcmp(imagetyp, "INTEGER ") == 0) && (bitpix == 16)) return TRUE;
		}
	}
	return FALSE;
}

/*!
Convert SHARP I data to valid FITS format:
SHARP I data is unsigned short, which does not exist in FITS standard. So
we subtract 32767 from each pixel and typecast to signed short. The data values
represent the correct values if we also set bzero to 32767 and bscale to 1.0.
*/

void Fits::convertSHARPIdata() {
	unsigned short *usdata = (unsigned short *)i2data;
    dpint64 i;

	for (i = 0; i < Nelements(); i++) i2data[i] = (signed short)((long)usdata[i] - 32767);
	bzero = 32767.0;
	bscale = 1.0;
}

struct bmpfileheader {
    char bfType[2];
    unsigned long   bfSize; 
    unsigned short    bfReserved1; 
    unsigned short    bfReserved2; 
    unsigned long   bfOffBits;
};

typedef struct {
	unsigned long   biSize; 
    long    biWidth; 
    long    biHeight; 
    unsigned short    biPlanes; 
    unsigned short    biBitCount; 
    unsigned long  biCompression; 
    unsigned long  biSizeImage; 
    long   biXPelsPerMeter; 
    long   biYPelsPerMeter; 
    unsigned long  biClrUsed; 
    unsigned long  biClrImportant;
} bmpinfo;

/*!
Utility function to swap the bytes in a BMP header.
*/
void swapBMPBytes(bmpfileheader *h, bmpinfo *b) {
    char *_tmp;
    char tempr;

    _tmp = (char *)h;
    SWAP(_tmp[4], _tmp[7]);
    SWAP(_tmp[5], _tmp[6]);
    SWAP(_tmp[8], _tmp[9]);
    SWAP(_tmp[10], _tmp[11]);
    SWAP(_tmp[12], _tmp[15]);
    SWAP(_tmp[13], _tmp[14]);

	_tmp = (char *)b;
    SWAP(_tmp[0], _tmp[3]);
    SWAP(_tmp[1], _tmp[2]);
    SWAP(_tmp[4], _tmp[7]);
    SWAP(_tmp[5], _tmp[6]);
    SWAP(_tmp[8], _tmp[11]);
    SWAP(_tmp[9], _tmp[10]);
    SWAP(_tmp[12], _tmp[13]);
    SWAP(_tmp[14], _tmp[15]);
    SWAP(_tmp[16], _tmp[19]);
    SWAP(_tmp[17], _tmp[18]);
    SWAP(_tmp[20], _tmp[23]);
    SWAP(_tmp[21], _tmp[22]);
    SWAP(_tmp[24], _tmp[27]);
    SWAP(_tmp[25], _tmp[26]);
    SWAP(_tmp[28], _tmp[31]);
    SWAP(_tmp[29], _tmp[30]);
    SWAP(_tmp[32], _tmp[35]);
    SWAP(_tmp[33], _tmp[34]);
    SWAP(_tmp[36], _tmp[39]);
    SWAP(_tmp[37], _tmp[38]);
}

/*!
Write a BMP file.
*/

bool Fits::WriteBMP(const char *fname) {
	FILE *fd;
	bmpfileheader h;
	bmpinfo b;
	long x, y;
	unsigned char color[3];
	dpint64 off;

	off = Naxis(1) % 4;

	h.bfType[0] = 'B';
	h.bfType[1] = 'M';
	h.bfSize = 14 + 40 + Nelements() * 3 + off * Naxis(2);
	h.bfReserved1 = 0;
	h.bfReserved2 = 0;
	h.bfOffBits = 14 + 40;

	b.biSize = 40;
	b.biWidth = Naxis(1);
	b.biHeight = Naxis(2);
	b.biPlanes = 1;
	b.biBitCount = 24;
	b.biCompression = 0;
	b.biSizeImage = Nelements() * 3 + off * Naxis(2);
	b.biXPelsPerMeter = 2834;
	b.biYPelsPerMeter = 2834;
	b.biClrUsed = 0;
	b.biClrImportant = 0;

/* Swap bytes if necessary */
	if (getByteOrder()) swapBMPBytes(&h, &b);

	if ((fd = fopen(fname, "w+b")) == NULL) {
		dp_output("Fits::WriteBMP: Could not open file %s for writing\n", fname);
		return FALSE;
	}

	fwrite(h.bfType, 2, 1, fd);
	fwrite(&h.bfSize, 4, 1, fd);
	fwrite(&h.bfReserved1, 2, 1, fd);
	fwrite(&h.bfReserved2, 2, 1, fd);
	fwrite(&h.bfOffBits, 4, 1, fd);
	fwrite(&b, 40, 1, fd);

	for (y = 0; y < Naxis(2); y++) {
		for (x = 0; x < Naxis(1); x++) {
			color[0] = color[1] = color[2] = (unsigned char)ValueAt(C_I(x, y));
			fwrite(color, sizeof(color), 1, fd);
		}
		if (off) fwrite(color, off, 1, fd);
	}
	fclose(fd);

	return TRUE;
}
/*!
Write a color BMP file.
*/

bool Fits::WriteBMP(const char *fname, Fits &red, Fits &green, Fits &blue) {
	FILE *fd;
	bmpfileheader h;
	bmpinfo b;
	long x, y, n;
	unsigned char color[3];
	dpint64 off;

/* Consistency check */
	if ((!red.matches(green)) || (!red.matches(blue))) {
		dp_output("Fits::WriteBMP: The arrays don't match in size\n");
		return FALSE;
	}
	off = red.Naxis(1) % 4;

	h.bfType[0] = 'B';
	h.bfType[1] = 'M';
	h.bfSize = 14 + 40 + red.Nelements() * 3 + off * red.Naxis(2);
	h.bfReserved1 = 0;
	h.bfReserved2 = 0;
	h.bfOffBits = 14 + 40;

	b.biSize = 40;
	b.biWidth = red.Naxis(1);
	b.biHeight = red.Naxis(2);
	b.biPlanes = 1;
	b.biBitCount = 24;
	b.biCompression = 0;
	b.biSizeImage = red.Nelements() * 3 + off * red.Naxis(2);
	b.biXPelsPerMeter = 2834;
	b.biYPelsPerMeter = 2834;
	b.biClrUsed = 0;
	b.biClrImportant = 0;

/* Swap bytes if necessary */
	if (getByteOrder()) swapBMPBytes(&h, &b);

	if ((fd = fopen(fname, "w+b")) == NULL) {
		dp_output("Fits::WriteBMP: Could not open file %s for writing\n", fname);
		return FALSE;
	}

	fwrite(h.bfType, 2, 1, fd);
	fwrite(&h.bfSize, 4, 1, fd);
	fwrite(&h.bfReserved1, 2, 1, fd);
	fwrite(&h.bfReserved2, 2, 1, fd);
	fwrite(&h.bfOffBits, 4, 1, fd);
	fwrite(&b, 40, 1, fd);

	for (y = 0; y < red.Naxis(2); y++) {
		for (x = 0; x < red.Naxis(1); x++) {
			n = red.C_I(x, y);
			color[2] = (unsigned char)red.ValueAt(n);
			color[1] = (unsigned char)green.ValueAt(n);
			color[0] = (unsigned char)blue.ValueAt(n);
			fwrite(color, sizeof(color), 1, fd);
		}
		if (off) fwrite(color, off, 1, fd);
	}
	fclose(fd);

	return TRUE;
}