

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>



#define MAIN_G
#include "rle_bits.h"




int main(int argc, char *argv[])
{
	int rle_fd,ppm_fd,i;
	unsigned char line[3*4096];
	
	if (argc < 3)

	   rle_fd = fileno(stdin);
         else
	   {
            i = open(argv[1],O_RDONLY);
	    if (i > 0)
	       rle_fd = i;
             else
               rle_fd = fileno(stdin);
           }
	 

	if (argc < 3)
	   ppm_fd = fileno(stdout);
         else
           {
            i = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0664);
	    if (i > 0)
                ppm_fd = i;
             else
               ppm_fd = fileno(stdout);
           } 

	int width,height; 
        rle_init();

	if (rle_get_header(rle_fd,width,height) == false)
	   exit(1);

	char st[256];
	sprintf(st,"P6\n%d %d\n255\n",width,height);
	write(ppm_fd,st,strlen(st));
	
	unsigned char C;
	int l = 0;
	for (int j=0; j<height; j++)
          {
//           fprintf(stderr,"doing line %d\n",j);
           for (int k=0; k<width; k++)
            {
	     rle_get_pixel(rle_fd,C); 
  	     
	     line[(l*3)+0] = rle_Colormap[C].r;			
	     line[(l*3)+1] = rle_Colormap[C].g;			
	     line[(l*3)+2] = rle_Colormap[C].b;			
		
	     l++;
	     if (l >= 3072)
	        {
                 write(ppm_fd,line,(l*3));
	         l = 0;
	        }
	    }
          }

	write(ppm_fd,line,l*3);
	close(ppm_fd);
	close(rle_fd);
	rle_done();
}
