/************************************************************/
/*         File Name: Sunalign.c                            */
/*         Package:   Sun Rasterfile Utility                */
/*         Author:    Michael D. Garris                     */
/*         Date:      3/08/90                               */
/************************************************************/
#include <stdio.h>
#include <math.h>
#include <rasterfile.h>
#include <memory.h>

/************************************************************/
/* If needed, word aligns the scanlines of a sun rasterfile.*/
/************************************************************/
main(argc,argv)
int argc;
char *argv[];
{
   int awidth,alength;
   struct rasterfile rasterhdr;
   char *filename;
   unsigned char *data,*adata,*map;
   FILE *fpin,*fpout;

   procargs(argc,argv,&filename);
   if((fpin = fopen(filename,"r")) == NULL){
      fprintf(stderr,"Unable to open file %s\n",filename);
      exit(-1);
   }
   fread(&rasterhdr,sizeof(struct rasterfile),1,fpin);
   map = (unsigned char *)malloc(rasterhdr.ras_maplength);
   fread(map,sizeof(char),rasterhdr.ras_maplength,fpin);
   data = (unsigned char *)malloc(rasterhdr.ras_length);
   fread(data,sizeof(char),rasterhdr.ras_length,fpin);
   fclose(fpin);
   if(!WordAlignImage(&adata,&awidth,&alength,data,rasterhdr.ras_width,
             rasterhdr.ras_height,rasterhdr.ras_depth)){
      free(map);
      free(data);
      fclose(fpin);
      exit(0);
   }
   if((fpout = fopen(filename,"w")) == NULL){
      fprintf(stderr,"Unable to open file %s\n",filename);
      exit(-1);
   }
   rasterhdr.ras_width = awidth;
   fwrite(&rasterhdr,sizeof(struct rasterfile),1,fpout);
   fwrite(map,sizeof(unsigned char),rasterhdr.ras_maplength,fpout);
   fwrite(adata, sizeof(unsigned char), alength, fpout);
   fclose(fpout);
   free(map);
   free(data);
   free(adata);
}

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

