Saving OpenGL surface as a BMP

Someone had asked how to save an OpenGL surface as a BMP file. This is what my code does:

void SaveScreen(const char *filename)
{
SDL_Surface *image;
SDL_Surface *temp;
int idx;
SDL_Surface * screen = SDL_GetVideoSurface();
int w = screen->w;
int h = screen->h;
image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 24, 0x0000FF, 0x00FF00, 0xFF0000, 0x000000);
temp = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 24, 0x0000FF, 0x00FF00, 0xFF0000, 0x000000);
glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, image->pixels);
for (idx = 0; idx < h; idx++)
{
memcpy((unsigned char *)(temp->pixels) + 3 * w * idx,
(unsigned char )(image->pixels) + 3 * w * (h - idx),
3
w);
}
memcpy(image->pixels,temp->pixels,w * h * 3);
SDL_SaveBMP(image, filename);
SDL_FreeSurface(image);
SDL_FreeSurface(temp);
}

Dennis Jenkins