/************************************************************/
/*         File Name: Loadidhr.c                            */
/*         Package:   IHead Image Read Routines             */
/*                                                          */
/*         Contents:  readihdrfile()                        */
/************************************************************/
#include <stdio.h>
#include <math.h>
#include <ihead.h>

/************************************************************/
/*         Routine:   Readihdrfile()                        */
/*         Author:    Michael D. Garris                     */
/*         Date:      3/15/90                               */
/************************************************************/
/************************************************************/
/* Readihdrfile() reads in an IHead binary raster           */
/* file and returns an ihead structure, raster data, and    */
/* integer file specs.                                      */
/************************************************************/
readihdrfile(file,head,data,width,height)
char *file;
IHEAD **head;
unsigned char **data;
int *width,*height;
{
   FILE *fp;
   IHEAD *readihdr();
   IHEAD *ihead;
   int outbytes, depth, comp, filesize, complen;
   unsigned char *indata, *outdata;

   /* open the image file */
   if((fp = fopen(file,"r")) == NULL){
      fprintf(stderr,"Unable to open file:: %s\n",file);
      exit(-1);
   }
   /* read in the image header */
   (*head) = readihdr(fp);
   ihead = *head;
   sscanf((*head)->depth,"%d",&depth);
   if(depth != 1){
      fprintf(stderr,"File: %s is not a binary file.\n",file);
      exit(-1);
   }
   sscanf((*head)->compress,"%d",&comp);
   /* convert string fields to integers */
   sscanf((*head)->width,"%d",width);
   sscanf((*head)->height,"%d",height);
   sscanf((*head)->complen,"%d",&complen);

   /* allocate a raster data buffer */
   filesize = ((int)((*width)>>3) * (*height));
   outdata = (unsigned char *)malloc(filesize * sizeof(unsigned char));
   indata = (unsigned char *)malloc(complen * sizeof(unsigned char));

   /* read in the raster data */
   if(complen == 0)    /* file is uncompressed */
      fread(outdata,sizeof(unsigned char),filesize,fp);
   else
      fread(indata,sizeof(unsigned char),complen,fp);   /* file is compressed */
   switch (comp) {
      case CCITT_G4:
        grp4decomp(indata,complen,*width,*height,outdata,&outbytes);
        sprintf((*head)->complen,"%d",0);
        sprintf((*head)->compress,"%d",UNCOMP);
        *data = outdata;
        free(indata);
      break;
      case UNCOMP:
        *data = outdata;
      break;
      default:
         fprintf(stderr,"Read Failure - File: %s has invalid compression code.\n",file);
         exit(-1);
      break;
   }
   /* close the image file */
   fclose(fp);
}
