#include <sdl.h>
#include <sdl_opengl.h>

void InitGraphics()
{
    const int width = 800, height = 600;

    // Initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0) exit(1);

    // Window Settings
    SDL_WM_SetCaption("SDL/OpenGL Sample", "SDL/OpenGL Sample");

    // Get Video Info
    const SDL_VideoInfo *video = SDL_GetVideoInfo();
    if (!video) { SDL_Quit(); exit(2); }

    // Create Video Surface
    SDL_Surface *screen = SDL_SetVideoMode(width, height, video->vfmt->BitsPerPixel, SDL_OPENGL);
    if (!screen) { SDL_Quit(); exit(3); }

    // Size OpenGL to Video Surface
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, (float)width / (float)height, 1.0, 100.0);
    glMatrixMode(GL_MODELVIEW);

    // Set Pixel Format
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    // OpenGL Render Settings
    glClearColor(0, 0, 0, 1);
    glClearDepth(1.0);
    glEnable(GL_DEPTH_TEST);
}

// Draw the scene
void DrawGraphics()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Set location in front of camera
    glLoadIdentity();
    glTranslated(0, 0, -10);

    // Draw a square
    glBegin(GL_QUADS);
    glColor3d(1, 0, 0);
    glVertex3d(-2, 2, 0);
    glVertex3d(2, 2, 0);
    glVertex3d(2, -2, 0);
    glVertex3d(-2, -2, 0);
    glEnd();

    // Show the frame
    SDL_GL_SwapBuffers();
}

// Handle events
bool Events()
{
    SDL_Event event;

    while (SDL_PollEvent(&event))
    {
        switch (event.type)
        {
        case SDL_KEYDOWN:
            // Exit when ESC is pressed
            if (event.key.keysym.sym == SDLK_ESCAPE) return false;
            break;

        case SDL_QUIT:
            return false;
        }
    }
    return true;
}

// Program entry point
int main(int argc, char **argv)
{
    InitGraphics();

    // Event loop
    while (Events())
    {
        DrawGraphics();
    }

    // Clean up
    SDL_Quit();
    return 0;
}
