#include "jinclude.h"
#include "Bool.h"
#include "Erreur.h" 


LOCAL JSAMPIMAGE
    alloc_sampimage(compress_info_ptr cinfo,
                        int num_comps, long num_rows, long num_cols)
/* Allocate an in-memory sample image (all components same size) */
{
JSAMPIMAGE image;
int ci;

   image = (JSAMPIMAGE) (*cinfo->emethods->alloc_small)
    (num_comps * SIZEOF(JSAMPARRAY));
   for (ci = 0; ci < num_comps; ci++)
   {
      image[ci] = (*cinfo->emethods->alloc_small_sarray) (num_cols, num_rows);
   }
   return image;
}

#include "JOColor.h"

void my_pipeline(compress_info_ptr cinfo)
{
JSAMPIMAGE pixel_data;
JSAMPROW array[3];
int i,j;

   switch(cinfo -> in_color_space)
   {
      case CS_GRAYSCALE:
         pixel_data = alloc_sampimage(cinfo, 1, 8, cinfo->image_width);
         break;
      case CS_RGB:
         pixel_data = alloc_sampimage(cinfo, 3, 8, cinfo->image_width);
         rgb_y_init(cinfo);
         break;
      default:
         erreur_interne("Bad colorspace in JOPipe");
         break;
   };

  /* Tell the memory manager to instantiate big arrays.
   * We don't need any big arrays in this controller,
   * but some other module (like the output file writer) may need one.
   */
   (*cinfo->emethods->alloc_big_arrays)
    ((long) 0,                  /* no more small sarrays */
     (long) 0,                  /* no more small barrays */
     (long) 0);                 /* no more "medium" objects */


   for (i = 0; i < ((cinfo->image_height / 8) * 8); i += 8)
   {
      for (j = 0; j < 8; j++)
      {
         array[0] = pixel_data[0][j];
         array[1] = pixel_data[1][j];
         array[2] = pixel_data[2][j];
         cinfo->methods->get_input_row(cinfo, array);
      };
 
      if(cinfo -> jpeg_color_space == CS_GRAYSCALE && 
         cinfo -> in_color_space == CS_RGB )
         rgb_y(cinfo,8,pixel_data);

      cinfo->methods->put_pixel_rows(cinfo, 8, pixel_data);
   };
   for (j = 0; j < cinfo->image_height % 8; j++)
   {
      array[0] = pixel_data[0][j];
      array[1] = pixel_data[1][j];
      array[2] = pixel_data[2][j];
      cinfo->methods->get_input_row(cinfo, array);
   };

   if(cinfo -> jpeg_color_space == CS_GRAYSCALE && 
      cinfo -> in_color_space == CS_RGB )
      rgb_y(cinfo,8,pixel_data);

   cinfo->methods->put_pixel_rows(cinfo, j, pixel_data);
}
