File: drvrmem.c

package info (click to toggle)
cfitsio 3.470-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 14,484 kB
  • sloc: ansic: 106,145; yacc: 4,883; sh: 3,259; fortran: 2,613; lex: 504; makefile: 162
file content (1301 lines) | stat: -rw-r--r-- 39,553 bytes parent folder | download | duplicates (7)
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
/*  This file, drvrmem.c, contains driver routines for memory files.        */

/*  The FITSIO software was written by William Pence at the High Energy    */
/*  Astrophysic Science Archive Research Center (HEASARC) at the NASA      */
/*  Goddard Space Flight Center.                                           */

#include <string.h>
#include <stdlib.h>
#include <stddef.h>  /* apparently needed to define size_t */
#include "fitsio2.h"

#if HAVE_BZIP2
#include "bzlib.h"
#endif

/* prototype for .Z file uncompression function in zuncompress.c */
int zuncompress2mem(char *filename, 
             FILE *diskfile, 
             char **buffptr, 
             size_t *buffsize, 
             void *(*mem_realloc)(void *p, size_t newsize),
             size_t *filesize,
             int *status);

#if HAVE_BZIP2
/* prototype for .bz2 uncompression function (in this file) */
void bzip2uncompress2mem(char *filename, FILE *diskfile, int hdl,
                         size_t* filesize, int* status);
#endif


#define RECBUFLEN 1000

static char stdin_outfile[FLEN_FILENAME];

typedef struct    /* structure containing mem file structure */ 
{
    char **memaddrptr;   /* Pointer to memory address pointer; */
                         /* This may or may not point to memaddr. */
    char *memaddr;       /* Pointer to starting memory address; may */
                         /* not always be used, so use *memaddrptr instead */
    size_t *memsizeptr;  /* Pointer to the size of the memory allocation. */
                         /* This may or may not point to memsize. */
    size_t memsize;      /* Size of the memory allocation; this may not */
                         /* always be used, so use *memsizeptr instead. */
    size_t deltasize;    /* Suggested increment for reallocating memory */
    void *(*mem_realloc)(void *p, size_t newsize);  /* realloc function */
    LONGLONG currentpos;   /* current file position, relative to start */
    LONGLONG fitsfilesize; /* size of the FITS file (always <= *memsizeptr) */
    FILE *fileptr;      /* pointer to compressed output disk file */
} memdriver;

static memdriver memTable[NMAXFILES];  /* allocate mem file handle tables */

/*--------------------------------------------------------------------------*/
int mem_init(void)
{
    int ii;

    for (ii = 0; ii < NMAXFILES; ii++) /* initialize all empty slots in table */
    {
       memTable[ii].memaddrptr = 0;
       memTable[ii].memaddr = 0;
    }
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_setoptions(int options)
{
  /* do something with the options argument, to stop compiler warning */
  options = 0;
  return(options);
}
/*--------------------------------------------------------------------------*/
int mem_getoptions(int *options)
{
  *options = 0;
  return(0);
}
/*--------------------------------------------------------------------------*/
int mem_getversion(int *version)
{
    *version = 10;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_shutdown(void)
{
  return(0);
}
/*--------------------------------------------------------------------------*/
int mem_create(char *filename, int *handle)
/*
  Create a new empty memory file for subsequent writes.
  The file name is ignored in this case.
*/
{
    int status;

    /* initially allocate 1 FITS block = 2880 bytes */
    status = mem_createmem(2880L, handle);

    if (status)
    {
        ffpmsg("failed to create empty memory file (mem_create)");
        return(status);
    }

    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_create_comp(char *filename, int *handle)
/*
  Create a new empty memory file for subsequent writes.
  Also create an empty compressed .gz file.  The memory file
  will be compressed and written to the disk file when the file is closed.
*/
{
    FILE *diskfile;
    char mode[4];
    int  status;

    /* first, create disk file for the compressed output */


    if ( !strcmp(filename, "-.gz") || !strcmp(filename, "stdout.gz") ||
         !strcmp(filename, "STDOUT.gz") )
    {
       /* special case: create uncompressed FITS file in memory, then
          compress it an write it out to 'stdout' when it is closed.  */

       diskfile = stdout;
    }
    else
    {
        /* normal case: create disk file for the compressed output */

        strcpy(mode, "w+b");    /* create file with read-write */

        diskfile = fopen(filename, "r"); /* does file already exist? */

        if (diskfile)
        {
            fclose(diskfile);         /* close file and exit with error */
            return(FILE_NOT_CREATED); 
        }

#if MACHINE == ALPHAVMS || MACHINE == VAXVMS
        /* specify VMS record structure: fixed format, 2880 byte records */
        /* but force stream mode access to enable random I/O access      */
        diskfile = fopen(filename, mode, "rfm=fix", "mrs=2880", "ctx=stm"); 
#else
        diskfile = fopen(filename, mode); 
#endif

        if (!(diskfile))           /* couldn't create file */
        {
            return(FILE_NOT_CREATED); 
        }
    }

    /* now create temporary memory file */

    /* initially allocate 1 FITS block = 2880 bytes */
    status = mem_createmem(2880L, handle);

    if (status)
    {
        ffpmsg("failed to create empty memory file (mem_create_comp)");
        return(status);
    }

    memTable[*handle].fileptr = diskfile;

    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_openmem(void **buffptr,   /* I - address of memory pointer          */
                size_t *buffsize, /* I - size of buffer, in bytes           */
                size_t deltasize, /* I - increment for future realloc's     */
                void *(*memrealloc)(void *p, size_t newsize),  /* function  */
                int *handle)
/* 
  lowest level routine to open a pre-existing memory file.
*/
{
    int ii;

    *handle = -1;
    for (ii = 0; ii < NMAXFILES; ii++)  /* find empty slot in handle table */
    {
        if (memTable[ii].memaddrptr == 0)
        {
            *handle = ii;
            break;
        }
    }
    if (*handle == -1)
       return(TOO_MANY_FILES);    /* too many files opened */

    memTable[ii].memaddrptr = (char **) buffptr; /* pointer to start addres */
    memTable[ii].memsizeptr = buffsize;     /* allocated size of memory */
    memTable[ii].deltasize = deltasize;     /* suggested realloc increment */
    memTable[ii].fitsfilesize = *buffsize;  /* size of FITS file (upper limit) */
    memTable[ii].currentpos = 0;            /* at beginning of the file */
    memTable[ii].mem_realloc = memrealloc;  /* memory realloc function */
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_createmem(size_t msize, int *handle)
/* 
  lowest level routine to allocate a memory file.
*/
{
    int ii;

    *handle = -1;
    for (ii = 0; ii < NMAXFILES; ii++)  /* find empty slot in handle table */
    {
        if (memTable[ii].memaddrptr == 0)
        {
            *handle = ii;
            break;
        }
    }
    if (*handle == -1)
       return(TOO_MANY_FILES);    /* too many files opened */

    /* use the internally allocated memaddr and memsize variables */
    memTable[ii].memaddrptr = &memTable[ii].memaddr;
    memTable[ii].memsizeptr = &memTable[ii].memsize;

    /* allocate initial block of memory for the file */
    if (msize > 0)
    {
        memTable[ii].memaddr = (char *) malloc(msize); 
        if ( !(memTable[ii].memaddr) )
        {
            ffpmsg("malloc of initial memory failed (mem_createmem)");
            return(FILE_NOT_OPENED);
        }
    }

    /* set initial state of the file */
    memTable[ii].memsize = msize;
    memTable[ii].deltasize = 2880;
    memTable[ii].fitsfilesize = 0;
    memTable[ii].currentpos = 0;
    memTable[ii].mem_realloc = realloc;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_truncate(int handle, LONGLONG filesize)
/*
  truncate the file to a new size
*/
{
    char *ptr;

    /* call the memory reallocation function, if defined */
    if ( memTable[handle].mem_realloc )
    {    /* explicit LONGLONG->size_t cast */
        ptr = (memTable[handle].mem_realloc)(
                                *(memTable[handle].memaddrptr),
                                 (size_t) filesize);
        if (!ptr)
        {
            ffpmsg("Failed to reallocate memory (mem_truncate)");
            return(MEMORY_ALLOCATION);
        }

        /* if allocated more memory, initialize it to zero */
        if ( filesize > *(memTable[handle].memsizeptr) )
        {
             memset(ptr + *(memTable[handle].memsizeptr),
                    0,
                ((size_t) filesize) - *(memTable[handle].memsizeptr) );
        }

        *(memTable[handle].memaddrptr) = ptr;
        *(memTable[handle].memsizeptr) = (size_t) (filesize);
    }

    memTable[handle].currentpos = filesize;
    memTable[handle].fitsfilesize = filesize;
    return(0);
}
/*--------------------------------------------------------------------------*/
int stdin_checkfile(char *urltype, char *infile, char *outfile)
/*
   do any special case checking when opening a file on the stdin stream
*/
{
    if (strlen(outfile))
    {
        stdin_outfile[0] = '\0';
        strncat(stdin_outfile,outfile,FLEN_FILENAME-1); /* an output file is specified */
	strcpy(urltype,"stdinfile://");
    }
    else
        *stdin_outfile = '\0';  /* no output file was specified */

    return(0);
}
/*--------------------------------------------------------------------------*/
int stdin_open(char *filename, int rwmode, int *handle)
/*
  open a FITS file from the stdin file stream by copying it into memory
  The file name is ignored in this case.
*/
{
    int status;
    char cbuff;

    if (*stdin_outfile)
    {
      /* copy the stdin stream to the specified disk file then open the file */

      /* Create the output file */
      status =  file_create(stdin_outfile,handle);

      if (status)
      {
        ffpmsg("Unable to create output file to copy stdin (stdin_open):");
        ffpmsg(stdin_outfile);
        return(status);
      }
 
      /* copy the whole stdin stream to the file */
      status = stdin2file(*handle);
      file_close(*handle);

      if (status)
      {
        ffpmsg("failed to copy stdin to file (stdin_open)");
        ffpmsg(stdin_outfile);
        return(status);
      }

      /* reopen file with proper rwmode attribute */
      status = file_open(stdin_outfile, rwmode, handle);
    }
    else
    {
   
      /* get the first character, then put it back */
      cbuff = fgetc(stdin);
      ungetc(cbuff, stdin);
    
      /* compressed files begin with 037 or 'P' */
      if (cbuff == 31 || cbuff == 75)
      {
         /* looks like the input stream is compressed */
         status = mem_compress_stdin_open(filename, rwmode, handle);
	 
      }
      else
      {
        /* copy the stdin stream into memory then open file in memory */

        if (rwmode != READONLY)
        {
          ffpmsg("cannot open stdin with WRITE access");
          return(READONLY_FILE);
        }

        status = mem_createmem(2880L, handle);

        if (status)
        {
          ffpmsg("failed to create empty memory file (stdin_open)");
          return(status);
        }
 
        /* copy the whole stdin stream into memory */
        status = stdin2mem(*handle);

        if (status)
        {
          ffpmsg("failed to copy stdin into memory (stdin_open)");
          free(memTable[*handle].memaddr);
        }
      }
    }

    return(status);
}
/*--------------------------------------------------------------------------*/
int stdin2mem(int hd)  /* handle number */
/*
  Copy the stdin stream into memory.  Fill whatever amount of memory
  has already been allocated, then realloc more memory if necessary.
*/
{
    size_t nread, memsize, delta;
    LONGLONG filesize;
    char *memptr;
    char simple[] = "SIMPLE";
    int c, ii, jj;

    memptr = *memTable[hd].memaddrptr;
    memsize = *memTable[hd].memsizeptr;
    delta = memTable[hd].deltasize;

    filesize = 0;
    ii = 0;

    for(jj = 0; (c = fgetc(stdin)) != EOF && jj < 2000; jj++)
    {
       /* Skip over any garbage at the beginning of the stdin stream by */
       /* reading 1 char at a time, looking for 'S', 'I', 'M', 'P', 'L', 'E' */
       /* Give up if not found in the first 2000 characters */

       if (c == simple[ii])
       {
           ii++;
           if (ii == 6)   /* found the complete string? */
           {
              memcpy(memptr, simple, 6);  /* copy "SIMPLE" to buffer */
              filesize = 6;
              break;
           }
       }
       else
          ii = 0;  /* reset search to beginning of the string */
    }

   if (filesize == 0)
   {
       ffpmsg("Couldn't find the string 'SIMPLE' in the stdin stream.");
       ffpmsg("This does not look like a FITS file.");
       return(FILE_NOT_OPENED);
   }

    /* fill up the remainder of the initial memory allocation */
    nread = fread(memptr + 6, 1, memsize - 6, stdin);
    nread += 6;  /* add in the 6 characters in 'SIMPLE' */

    if (nread < memsize)    /* reached the end? */
    {
       memTable[hd].fitsfilesize = nread;
       return(0);
    }

    filesize = nread;

    while (1)
    {
        /* allocate memory for another FITS block */
        memptr = realloc(memptr, memsize + delta);

        if (!memptr)
        {
            ffpmsg("realloc failed while copying stdin (stdin2mem)");
            return(MEMORY_ALLOCATION);
        }
        memsize += delta;

        /* read another FITS block */
        nread = fread(memptr + filesize, 1, delta, stdin);

        filesize += nread;

        if (nread < delta)    /* reached the end? */
           break;
    }

     memTable[hd].fitsfilesize = filesize;
    *memTable[hd].memaddrptr = memptr;
    *memTable[hd].memsizeptr = memsize;

    return(0);
}
/*--------------------------------------------------------------------------*/
int stdin2file(int handle)  /* handle number */
/*
  Copy the stdin stream to a file.  .
*/
{
    size_t nread;
    char simple[] = "SIMPLE";
    int c, ii, jj, status;
    char recbuf[RECBUFLEN];

    ii = 0;
    for(jj = 0; (c = fgetc(stdin)) != EOF && jj < 2000; jj++)
    {
       /* Skip over any garbage at the beginning of the stdin stream by */
       /* reading 1 char at a time, looking for 'S', 'I', 'M', 'P', 'L', 'E' */
       /* Give up if not found in the first 2000 characters */

       if (c == simple[ii])
       {
           ii++;
           if (ii == 6)   /* found the complete string? */
           {
              memcpy(recbuf, simple, 6);  /* copy "SIMPLE" to buffer */
              break;
           }
       }
       else
          ii = 0;  /* reset search to beginning of the string */
    }

   if (ii != 6)
   {
       ffpmsg("Couldn't find the string 'SIMPLE' in the stdin stream");
       return(FILE_NOT_OPENED);
   }

    /* fill up the remainder of the buffer */
    nread = fread(recbuf + 6, 1, RECBUFLEN - 6, stdin);
    nread += 6;  /* add in the 6 characters in 'SIMPLE' */

    status = file_write(handle, recbuf, nread);
    if (status)
       return(status);

    /* copy the rest of stdin stream */
    while(0 != (nread = fread(recbuf,1,RECBUFLEN, stdin)))
    {
        status = file_write(handle, recbuf, nread);
        if (status)
           return(status);
    }

    return(status);
}
/*--------------------------------------------------------------------------*/
int stdout_close(int handle)
/*
  copy the memory file to stdout, then free the memory
*/
{
    int status = 0;

    /* copy from memory to standard out.  explicit LONGLONG->size_t cast */
    if(fwrite(memTable[handle].memaddr, 1,
              ((size_t) memTable[handle].fitsfilesize), stdout) !=
              (size_t) memTable[handle].fitsfilesize )
    {
                ffpmsg("failed to copy memory file to stdout (stdout_close)");
                status = WRITE_ERROR;
    }

    free( memTable[handle].memaddr );   /* free the memory */
    memTable[handle].memaddrptr = 0;
    memTable[handle].memaddr = 0;
    return(status);
}
/*--------------------------------------------------------------------------*/
int mem_compress_openrw(char *filename, int rwmode, int *hdl)
/*
  This routine opens the compressed diskfile and creates an empty memory
  buffer with an appropriate size, then calls mem_uncompress2mem. It allows
  the memory 'file' to be opened with READWRITE access.
*/
{
   return(mem_compress_open(filename, READONLY, hdl));  
}
/*--------------------------------------------------------------------------*/
int mem_compress_open(char *filename, int rwmode, int *hdl)
/*
  This routine opens the compressed diskfile and creates an empty memory
  buffer with an appropriate size, then calls mem_uncompress2mem.
*/
{
    FILE *diskfile;
    int status, estimated = 1;
    unsigned char buffer[4];
    size_t finalsize, filesize;
    LONGLONG llsize = 0;
    unsigned int modulosize;
    char *ptr;

    if (rwmode != READONLY)
    {
        ffpmsg(
  "cannot open compressed file with WRITE access (mem_compress_open)");
        ffpmsg(filename);
        return(READONLY_FILE);
    }

    /* open the compressed disk file */
    status = file_openfile(filename, READONLY, &diskfile);
    if (status)
    {
        ffpmsg("failed to open compressed disk file (compress_open)");
        ffpmsg(filename);
        return(status);
    }

    if (fread(buffer, 1, 2, diskfile) != 2)  /* read 2 bytes */
    {
        fclose(diskfile);
        return(READ_ERROR);
    }

    if (memcmp(buffer, "\037\213", 2) == 0)  /* GZIP */
    {
        /* the uncompressed file size is give at the end */
        /* of the file in the ISIZE field  (modulo 2^32) */

        fseek(diskfile, 0, 2);            /* move to end of file */
        filesize = ftell(diskfile);       /* position = size of file */
        fseek(diskfile, -4L, 1);          /* move back 4 bytes */
        fread(buffer, 1, 4L, diskfile);   /* read 4 bytes */

        /* have to worry about integer byte order */
	modulosize  = buffer[0];
	modulosize |= buffer[1] << 8;
	modulosize |= buffer[2] << 16;
	modulosize |= buffer[3] << 24;

/*
  the field ISIZE in the gzipped file header only stores 4 bytes and contains
  the uncompressed file size modulo 2^32.  If the uncompressed file size
  is less than the compressed file size (filesize), then one probably needs to
  add 2^32 = 4294967296 to the uncompressed file size, assuming that the gzip
  produces a compressed file that is smaller than the original file.

  But one must allow for the case of very small files, where the
  gzipped file may actually be larger then the original uncompressed file.
  Therefore, only perform the modulo 2^32 correction test if the compressed 
  file is greater than 10,000 bytes in size.  (Note: this threhold would
  fail only if the original file was greater than 2^32 bytes in size AND gzip 
  was able to compress it by more than a factor of 400,000 (!) which seems
  highly unlikely.)
  
  Also, obviously, this 2^32 modulo correction cannot be performed if the
  finalsize variable is only 32-bits long.  Typically, the 'size_t' integer
  type must be 8 bytes or larger in size to support data files that are 
  greater than 2 GB (2^31 bytes) in size.  
*/
        finalsize = modulosize;

        if (sizeof(size_t) > 4 && filesize > 10000) {
	    llsize = (LONGLONG) finalsize;  
	    /* use LONGLONG variable to suppress compiler warning */
            while (llsize <  (LONGLONG) filesize) llsize += 4294967296;

            finalsize = (size_t) llsize;
        }

        estimated = 0;  /* file size is known, not estimated */
    }
    else if (memcmp(buffer, "\120\113", 2) == 0)   /* PKZIP */
    {
        /* the uncompressed file size is give at byte 22 the file */

        fseek(diskfile, 22L, 0);            /* move to byte 22 */
        fread(buffer, 1, 4L, diskfile);   /* read 4 bytes */

        /* have to worry about integer byte order */
	modulosize  = buffer[0];
	modulosize |= buffer[1] << 8;
	modulosize |= buffer[2] << 16;
	modulosize |= buffer[3] << 24;
        finalsize = modulosize;

        estimated = 0;  /* file size is known, not estimated */
    }
    else if (memcmp(buffer, "\037\036", 2) == 0)  /* PACK */
        finalsize = 0;  /* for most methods we can't determine final size */
    else if (memcmp(buffer, "\037\235", 2) == 0)  /* LZW */
        finalsize = 0;  /* for most methods we can't determine final size */
    else if (memcmp(buffer, "\037\240", 2) == 0)  /* LZH */
        finalsize = 0;  /* for most methods we can't determine final size */
#if HAVE_BZIP2
    else if (memcmp(buffer, "BZ", 2) == 0)        /* BZip2 */
        finalsize = 0;  /* for most methods we can't determine final size */
#endif
    else
    {
        /* not a compressed file; this should never happen */
        fclose(diskfile);
        return(1);
    }

    if (finalsize == 0)  /* estimate uncompressed file size */
    {
            fseek(diskfile, 0, 2);   /* move to end of the compressed file */
            finalsize = ftell(diskfile);  /* position = size of file */
            finalsize = finalsize * 3;   /* assume factor of 3 compression */
    }

    fseek(diskfile, 0, 0);   /* move back to beginning of file */

    /* create a memory file big enough (hopefully) for the uncompressed file */
    status = mem_createmem(finalsize, hdl);

    if (status && estimated)
    {
        /* memory allocation failed, so try a smaller estimated size */
        finalsize = finalsize / 3;
        status = mem_createmem(finalsize, hdl);
    }

    if (status)
    {
        fclose(diskfile);
        ffpmsg("failed to create empty memory file (compress_open)");
        return(status);
    }

    /* uncompress file into memory */
    status = mem_uncompress2mem(filename, diskfile, *hdl);

    fclose(diskfile);

    if (status)
    {
        mem_close_free(*hdl);   /* free up the memory */
        ffpmsg("failed to uncompress file into memory (compress_open)");
        return(status);
    }

    /* if we allocated too much memory initially, then free it */
    if (*(memTable[*hdl].memsizeptr) > 
       (( (size_t) memTable[*hdl].fitsfilesize) + 256L) ) 
    {
        ptr = realloc(*(memTable[*hdl].memaddrptr), 
                     ((size_t) memTable[*hdl].fitsfilesize) );
        if (!ptr)
        {
            ffpmsg("Failed to reduce size of allocated memory (compress_open)");
            return(MEMORY_ALLOCATION);
        }

        *(memTable[*hdl].memaddrptr) = ptr;
        *(memTable[*hdl].memsizeptr) = (size_t) (memTable[*hdl].fitsfilesize);
    }

    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_compress_stdin_open(char *filename, int rwmode, int *hdl)
/*
  This routine reads the compressed input stream and creates an empty memory
  buffer, then calls mem_uncompress2mem.
*/
{
    int status;
    char *ptr;

    if (rwmode != READONLY)
    {
        ffpmsg(
  "cannot open compressed input stream with WRITE access (mem_compress_stdin_open)");
        return(READONLY_FILE);
    }
 
    /* create a memory file for the uncompressed file */
    status = mem_createmem(28800, hdl);

    if (status)
    {
        ffpmsg("failed to create empty memory file (compress_stdin_open)");
        return(status);
    }

    /* uncompress file into memory */
    status = mem_uncompress2mem(filename, stdin, *hdl);

    if (status)
    {
        mem_close_free(*hdl);   /* free up the memory */
        ffpmsg("failed to uncompress stdin into memory (compress_stdin_open)");
        return(status);
    }

    /* if we allocated too much memory initially, then free it */
    if (*(memTable[*hdl].memsizeptr) > 
       (( (size_t) memTable[*hdl].fitsfilesize) + 256L) ) 
    {
        ptr = realloc(*(memTable[*hdl].memaddrptr), 
                      ((size_t) memTable[*hdl].fitsfilesize) );
        if (!ptr)
        {
            ffpmsg("Failed to reduce size of allocated memory (compress_stdin_open)");
            return(MEMORY_ALLOCATION);
        }

        *(memTable[*hdl].memaddrptr) = ptr;
        *(memTable[*hdl].memsizeptr) = (size_t) (memTable[*hdl].fitsfilesize);
    }

    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_iraf_open(char *filename, int rwmode, int *hdl)
/*
  This routine creates an empty memory buffer, then calls iraf2mem to
  open the IRAF disk file and convert it to a FITS file in memeory.
*/
{
    int status;
    size_t filesize = 0;

    /* create a memory file with size = 0 for the FITS converted IRAF file */
    status = mem_createmem(filesize, hdl);
    if (status)
    {
        ffpmsg("failed to create empty memory file (mem_iraf_open)");
        return(status);
    }

    /* convert the iraf file into a FITS file in memory */
    status = iraf2mem(filename, memTable[*hdl].memaddrptr,
                      memTable[*hdl].memsizeptr, &filesize, &status);

    if (status)
    {
        mem_close_free(*hdl);   /* free up the memory */
        ffpmsg("failed to convert IRAF file into memory (mem_iraf_open)");
        return(status);
    }

    memTable[*hdl].currentpos = 0;           /* save starting position */
    memTable[*hdl].fitsfilesize=filesize;   /* and initial file size  */

    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_rawfile_open(char *filename, int rwmode, int *hdl)
/*
  This routine creates an empty memory buffer, writes a minimal
  image header, then copies the image data from the raw file into
  memory.  It will byteswap the pixel values if the raw array
  is in little endian byte order.
*/
{
    FILE *diskfile;
    fitsfile *fptr;
    short *sptr;
    int status, endian, datatype, bytePerPix, naxis;
    long dim[5] = {1,1,1,1,1}, ii, nvals, offset = 0;
    size_t filesize = 0, datasize;
    char rootfile[FLEN_FILENAME], *cptr = 0, *cptr2 = 0;
    void *ptr;

    if (rwmode != READONLY)
    {
        ffpmsg(
  "cannot open raw binary file with WRITE access (mem_rawfile_open)");
        ffpmsg(filename);
        return(READONLY_FILE);
    }

    cptr = strchr(filename, '[');   /* search for opening bracket [ */

    if (!cptr)
    {
        ffpmsg("binary file name missing '[' character (mem_rawfile_open)");
        ffpmsg(filename);
        return(URL_PARSE_ERROR);
    }

    *rootfile = '\0';
    strncat(rootfile, filename, cptr - filename);  /* store the rootname */

    cptr++;

    while (*cptr == ' ')
       cptr++;    /* skip leading blanks */

    /* Get the Data Type of the Image */

    if (*cptr == 'b' || *cptr == 'B')
    {
      datatype = BYTE_IMG;
      bytePerPix = 1;
    }
    else if (*cptr == 'i' || *cptr == 'I')
    {
      datatype = SHORT_IMG;
      bytePerPix = 2;
    }
    else if (*cptr == 'u' || *cptr == 'U')
    {
      datatype = USHORT_IMG;
      bytePerPix = 2;

    }
    else if (*cptr == 'j' || *cptr == 'J')
    {
      datatype = LONG_IMG;
      bytePerPix = 4;
    }  
    else if (*cptr == 'r' || *cptr == 'R' || *cptr == 'f' || *cptr == 'F')
    {
      datatype = FLOAT_IMG;
      bytePerPix = 4;
    }    
    else if (*cptr == 'd' || *cptr == 'D')
    {
      datatype = DOUBLE_IMG;
      bytePerPix = 8;
    }
    else
    {
        ffpmsg("error in raw binary file datatype (mem_rawfile_open)");
        ffpmsg(filename);
        return(URL_PARSE_ERROR);
    }

    cptr++;

    /* get Endian: Big or Little; default is same as the local machine */
    
    if (*cptr == 'b' || *cptr == 'B')
    {
        endian = 0;
        cptr++;
    }
    else if (*cptr == 'l' || *cptr == 'L')
    {
        endian = 1;
        cptr++;
    }
    else
        endian = BYTESWAPPED; /* byteswapped machines are little endian */

    /* read each dimension (up to 5) */

    naxis = 1;
    dim[0] = strtol(cptr, &cptr2, 10);
    
    if (cptr2 && *cptr2 == ',')
    {
      naxis = 2;
      dim[1] = strtol(cptr2+1, &cptr, 10);

      if (cptr && *cptr == ',')
      {
        naxis = 3;
        dim[2] = strtol(cptr+1, &cptr2, 10);

        if (cptr2 && *cptr2 == ',')
        {
          naxis = 4;
          dim[3] = strtol(cptr2+1, &cptr, 10);

          if (cptr && *cptr == ',')
            naxis = 5;
            dim[4] = strtol(cptr+1, &cptr2, 10);
        }
      }
    }

    cptr = maxvalue(cptr, cptr2);

    if (*cptr == ':')   /* read starting offset value */
        offset = strtol(cptr+1, 0, 10);

    nvals = dim[0] * dim[1] * dim[2] * dim[3] * dim[4];
    datasize = nvals * bytePerPix;
    filesize = nvals * bytePerPix + 2880;
    filesize = ((filesize - 1) / 2880 + 1) * 2880; 

    /* open the raw binary disk file */
    status = file_openfile(rootfile, READONLY, &diskfile);
    if (status)
    {
        ffpmsg("failed to open raw  binary file (mem_rawfile_open)");
        ffpmsg(rootfile);
        return(status);
    }

    /* create a memory file with corrct size for the FITS converted raw file */
    status = mem_createmem(filesize, hdl);
    if (status)
    {
        ffpmsg("failed to create memory file (mem_rawfile_open)");
        fclose(diskfile);
        return(status);
    }

    /* open this piece of memory as a new FITS file */
    ffimem(&fptr, (void **) memTable[*hdl].memaddrptr, &filesize, 0, 0, &status);

    /* write the required header keywords */
    ffcrim(fptr, datatype, naxis, dim, &status);

    /* close the FITS file, but keep the memory allocated */
    ffclos(fptr, &status);

    if (status > 0)
    {
        ffpmsg("failed to write basic image header (mem_rawfile_open)");
        fclose(diskfile);
        mem_close_free(*hdl);   /* free up the memory */
        return(status);
    }

    if (offset > 0)
       fseek(diskfile, offset, 0);   /* offset to start of the data */

    /* read the raw data into memory */
    ptr = *memTable[*hdl].memaddrptr + 2880;

    if (fread((char *) ptr, 1, datasize, diskfile) != datasize)
      status = READ_ERROR;

    fclose(diskfile);  /* close the raw binary disk file */

    if (status)
    {
        mem_close_free(*hdl);   /* free up the memory */
        ffpmsg("failed to copy raw file data into memory (mem_rawfile_open)");
        return(status);
    }

    if (datatype == USHORT_IMG)  /* have to subtract 32768 from each unsigned */
    {                            /* value to conform to FITS convention. More */
                                 /* efficient way to do this is to just flip  */
                                 /* the most significant bit.                 */

      sptr = (short *) ptr;

      if (endian == BYTESWAPPED)  /* working with native format */
      {
        for (ii = 0; ii < nvals; ii++, sptr++)
        {
          *sptr =  ( *sptr ) ^ 0x8000;
        }
      }
      else  /* pixels are byteswapped WRT the native format */
      {
        for (ii = 0; ii < nvals; ii++, sptr++)
        {
          *sptr =  ( *sptr ) ^ 0x80;
        }
      }
    }

    if (endian)  /* swap the bytes if array is in little endian byte order */
    {
      if (datatype == SHORT_IMG || datatype == USHORT_IMG)
      {
        ffswap2( (short *) ptr, nvals);
      }
      else if (datatype == LONG_IMG || datatype == FLOAT_IMG)
      {
        ffswap4( (INT32BIT *) ptr, nvals);
      }

      else if (datatype == DOUBLE_IMG)
      {
        ffswap8( (double *) ptr, nvals);
      }
    }

    memTable[*hdl].currentpos = 0;           /* save starting position */
    memTable[*hdl].fitsfilesize=filesize;    /* and initial file size  */

    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_uncompress2mem(char *filename, FILE *diskfile, int hdl)
{
/*
  lower level routine to uncompress a file into memory.  The file
  has already been opened and the memory buffer has been allocated.
*/

  size_t finalsize;
  int status;
  /* uncompress file into memory */
  status = 0;

    if (strstr(filename, ".Z")) {
         zuncompress2mem(filename, diskfile,
		 memTable[hdl].memaddrptr,   /* pointer to memory address */
		 memTable[hdl].memsizeptr,   /* pointer to size of memory */
		 realloc,                     /* reallocation function */
		 &finalsize, &status);        /* returned file size nd status*/
#if HAVE_BZIP2
    } else if (strstr(filename, ".bz2")) {
        bzip2uncompress2mem(filename, diskfile, hdl, &finalsize, &status);
#endif
    } else {
         uncompress2mem(filename, diskfile,
		 memTable[hdl].memaddrptr,   /* pointer to memory address */
		 memTable[hdl].memsizeptr,   /* pointer to size of memory */
		 realloc,                     /* reallocation function */
		 &finalsize, &status);        /* returned file size nd status*/
    } 

  memTable[hdl].currentpos = 0;           /* save starting position */
  memTable[hdl].fitsfilesize=finalsize;   /* and initial file size  */
  return status;
}
/*--------------------------------------------------------------------------*/
int mem_size(int handle, LONGLONG *filesize)
/*
  return the size of the file; only called when the file is first opened
*/
{
    *filesize = memTable[handle].fitsfilesize;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_close_free(int handle)
/*
  close the file and free the memory.
*/
{
    free( *(memTable[handle].memaddrptr) );

    memTable[handle].memaddrptr = 0;
    memTable[handle].memaddr = 0;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_close_keep(int handle)
/*
  close the memory file but do not free the memory.
*/
{
    memTable[handle].memaddrptr = 0;
    memTable[handle].memaddr = 0;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_close_comp(int handle)
/*
  compress the memory file, writing it out to the fileptr (which might
  be stdout)
*/
{
    int status = 0;
    size_t compsize;

    /* compress file in  memory to a .gz disk file */

    if(compress2file_from_mem(memTable[handle].memaddr,
              (size_t) (memTable[handle].fitsfilesize), 
              memTable[handle].fileptr,
              &compsize, &status ) )
    {
            ffpmsg("failed to copy memory file to file (mem_close_comp)");
            status = WRITE_ERROR;
    }

    free( memTable[handle].memaddr );   /* free the memory */
    memTable[handle].memaddrptr = 0;
    memTable[handle].memaddr = 0;

    /* close the compressed disk file (except if it is 'stdout' */
    if (memTable[handle].fileptr != stdout)
        fclose(memTable[handle].fileptr);

    return(status);
}
/*--------------------------------------------------------------------------*/
int mem_seek(int handle, LONGLONG offset)
/*
  seek to position relative to start of the file.
*/
{
    if (offset >  memTable[handle].fitsfilesize )
        return(END_OF_FILE);

    memTable[handle].currentpos = offset;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_read(int hdl, void *buffer, long nbytes)
/*
  read bytes from the current position in the file
*/
{
    if (memTable[hdl].currentpos + nbytes > memTable[hdl].fitsfilesize)
        return(END_OF_FILE);

    memcpy(buffer,
           *(memTable[hdl].memaddrptr) + memTable[hdl].currentpos,
           nbytes);

    memTable[hdl].currentpos += nbytes;
    return(0);
}
/*--------------------------------------------------------------------------*/
int mem_write(int hdl, void *buffer, long nbytes)
/*
  write bytes at the current position in the file
*/
{
    size_t newsize;
    char *ptr;

    if ((size_t) (memTable[hdl].currentpos + nbytes) > 
         *(memTable[hdl].memsizeptr) )
    {
               
        if (!(memTable[hdl].mem_realloc))
        {
            ffpmsg("realloc function not defined (mem_write)");
            return(WRITE_ERROR);
        }

        /*
          Attempt to reallocate additional memory:
          the memory buffer size is incremented by the larger of:
             1 FITS block (2880 bytes) or
             the defined 'deltasize' parameter
         */

        newsize = maxvalue( (size_t)
            (((memTable[hdl].currentpos + nbytes - 1) / 2880) + 1) * 2880,
            *(memTable[hdl].memsizeptr) + memTable[hdl].deltasize);

        /* call the realloc function */
        ptr = (memTable[hdl].mem_realloc)(
                                    *(memTable[hdl].memaddrptr),
                                     newsize);
        if (!ptr)
        {
            ffpmsg("Failed to reallocate memory (mem_write)");
            return(MEMORY_ALLOCATION);
        }

        *(memTable[hdl].memaddrptr) = ptr;
        *(memTable[hdl].memsizeptr) = newsize;
    }

    /* now copy the bytes from the buffer into memory */
    memcpy( *(memTable[hdl].memaddrptr) + memTable[hdl].currentpos,
             buffer,
             nbytes);

    memTable[hdl].currentpos += nbytes;
    memTable[hdl].fitsfilesize =
               maxvalue(memTable[hdl].fitsfilesize,
                        memTable[hdl].currentpos);
    return(0);
}


#if HAVE_BZIP2
void bzip2uncompress2mem(char *filename, FILE *diskfile, int hdl,
                        size_t* filesize, int* status) {
    BZFILE* b;
    int  bzerror;
    char buf[8192];
    size_t total_read = 0;
    char* errormsg = NULL;

    *filesize = 0;
    *status = 0;
    b = BZ2_bzReadOpen(&bzerror, diskfile, 0, 0, NULL, 0);
    if (bzerror != BZ_OK) {
        BZ2_bzReadClose(&bzerror, b);
        if (bzerror == BZ_MEM_ERROR)
            ffpmsg("failed to open a bzip2 file: out of memory\n");
        else if (bzerror == BZ_CONFIG_ERROR)
            ffpmsg("failed to open a bzip2 file: miscompiled bzip2 library\n");
        else if (bzerror == BZ_IO_ERROR)
            ffpmsg("failed to open a bzip2 file: I/O error");
        else
            ffpmsg("failed to open a bzip2 file");
        *status = READ_ERROR;
        return;
    }
    bzerror = BZ_OK;
    while (bzerror == BZ_OK) {
        int nread;
        nread = BZ2_bzRead(&bzerror, b, buf, sizeof(buf));
        if (bzerror == BZ_OK || bzerror == BZ_STREAM_END) {
            *status = mem_write(hdl, buf, nread);
            if (*status) {
                BZ2_bzReadClose(&bzerror, b);
                if (*status == MEMORY_ALLOCATION)
                    ffpmsg("Failed to reallocate memory while uncompressing bzip2 file");
                return;
            }
            total_read += nread;
        } else {
            if (bzerror == BZ_IO_ERROR)
                errormsg = "failed to read bzip2 file: I/O error";
            else if (bzerror == BZ_UNEXPECTED_EOF)
                errormsg = "failed to read bzip2 file: unexpected end-of-file";
            else if (bzerror == BZ_DATA_ERROR)
                errormsg = "failed to read bzip2 file: data integrity error";
            else if (bzerror == BZ_MEM_ERROR)
                errormsg = "failed to read bzip2 file: insufficient memory";
        }
    }
    BZ2_bzReadClose(&bzerror, b);
    if (bzerror != BZ_OK) {
        if (errormsg)
            ffpmsg(errormsg);
        else
            ffpmsg("failure closing bzip2 file after reading\n");
        *status = READ_ERROR;
        return;
    }
    *filesize = total_read;
}
#endif