/************************************************************/
/*         File Name: Ihdr2sun.c                            */
/*         Package:   NIST Ihead to Sun Rasterfile          */
/*         Author:    Michael D. Garris                     */
/*         Date:      3/08/90                               */
/************************************************************/
#include <stdio.h>
#include <rasterfile.h>
#include <ihead.h>

#define BUFSIZE		80
#define SUNEXT		".ras"

/************************************************************/
/* Converts an NIST ihead image to a sun rasterfile.        */
/************************************************************/
main(argc,argv)
int argc;
char *argv[];
{
   int width,height,filesize;
   struct rasterfile rasterhdr;
   char *filename, sunfile[BUFSIZE];
   unsigned char *data;
   IHEAD *ihead;
   FILE *fp;

   procargs(argc,argv,&filename);
   readihdrfile(filename,&ihead,&data,&width,&height);
   rasterhdr.ras_magic = RAS_MAGIC;
   rasterhdr.ras_width = width;
   rasterhdr.ras_height = height;
   rasterhdr.ras_depth = 1;
   filesize = (width>>3) * height;
   rasterhdr.ras_length = filesize;
   rasterhdr.ras_type = RT_STANDARD;
   rasterhdr.ras_maplength = 0;
   rasterhdr.ras_maptype = RMT_NONE;

   strcpy(sunfile, filename);
   fileroot(sunfile);
   strcat(sunfile,SUNEXT);
   if((fp = fopen(sunfile,"w")) == NULL){
      fprintf(stderr,"Unable to open file %s\n",sunfile);
      exit(-1);
   }
   fwrite(&rasterhdr,sizeof(struct rasterfile),1,fp);
   fwrite(data,sizeof(char),rasterhdr.ras_length,fp);
   fclose(fp);
   free(ihead);
   free(data);
}
 
/************************************************************/
/*         Routine:   FileRoot()                            */
/*         Author:    Michael D. Garris                     */
/*         Date:      11/27/89                              */
/************************************************************/
/*************************************************************/
/* Fileroot() is a destructive procedure which takes a file  */
/* name and strips off the rightmost extension, if it exists.*/
/*************************************************************/
fileroot(file)
char *file;
{
   char *cptr;

   cptr = file + strlen(file);
   while((cptr != file) && (*cptr != '.'))
      cptr--;
   if(*cptr == '.')
      *cptr = NULL;
}

procargs(argc,argv,filename)
int argc;
char *argv[],**filename;
{
   if(argc < 2){
      fprintf(stderr,"Usage: ihdr2sun <IHead file>\n");
      exit(-1);
   }
  *filename = argv[1];
}
