#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iocslib.h>

#define NORM(x) { if(x<0) x=0; else if (x>255) x=255;}

void
write_x68k(buf, PPM_WIDTH, PPM_HEIGHT, rateW, rateH)
     u_char	*buf;
     int PPM_WIDTH;
     int PPM_HEIGHT;
     int rateW;
     int rateH;
{
  int x, y;
  long cr, cb;
  long L;
  long r,g,b;
  u_char *Y;
  u_char *Cr;
  u_char *Cb;

  struct PSETPTR psetptr;

  CRTMOD(12);
  G_CLR_ON();

  Y = buf;

  Cb = Y + (PPM_HEIGHT * PPM_WIDTH);
  Cr = Cb + (PPM_HEIGHT / rateH) * (PPM_WIDTH / rateW);

  for( y = 0 ; y < PPM_HEIGHT; y++){
    for( x = 0 ; x < PPM_WIDTH ; x++){
      L = Y[y * PPM_WIDTH + x] *  100000; 
      cb = Cb[(y / rateH) * PPM_WIDTH /rateW + (x /rateW)];
      if(cb > 127) cb = cb - 256;
      cr = Cr[(y / rateH) * PPM_WIDTH /rateW + (x /rateW)];
      if(cr > 127) cr = cr - 256;

      r = L + 140200 * cr;
      g = L - 34414 * cb - 71414 * cr;
      b = L + 177200 * cb;
      
      r = r / 100000;
      g = g / 100000;
      b = b / 100000;

      NORM(r);
      NORM(g);
      NORM(b);

      psetptr.x = x;
      psetptr.y = y*2;
	  psetptr.color = ((g & 0xf8) << 8) | 
					 ((r & 0xf8) << 3) | 
					 ((b & 0xf8) >> 2 ) ;
	  PSET(&psetptr);
	  psetptr.y ++;
	  PSET(&psetptr);
    }
  }
}






