void BitmapBGLayer::draw(Surface &dest)
{
   SDL_rect dstrect;
   int sx, sy, destWidth, destHeight;

   // check validity of dest and bg surfaces
   if(!dest.isValid() || !bg || !bg->isValid())
      return;

   destWidth  = dest.getWidth();
   destHeight = dest.getHeight();
   
   dstrect.w = bg->getWidth();
   dstrect.h = bg->getHeight();

   // calculate screen coordinates
   sx = scrollx ? x - wCamX / scrollx : x;
   sy = scrolly ? y - wCamY / scrolly : y;
   
   // clip to right and bottom edges immediately
   if(sx >= destWidth || sy >= destHeight)
      return;
   
   // if looping along either axis, adjust the coordinates to start tiling
   // as close to the screen buffer as possible
   
   if((loopflags & LOOP_X))
   {
      if(sx <= -dstrect.w)
         sx += (-sx / dstrect.w) * dstrect.w;
   }
   else if(dstrect.w + sx < 0)
      return; // if not looping and off left edge, clip
   
   if((loopflags & LOOP_Y))
   {
      if(sy <= -dstrect.h)
         sy += (-sy / dstrect.h) * dstrect.h;
   }
   else if(dstrect.h + sy < 0)
      return; // if not looping and off top edge, clip
   
   dstrect.y = sy;
   
   do
   {
      dstrect.x = sx;
      
      do
      {
         bg->blitTo(dest, NULL, &dstrect);
         dstrect.x += dstrect.w;
      }
      while((loopflags & LOOP_X) && dstrect.x < destWidth);
      
      dstrect.y += dstrect.h;
   }
   while((loopflags & LOOP_Y) && dstrect.y < destHeight);
}