/* this file is decrunch.c, 5/29/91, to decompress an image file */
#include <stdio.h>
#include <math.h>
typedef unsigned char byte;
unsigned char *fzread();
unsigned char *cread();
#define ABS(x) ((x)>=0?(x):-(x))
#define	MIN(a,b) (((a)<(b))?(a):(b))
#define	MAX(a,b) (((a)>(b))?(a):(b))


/*----------------------------------------------------------------------------*/
main(argc,argv)

int argc;	char *argv[];

{

 /*------------------------------------------------------------------------- */
 struct fitshead {
  char   fitxt[80];};
 /*------------------------------------------------------------------------- */
FILE *fopen(),*fin,*fout;
struct	fitshead *fth, fitsheader;
 char	*comments, *p, *upd;
 byte	*data;
 int	dims[8], num_dim, type, nc, nq;
 int	size, fw, i, foundfits=1;
 static int	noend;

 if (argc<3) printf("decrunch requires an input and output file\n");
 
 /* is this an fz compressed file? */	
 data = fzread(argv[1], &type, &num_dim, dims, &comments);
 if (data != NULL)  {
   fzwrite(data, argv[2], type, num_dim, dims, comments);
 /* done if fz */
 exit(0); }

 fth=&fitsheader;
 if ((fin=fopen(argv[1],"r")) == NULL) { perror("file open error");
  exit(0); }
 if ((nq=fread(fth,1,80,fin)) == NULL) { perror("header read error");
  exit(0); }
/* is this a fits compressed file? */	
 if (strncmp(fth,"SIMPLE  =",80)) {
  upd="SIMPLE  =                    T                                                  ";
  upd[79] = NULL;
  fseek(fin,0,0);
  if ((fout=fopen(argv[2],"w")) == NULL) { perror("file open error");
  exit(0); }

 noend=1;
  while(noend)
  {
   for (i=0; i<36; i++ )
   {
    if ((strncmp(fth,"END ",4)) == 0) noend=0;
    nq=fread(fth,1,80,fin); 
    fitsheader.fitxt[79] = NULL;
    if (foundfits) {fwrite(upd,1,80,fout); foundfits=0;}
    else {fwrite(fth,1,80,fout);}
   } 
  }
 data = cread(fin, &size);
 fclose(fin);

 if (fwrite(data, 1, size, fout) != size) {
	 perror("error writing file");	fclose(fout); }
 fclose(fout);
 
 }

 if (data == NULL) {
  printf("something bad has happened, cannot continue\n");
  exit(0); }

}
