#include "SDL.h"
void setpixel(SDL_Surface *screen, int x, int y, Uint8 r, Uint8 g, Uint8 b)
{
  Uint8 *ubuff8;
  Uint16 *ubuff16;
  Uint32 *ubuff32;
  Uint32 color;
  char c1, c2, c3;
  
  /* Lock the screen, if needed */
  if(SDL_MUSTLOCK(screen)) {
    if(SDL_LockSurface(screen) < 0) 
      return;
  }
  
  /* Get the color */
  color = SDL_MapRGB( screen->format, r, g, b );
  
  /* How we draw the pixel depends on the bitdepth */
  switch(screen->format->BytesPerPixel) 
    {
    case 1: 
      ubuff8 = (Uint8*) screen->pixels;
      ubuff8 += (y * screen->pitch) + x; 
      *ubuff8 = (Uint8) color;
      break;
    case 2:
      ubuff8 = (Uint8*) screen->pixels;
      ubuff8 += (y * screen->pitch) + (x*2);
      ubuff16 = (Uint16*) ubuff8;
      *ubuff16 = (Uint16) color; 
      break;  
    case 3:
      ubuff8 = (Uint8*) screen->pixels;
      ubuff8 += (y * screen->pitch) + (x*3);
      
      if(SDL_BYTEORDER == SDL_LIL_ENDIAN) {
	c1 = (color & 0xFF0000) >> 16;
	c2 = (color & 0x00FF00) >> 8;
	c3 = (color & 0x0000FF);
      } else {
	c3 = (color & 0xFF0000) >> 16;
	c2 = (color & 0x00FF00) >> 8;
	c1 = (color & 0x0000FF);	
      }
      ubuff8[0] = c3;
      ubuff8[1] = c2;
      ubuff8[2] = c1;
      break;
      
    case 4:
      ubuff8 = (Uint8*) screen->pixels;
      ubuff8 += (y*screen->pitch) + (x*4);
      ubuff32 = (Uint32*)ubuff8;
      *ubuff32 = color;
      break;
      
    default:
      fprintf(stderr, "Error: Unknown bitdepth!\n");
    }
  
  /* Unlock the screen if needed */
  if(SDL_MUSTLOCK(screen)) {
    SDL_UnlockSurface(screen);
  }
}