/*

   NULL

   g_sdl.c

   28.1.1998

   graphics main

*/

#include <SDL.h>
#include <SDL_endian.h>

#include "g_main.h"
#include "m_main.h"

SDL_Surface *scrn;

static cFile *border;

int borderflag = 0;
int with_borders = 1;

void    g_init(void) {	// Init Display (open screen etc.)

	border=m_loadfile("gfx/border.chk");

	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER);
	scrn = SDL_SetVideoMode(320, 240, 16, SDL_SWSURFACE);

	SDL_WM_SetCaption("Megademo IV 2", "MDIV2");
	SDL_ShowCursor(SDL_DISABLE);
}


void    g_shutdown(void) {   // Shutdown display (close screen..)

	SDL_Quit();
}


void    g_update(rgb18 *buf) {
	//Update buffer are. The buffer is 160x128x32bit
	//with 18 bit used in 0RGB style 	
	//it has to be scaled to 320x128

	int x, y;
	Uint16 *pic;

	if (with_borders) {

		if (!borderflag) {
			Uint8 *p=(char *) border->data;
			memset(scrn->pixels, 0, 20*320*2);
			memset(scrn->pixels+220*320*2, 0, 20*320*2);
			pic = scrn->pixels + 20*320*2;
			for (y=0;y<200;y++)  {
				for (x=0;x<320;x++) {
					*pic++ = ((p[1] >> 3) << 11)
						 | ((p[2] >> 2) << 5)
						 | (p[3] >> 3);
					p += 4;
				}
			}
			borderflag=-1;
		}

		Uint16 *pic = scrn->pixels + (20+36)*320*2;

		for (y=0; y<128; y++) {
			for (x=0; x<160; x++) {
				Uint16 col = ((buf[0].r>>1) << 11)
						| (buf[0].g << 5)
						| (buf[0].b >> 1);
				*pic++ = col;
				*pic++ = col;

				buf++;
			}
		}

	}
	else {
		// No borders
		pic = scrn->pixels;

		// Skip four lines
		buf += 160*4;

		for ( y=0;y<120;y++) {
			for (x=0;x<160;x++) {
				Uint16 col = ((buf[0].r>>1) << 11)
						| (buf[0].g << 5)
						| (buf[0].b >> 1);
				*pic++ = col;
				*pic++ = col;

				buf++;
			}

			// Double line:
			memcpy(pic, pic-320, 320*2);
			pic += 320;
		}
	}

	SDL_UpdateRect(scrn, 0, 0, 0, 0);
}
