#include "r2d/lcds/d_sample/r2d_tfd_lcd.h" 
#include "rvm/rvm_use_id_list.h"

#define RGB(R, G, B) ( (((unsigned char)(R) & 0xf8) << 8) | (((unsigned char)(G) & 0xfc) << 3) | (((unsigned char)(B) & 0xf8) >> 3) )

void r2d_lcd_power_on(void)
{
}

void r2d_lcd_power_off(void)
{
}

void r2d_refresh(void)
{
  UINT16 i,j;

#ifndef _WINDOWS
  
  UINT32 v;
  UINT32  *p;
  INT16 x1,x2,y1,y2,de,ds;
  UINT32 a,b,c,d,e,f;
	
  p=r2d_g_framebuffer->p_memory_words;
    
#if (R2D_REFRESH == R2D_HORIZONTAL)

	LCD_activate;

	x1=(r2d_update_ul_x>>1)<<1;  //0
	x2=((r2d_update_br_x>>1)<<1)+1; //174;

	ds=(x1>>1);
	de=R2D_MWWIDTH-(x2>>1)-1; // WHY -1, is formula right ????

	y1=r2d_update_ul_y; //0
	y2=r2d_update_br_y; //219

	//sprintf(debug,"%d,%d,%d,%d",x1,y1,x2,y2);
    //rvf_send_trace(debug,strlen(debug), NULL_PARAM, 
	//		   RV_TRACE_LEVEL_DEBUG_HIGH, R2D_USE_ID );

	  LCD_cmd (LCD_SD_PSET);  // set area devoted to MPU interface
  LCD_data (y1 & 0xff);
  LCD_data  (y1 >> 8);
  LCD_data  (y2 & 0xff);
  LCD_data  (y2 >> 8);

  LCD_cmd  (LCD_SD_CSET);  // set area devoted to MPU interface
  LCD_data  ((x1+2) & 0xff);
  LCD_data  ((x1+2) >> 8);
  LCD_data  ((x2+2) & 0xff);
  LCD_data  ((x2+2) >> 8);
  

	LCD_cmd(LCD_RAMWR);
	p=p+y1*R2D_MWWIDTH;

	for(i=y1;i<=y2;i++)
	{
	  p+=ds;
	  for(j=(x1>>1);j<=(x2>>1);j++)
	  {
            v=*p++;
			v=~v;

			/*white*/
			/*v=0xffffffff*/

			/*black*/
			/*v = 0x00000000*/

			/* The code below is a temporary fix for a problem with the LCD drivers.
		     * Currently, the LCD can only display colors in the range 0x0000 - 0xad55
			 * The code below maps pixel values into this range (divide by 2)
			 * Ideally, Epsom should provide a new GCP64 array to allow display of all
			 * colors. a-hill@ti.com*/

			/*if(v!=0xffffffff)
			{

				a = ((v&0xf8000000)>>1)&0xf8000000;
				b = ((v&0x07e00000)>>1)&0x07e00000;
				c=  ((v&0x001f0000)>>1)&0x001f0000;

				d = ((v&0x0000f800)>>1)&0x0000f800;
				e = ((v&0x000007e0)>>1)&0x000007e0;
				f=  ((v&0x0000001f)>>1)&0x0000001f;

				v = a|b|c|d|e|f;
			}*/

			LCD_data(v&0x0FFFF);
			LCD_data(v>>16);
		    	  
				  
	  }	    
      p+=de;     
      
	  
	  
    } 

	LCD_deactivate;
#endif
#endif

   r2d_check_and_send_event(r2d_g_framebuffer);
   r2d_reinit_update_region();

}