/************************************************************/
/*         File Name: Writihdr.c                            */
/*         Package:   Image Write Routines                  */
/*                                                          */
/*         Contents:  writeihdrfile()                       */
/************************************************************/
#include <stdio.h>
#include <ihead.h>

/************************************************************/
/*         Routine:   Writeihdrfile()                       */
/*         Author:    Michael D. Garris                     */
/*         Date:      4/26/89                               */
/*         Modifications:                                   */
/*           9/20/90   (Stan Janet) check return codes      */
/*           2/20/91   (MDG) compression capability         */
/************************************************************/
/************************************************************/
/* Writeihdrfile() writes a ihead structure and correspon-  */
/* ding image data to the specified file.                   */
/************************************************************/
void writeihdrfile(file,head,data)
char *file;
IHEAD *head;
unsigned char *data;
{
   FILE *fp;
   char lenstr[SHORT_CHARS];
   int i,width,height,depth,code,filesize,n, compbytes;
   unsigned char *compdata;

   /* reopen the image file for writing */
   fp = fopen(file,"w");
   if (fp == NULL)
      syserr("writeihdrfile","fopen",file);

   n = sscanf(head->width,"%d",&width);
   if (n != 1)
      fatalerr("writeihdrfile","sscanf failed on width field",NULL);
   n = sscanf(head->height,"%d",&height);
   if (n != 1)
      fatalerr("writeihdrfile","sscanf failed on height field",NULL);
   n = sscanf(head->depth,"%d",&depth);
   if (n != 1)
      fatalerr("writeihdrfile","sscanf failed on depth field",NULL);
   n = sscanf(head->compress, "%d", &code);
   if (n != 1)
      fatalerr("writeihdrfile","sscanf failed on compression code field",NULL);

   filesize = SizeFromDepth(width,height,depth);

   if(code == UNCOMP){
      sprintf(head->complen, "%d", 0);
      writeihdr(fp,head);
      n = fwrite(data,1,filesize,fp);
      if (n != filesize)
         syserr("writeihdrfile", "fwrite", file);
   }
   else
      fatalerr("writeihdrfile","Unknown compression",NULL);

   /* closes the new file */
   (void) fclose(fp);
}
