Port, clean-up and remove dead/unnecessary code

Make the apps test friendly

Change-Id: I251f7125984ea1d06f1e18bbaef664eeaac60239
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..05d1d4e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,7 @@
+SUBDIRS := opengl
+
+all: $(SUBDIRS)
+$(SUBDIRS):
+	$(MAKE) -C $@
+
+.PHONY: all $(SUBDIRS)
diff --git a/opengl/Makefile b/opengl/Makefile
new file mode 100644
index 0000000..dccc98f
--- /dev/null
+++ b/opengl/Makefile
@@ -0,0 +1,21 @@
+CROSS_COMPILE ?=
+CC = $(CROSS_COMPILE)gcc
+
+all: glesgears es2gears
+
+%.o : %.c
+	$(CC) -c -DGLES=1 $(CFLAGS) $(CPPFLAGS) $< -o $@
+
+gles2_simple-egl.o: simple-egl.c
+	$(CC) -c -DGLES=2 $(CFLAGS) $(CPPFLAGS) $< -o $@
+
+glesgears: glesgears.o simple-egl.o
+	$(CC) -o glesgears glesgears.o simple-egl.o -lGLESv1_CM -lm -lEGL -lwayland-client -lwayland-egl
+
+es2gears: es2gears.o gles2_simple-egl.o
+	$(CC) -o es2gears es2gears.o gles2_simple-egl.o -lGLESv2 -lm -lEGL -lwayland-client -lwayland-egl
+
+clean:
+	rm -f glesgears es2gears *.o
+
+.PHONY: all clean
diff --git a/opengl/README b/opengl/README
new file mode 100644
index 0000000..b02bc2c
--- /dev/null
+++ b/opengl/README
@@ -0,0 +1,7 @@
+To build glesgears and es2gears
+
+1. Copy the whole directory to the target
+2. On the target run:
+   % sudo apt-get install libgles2-mesa-dev mesa-common-dev libwayland-dev
+3. In the opengl directory:
+   % make
\ No newline at end of file
diff --git a/opengl/es2gears.c b/opengl/es2gears.c
index 37fb6a4..4119d01 100644
--- a/opengl/es2gears.c
+++ b/opengl/es2gears.c
@@ -1,16 +1,16 @@
 /*
  * Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
- * 
+ *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
  * to deal in the Software without restriction, including without limitation
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
@@ -23,7 +23,7 @@
  * Ported to GLES2.
  * Kristian Høgsberg <krh@bitplanet.net>
  * May 3, 2010
- * 
+ *
  * Improve GLES2 port:
  *   * Refactor gear drawing.
  *   * Use correct normals for surfaces.
@@ -35,21 +35,23 @@
  * Jul 13, 2010
  */
 
-#define GL_GLEXT_PROTOTYPES
-#define EGL_EGLEXT_PROTOTYPES
+/* 
+ * Port to Mendel Linux Wayland by Peter Nordström 1 June 2020 
+ * 
+ * Window handling and egl initialization done externally in
+ * simple-egl.c
+ */
+
 
 #define _GNU_SOURCE
 
+#include <GLES2/gl2.h>
 #include <math.h>
 #include <stdlib.h>
-#include <stdio.h>
 #include <string.h>
-#include <sys/time.h>
 #include <unistd.h>
-#include <GLES2/gl2.h>
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-#include "eglut.h"
+
+extern void HandleFrame(void);
 
 #define STRIPS_PER_TOOTH 7
 #define VERTICES_PER_TOOTH 34
@@ -100,15 +102,15 @@
 /** The direction of the directional light for the scene */
 static const GLfloat LightSourcePosition[4] = { 5.0, 5.0, 10.0, 1.0};
 
-/** 
+/**
  * Fills a gear vertex.
- * 
+ *
  * @param v the vertex to fill
  * @param x the x coordinate
  * @param y the y coordinate
  * @param z the z coortinate
- * @param n pointer to the normal table 
- * 
+ * @param n pointer to the normal table
+ *
  * @return the operation error code
  */
 static GearVertex *
@@ -126,13 +128,13 @@
 
 /**
  *  Create a gear wheel.
- * 
+ *
  *  @param inner_radius radius of hole at center
  *  @param outer_radius radius at center of teeth
  *  @param width width of gear
  *  @param teeth number of teeth
  *  @param tooth_depth depth of tooth
- *  
+ *
  *  @return pointer to the constructed struct gear
  */
 static struct gear *
@@ -276,11 +278,11 @@
    return gear;
 }
 
-/** 
+/**
  * Multiplies two 4x4 matrices.
- * 
+ *
  * The result is stored in matrix m.
- * 
+ *
  * @param m the first matrix to multiply
  * @param n the second matrix to multiply
  */
@@ -303,9 +305,9 @@
    memcpy(m, &tmp, sizeof tmp);
 }
 
-/** 
+/**
  * Rotates a 4x4 matrix.
- * 
+ *
  * @param[in,out] m the matrix to rotate
  * @param angle the angle to rotate
  * @param x the x component of the direction to rotate to
@@ -320,7 +322,7 @@
    sincos(angle, &s, &c);
    GLfloat r[16] = {
       x * x * (1 - c) + c,     y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
-      x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0, 
+      x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0,
       x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c,     0,
       0, 0, 0, 1
    };
@@ -329,9 +331,9 @@
 }
 
 
-/** 
+/**
  * Translates a 4x4 matrix.
- * 
+ *
  * @param[in,out] m the matrix to translate
  * @param x the x component of the direction to translate to
  * @param y the y component of the direction to translate to
@@ -345,9 +347,9 @@
    multiply(m, t);
 }
 
-/** 
+/**
  * Creates an identity 4x4 matrix.
- * 
+ *
  * @param m the matrix make an identity matrix
  */
 static void
@@ -363,12 +365,12 @@
    memcpy(m, t, sizeof(t));
 }
 
-/** 
+/**
  * Transposes a 4x4 matrix.
  *
  * @param m the matrix to transpose
  */
-static void 
+static void
 transpose(GLfloat *m)
 {
    GLfloat t[16] = {
@@ -407,9 +409,9 @@
    multiply(m, t);
 }
 
-/** 
+/**
  * Calculate a perspective projection transformation.
- * 
+ *
  * @param m the matrix to save the transformation in
  * @param fovy the field of view in the y direction
  * @param aspect the view aspect ratio
@@ -472,7 +474,7 @@
    glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
                       model_view_projection);
 
-   /* 
+   /*
     * Create and set the NormalMatrix. It's the inverse transpose of the
     * ModelView matrix.
     */
@@ -507,7 +509,7 @@
    glDisableVertexAttribArray(0);
 }
 
-/** 
+/**
  * Draws the gears.
  */
 static void
@@ -534,9 +536,9 @@
    draw_gear(gear3, transform, -3.1, 4.2, -2 * angle - 25.0, blue);
 }
 
-/** 
+/**
  * Handles a new window size or exposure.
- * 
+ *
  * @param width the window width
  * @param height the window height
  */
@@ -550,62 +552,6 @@
    glViewport(0, 0, (GLint) width, (GLint) height);
 }
 
-/** 
- * Handles special eglut events.
- * 
- * @param special the event to handle.
- */
-static void
-gears_special(int special)
-{
-   switch (special) {
-      case EGLUT_KEY_LEFT:
-         view_rot[1] += 5.0;
-         break;
-      case EGLUT_KEY_RIGHT:
-         view_rot[1] -= 5.0;
-         break;
-      case EGLUT_KEY_UP:
-         view_rot[0] += 5.0;
-         break;
-      case EGLUT_KEY_DOWN:
-         view_rot[0] -= 5.0;
-         break;
-   }
-}
-
-static void
-gears_idle(void)
-{
-   static int frames = 0;
-   static double tRot0 = -1.0, tRate0 = -1.0;
-   double dt, t = eglutGet(EGLUT_ELAPSED_TIME) / 1000.0;
-
-   if (tRot0 < 0.0)
-      tRot0 = t;
-   dt = t - tRot0;
-   tRot0 = t;
-
-   /* advance rotation for next frame */
-   angle += 70.0 * dt;  /* 70 degrees per second */
-   if (angle > 3600.0)
-      angle -= 3600.0;
-
-   eglutPostRedisplay();
-   frames++;
-
-   if (tRate0 < 0.0)
-      tRate0 = t;
-   if (t - tRate0 >= 5.0) {
-      GLfloat seconds = t - tRate0;
-      GLfloat fps = frames / seconds;
-      printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
-            fps);
-      tRate0 = t;
-      frames = 0;
-   }
-}
-
 static const char vertex_shader[] =
 "attribute vec3 position;\n"
 "attribute vec3 normal;\n"
@@ -659,7 +605,6 @@
    glShaderSource(v, 1, &p, NULL);
    glCompileShader(v);
    glGetShaderInfoLog(v, sizeof msg, NULL, msg);
-   printf("vertex shader info: %s\n", msg);
 
    /* Compile the fragment shader */
    p = fragment_shader;
@@ -667,7 +612,6 @@
    glShaderSource(f, 1, &p, NULL);
    glCompileShader(f);
    glGetShaderInfoLog(f, sizeof msg, NULL, msg);
-   printf("fragment shader info: %s\n", msg);
 
    /* Create and link the shader program */
    program = glCreateProgram();
@@ -678,7 +622,6 @@
 
    glLinkProgram(program);
    glGetProgramInfoLog(program, sizeof msg, NULL, msg);
-   printf("info: %s\n", msg);
 
    /* Enable the shaders */
    glUseProgram(program);
@@ -698,26 +641,18 @@
    gear3 = create_gear(1.3, 2.0, 0.5, 10, 0.7);
 }
 
-int
-main(int argc, char *argv[])
-{
-   /* Initialize the window */
-   eglutInitWindowSize(300, 300);
-   eglutInitAPIMask(EGLUT_OPENGL_ES2_BIT);
-   eglutInit(argc, argv);
+void RunGears() {
+  gears_init();
+  gears_reshape(600, 600);
+  while (1) {
+    double dt = 0.01666;
 
-   eglutCreateWindow("es2gears");
+    /* advance rotation for next frame */
+    angle += 70.0 * dt;  /* 70 degrees per second */
+    if (angle > 3600.0)
+      angle -= 3600.0;
 
-   /* Set up eglut callback functions */
-   eglutIdleFunc(gears_idle);
-   eglutReshapeFunc(gears_reshape);
-   eglutDisplayFunc(gears_draw);
-   eglutSpecialFunc(gears_special);
-
-   /* Initialize the gears */
-   gears_init();
-
-   eglutMainLoop();
-
-   return 0;
+    gears_draw();
+    HandleFrame();
+  }
 }
diff --git a/opengl/glesgears.c b/opengl/glesgears.c
index fae3233..5f45936 100644
--- a/opengl/glesgears.c
+++ b/opengl/glesgears.c
@@ -1,69 +1,45 @@
 /*
- * 3-D gear wheels.  This program is in the public domain.
- *
- * Command line options:
- *    -info      print GL implementation information
- *    -exit      automatically exit after 30 seconds
- *
- *
- * Brian Paul
+ * Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
-
 /* Conversion to use vertex buffer objects by Michael J. Clark */
 
+/* 
+ * Port to Mendel Linux Wayland by Peter Nordström 1 June 2020 
+ * 
+ * Window handling and egl initialization done externally in
+ * simple-egl.c
+ */
+
 #include <assert.h>
+#include <GLES/gl.h>
 #include <math.h>
 #include <stdlib.h>
-#include <stdio.h>
 #include <string.h>
-#include "window.h"
+#include <unistd.h>
 
-#define MAX_CONFIGS 10
-#define MAX_MODES 100
-
-
-#ifdef _WIN32
-  #define WIN32_LEAN_AND_MEAN 1
-  #include <windows.h>
-
-  static double
-  current_time(void)
-  {
-     DWORD tv;
-
-     tv = GetTickCount();
-     return (tv/1000.0);
-  }
-  
-#else
-  #include <sys/time.h>
-  #include <unistd.h>
-
-  /* return current time (in seconds) */
-  static double
-  current_time(void)
-  {
-     struct timeval tv;
-  #ifdef __VMS
-     (void) gettimeofday(&tv, NULL );
-  #else
-     struct timezone tz;
-     (void) gettimeofday(&tv, &tz);
-  #endif
-     return (double) tv.tv_sec + tv.tv_usec / 1000000.0;
-  }
-#endif
-
-#include <GLES/gl.h>
-#include <GLES/egl.h>
-
+extern void HandleFrame(void);
 
 #ifndef M_PI
 #define M_PI 3.14159265
 #endif
 
-
-static GLint autoexit = 0;
 static GLfloat viewDist = 40.0;
 
 typedef struct {
@@ -73,7 +49,7 @@
 
 typedef struct {
   vertex_t *vertices;
-  GLshort *indices;
+  GLushort *indices;
   GLfloat color[4];
   int nvertices, nindices;
   GLuint ibo;
@@ -87,7 +63,7 @@
 
   Draw a gear wheel.  You'll probably want to call this function when
   building a display list since we do a lot of trig here.
- 
+
   Input:  inner_radius - radius of hole at center
           outer_radius - radius at center of teeth
           width - width of gear
@@ -106,17 +82,18 @@
   GLfloat u1, v1, u2, v2, len;
   GLfloat cos_ta, cos_ta_1da, cos_ta_2da, cos_ta_3da, cos_ta_4da;
   GLfloat sin_ta, sin_ta_1da, sin_ta_2da, sin_ta_3da, sin_ta_4da;
-  GLshort ix0, ix1, ix2, ix3, ix4, ix5;
+  GLushort ix0, ix1, ix2, ix3, ix4, ix5;
   vertex_t *vt, *nm;
-  GLshort *ix;
+  GLushort *ix;
 
   gear_t *gear = calloc(1, sizeof(gear_t));
   gear->nvertices = teeth * 40;
   gear->nindices = teeth * 66 * 3;
   gear->vertices = calloc(gear->nvertices, sizeof(vertex_t));
-  gear->indices = calloc(gear->nindices, sizeof(GLshort));
+  gear->indices = calloc(gear->nindices, sizeof(GLushort));
   memcpy(&gear->color[0], &color[0], sizeof(GLfloat) * 4);
 
+
   r0 = inner_radius;
   r1 = outer_radius - tooth_depth / 2.0;
   r2 = outer_radius + tooth_depth / 2.0;
@@ -133,7 +110,7 @@
 #define INDEX(a,b,c) ((*ix++ = a),(*ix++ = b),(*ix++ = c))
 
   for (i = 0; i < teeth; i++) {
-    ta = i * 2.0 * M_PI / teeth;
+    ta = i * 2.0 * M_PI / (teeth);
 
     cos_ta = cos(ta);
     cos_ta_1da = cos(ta + da);
@@ -145,7 +122,7 @@
     sin_ta_2da = sin(ta + 2 * da);
     sin_ta_3da = sin(ta + 3 * da);
     sin_ta_4da = sin(ta + 4 * da);
-               
+
     u1 = r2 * cos_ta_1da - r1 * cos_ta;
     v1 = r2 * sin_ta_1da - r1 * sin_ta;
     len = sqrt(u1 * u1 + v1 * v1);
@@ -157,8 +134,8 @@
     /* front face */
     ix0 = VERTEX(r0 * cos_ta,          r0 * sin_ta,          width * 0.5);
     ix1 = VERTEX(r1 * cos_ta,          r1 * sin_ta,          width * 0.5);
-    ix2 = VERTEX(r0 * cos_ta,          r0 * sin_ta,          width * 0.5);
-    ix3 = VERTEX(r1 * cos_ta_3da,      r1 * sin_ta_3da,      width * 0.5);
+    ix2 = VERTEX(r0 * cos_ta_2da,      r0 * sin_ta_2da,      width * 0.5);
+    ix3 = VERTEX(r1 * cos_ta_2da,      r1 * sin_ta_2da,      width * 0.5);
     ix4 = VERTEX(r0 * cos_ta_4da,      r0 * sin_ta_4da,      width * 0.5);
     ix5 = VERTEX(r1 * cos_ta_4da,      r1 * sin_ta_4da,      width * 0.5);
     for (j = 0; j < 6; j++) {
@@ -168,7 +145,7 @@
     INDEX(ix1, ix3, ix2);
     INDEX(ix2, ix3, ix4);
     INDEX(ix3, ix5, ix4);
-               
+
     /* front sides of teeth */
     ix0 = VERTEX(r1 * cos_ta,          r1 * sin_ta,          width * 0.5);
     ix1 = VERTEX(r2 * cos_ta_1da,      r2 * sin_ta_1da,      width * 0.5);
@@ -181,12 +158,12 @@
     INDEX(ix1, ix3, ix2);
 
     /* back face */
-    ix0 = VERTEX(r1 * cos_ta,          r1 * sin_ta,          -width * 0.5);
-    ix1 = VERTEX(r0 * cos_ta,          r0 * sin_ta,          -width * 0.5);
-    ix2 = VERTEX(r1 * cos_ta_3da,      r1 * sin_ta_3da,      -width * 0.5);
-    ix3 = VERTEX(r0 * cos_ta,          r0 * sin_ta,          -width * 0.5);
-    ix4 = VERTEX(r1 * cos_ta_4da,      r1 * sin_ta_4da,      -width * 0.5);
-    ix5 = VERTEX(r0 * cos_ta_4da,      r0 * sin_ta_4da,      -width * 0.5);
+    ix0 = VERTEX(r0 * cos_ta,          r0 * sin_ta,          -width * 0.5);
+    ix1 = VERTEX(r1 * cos_ta,          r1 * sin_ta,          -width * 0.5);
+    ix2 = VERTEX(r0 * cos_ta_2da,      r0 * sin_ta_2da,      -width * 0.5);
+    ix3 = VERTEX(r1 * cos_ta_2da,      r1 * sin_ta_2da,      -width * 0.5);
+    ix4 = VERTEX(r0 * cos_ta_4da,      r0 * sin_ta_4da,      -width * 0.5);
+    ix5 = VERTEX(r1 * cos_ta_4da,      r1 * sin_ta_4da,      -width * 0.5);
     for (j = 0; j < 6; j++) {
       NORMAL(0.0,                  0.0,                  -1.0);
     }
@@ -194,7 +171,7 @@
     INDEX(ix1, ix3, ix2);
     INDEX(ix2, ix3, ix4);
     INDEX(ix3, ix5, ix4);
-               
+
     /* back sides of teeth */
     ix0 = VERTEX(r1 * cos_ta_3da,      r1 * sin_ta_3da,      -width * 0.5);
     ix1 = VERTEX(r2 * cos_ta_2da,      r2 * sin_ta_2da,      -width * 0.5);
@@ -205,7 +182,7 @@
     }
     INDEX(ix0, ix1, ix2);
     INDEX(ix1, ix3, ix2);
-               
+
     /* draw outward faces of teeth */
     ix0 = VERTEX(r1 * cos_ta,          r1 * sin_ta,          width * 0.5);
     ix1 = VERTEX(r1 * cos_ta,          r1 * sin_ta,          -width * 0.5);
@@ -262,12 +239,11 @@
 
 
 void draw_gear(gear_t* gear) {
-
   glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, gear->color);
   glVertexPointer(3, GL_FLOAT, sizeof(vertex_t), gear->vertices[0].pos);
   glNormalPointer(GL_FLOAT, sizeof(vertex_t), gear->vertices[0].norm);
   glDrawElements(GL_TRIANGLES, gear->nindices/3, GL_UNSIGNED_SHORT,
-                   gear->indices);
+                 gear->indices);
 }
 
 static GLfloat view_rotx = 20.0, view_roty = 30.0, view_rotz = 0.0;
@@ -277,39 +253,38 @@
 static void
 draw(void)
 {
+  glClearColor(0.0, 0.0, 0.0, 0.0);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
   glPushMatrix();
 
-    glTranslatef(0.0, 0.0, -viewDist);
+  glTranslatef(0.0, 0.0, -viewDist);
 
-    glRotatef(view_rotx, 1.0, 0.0, 0.0);
-    glRotatef(view_roty, 0.0, 1.0, 0.0);
-    glRotatef(view_rotz, 0.0, 0.0, 1.0);
+  glRotatef(view_rotx, 1.0, 0.0, 0.0);
+  glRotatef(view_roty, 0.0, 1.0, 0.0);
+  glRotatef(view_rotz, 0.0, 0.0, 1.0);
 
-    glPushMatrix();
-      glTranslatef(-3.0, -2.0, 0.0);
-      glRotatef(angle, 0.0, 0.0, 1.0);
-      draw_gear(gear1);
-    glPopMatrix();
+  glPushMatrix();
+  glTranslatef(-3.0, -2.0, 0.0);
+  glRotatef(angle, 0.0, 0.0, 1.0);
+  draw_gear(gear1);
+  glPopMatrix();
 
-    glPushMatrix();
-      glTranslatef(3.1, -2.0, 0.0);
-      glRotatef(-2.0 * angle - 9.0, 0.0, 0.0, 1.0);
-      draw_gear(gear2);
-    glPopMatrix();
+  glPushMatrix();
+  glTranslatef(3.1, -2.0, 0.0);
+  glRotatef(-2.0 * angle - 9.0, 0.0, 0.0, 1.0);
+  draw_gear(gear2);
+  glPopMatrix();
 
-    glPushMatrix();
-      glTranslatef(-3.1, 4.2, 0.0);
-      glRotatef(-2.0 * angle - 25.0, 0.0, 0.0, 1.0);
-      draw_gear(gear3);
-    glPopMatrix();
+  glPushMatrix();
+  glTranslatef(-3.1, 4.2, 0.0);
+  glRotatef(-2.0 * angle - 25.0, 0.0, 0.0, 1.0);
+  draw_gear(gear3);
+  glPopMatrix();
 
   glPopMatrix();
-  glFinish();
 }
 
-
 /* new window size or exposure */
 static void
 reshape(int width, int height)
@@ -322,16 +297,16 @@
   glFrustumf(-1.0, 1.0, -h, h, 5.0, 200.0);
   glMatrixMode(GL_MODELVIEW);
 }
- 
 
-static void
-init(int argc, char *argv[])
-{
+void initialize() {
+  glShadeModel(GL_SMOOTH);
+  glEnableClientState(GL_NORMAL_ARRAY);
+  glEnableClientState(GL_VERTEX_ARRAY);
+
   static GLfloat pos[4] = {5.0, 5.0, 10.0, 0.0};
   static GLfloat red[4] = {0.8, 0.1, 0.0, 1.0};
   static GLfloat green[4] = {0.0, 0.8, 0.2, 1.0};
   static GLfloat blue[4] = {0.2, 0.2, 1.0, 1.0};
-  GLint i;
 
   glLightfv(GL_LIGHT0, GL_POSITION, pos);
   glEnable(GL_CULL_FACE);
@@ -339,77 +314,27 @@
   glEnable(GL_LIGHT0);
   glEnable(GL_DEPTH_TEST);
 
-  glShadeModel(GL_SMOOTH);
-
-  glEnableClientState(GL_NORMAL_ARRAY);
-  glEnableClientState(GL_VERTEX_ARRAY);
-
-  for ( i=1; i<argc; i++ ) {
-    if (strcmp(argv[i], "-info")==0) {
-      printf("GL_RENDERER   = %s
-", (char *) glGetString(GL_RENDERER));
-      printf("GL_VERSION    = %s
-", (char *) glGetString(GL_VERSION));
-      printf("GL_VENDOR     = %s
-", (char *) glGetString(GL_VENDOR));
-      printf("GL_EXTENSIONS = %s
-", (char *) glGetString(GL_EXTENSIONS));
-    }
-    else if ( strcmp(argv[i], "-exit")==0) {
-      autoexit = 30;
-      printf("Auto Exit after %i seconds.
-", autoexit );
-    }
-  }
-
   /* make the gears */
   gear1 = gear(1.0, 4.0, 1.0, 20, 0.7, red);
   gear2 = gear(0.5, 2.0, 2.0, 10, 0.7, green);
   gear3 = gear(1.3, 2.0, 0.5, 10, 0.7, blue);
 }
 
-static void run_gears(GLint ttr)
-{
-  double st = current_time();
-  double ct = st;
-  double seconds = st;
-  double fps;
-  int    frames = 0;
-       
-  while ((ttr == 0) ||(ct - st < ttr))
-  {
-    double tt = current_time();
-    double dt = tt - ct;
-    ct = tt;
-    
+void RunGears() {
+  double dt = 0.01666;
+
+  initialize();
+  reshape(600, 600);
+
+  while (1) {
+    dt = 0.01666;
+
     /* advance rotation for next frame */
     angle += 70.0 * dt;  /* 70 degrees per second */
     if (angle > 3600.0)
-          angle -= 3600.0;        
-    draw(); 
-    postEGLWindow();
-    frames++;
-    dt = ct - seconds;
-    if (dt >= 5.0) 
-	{
-      fps = frames / dt;
-	  printf("%d frames in %3.1f seconds = %6.3f FPS
-", frames, dt, fps);
-	  seconds = ct;
-	  frames = 0;
-    }
-  }       
-}
+      angle -= 3600.0;
 
-int
-main(int argc, char *argv[])
-{
-    int width  = 300;
-    int height = 300;
-
-    createEGLWindow(width, height, "Gears");    
-    init(argc, argv);
-    reshape(width, height);
-    run_gears(autoexit);
-    return 0;
+    draw();
+    HandleFrame();
+  }
 }
diff --git a/opengl/simple-egl.c b/opengl/simple-egl.c
index cd7408e..11a47d0 100644
--- a/opengl/simple-egl.c
+++ b/opengl/simple-egl.c
@@ -21,7 +21,14 @@
  * DEALINGS IN THE SOFTWARE.
  */
 
-#include "config.h"
+/*
+ * Port to Mendel Linux by Peter Nordström 1 June 2020
+ *
+ * GL code is done in glesgears.c and es2gears.c for GLES1 and GLES2
+ * respectively
+ *
+ */
+
 
 #include <stdint.h>
 #include <stdio.h>
@@ -38,859 +45,406 @@
 #include <wayland-egl.h>
 #include <wayland-cursor.h>
 
+#if GLES==2
 #include <GLES2/gl2.h>
+#else
+#include <GLES/gl.h>
+#endif
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
 
-#include "xdg-shell-client-protocol.h"
+#include <libgen.h>
+#include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
 
-#include "shared/helpers.h"
-#include "shared/platform.h"
-#include "shared/weston-egl-ext.h"
+#define WINDOW_WIDTH 600
+#define WINDOW_HEIGHT 600
+#define GOLDEN_IMG_DIR "/home/mendel/golden_images"
+#define NUM_GOLDEN_IMAGES 10
+
+static bool test = false;
+static bool generate_ref_images = false;
+static char *AppName;
 
 struct window;
-struct seat;
 
 struct display {
-	struct wl_display *display;
-	struct wl_registry *registry;
-	struct wl_compositor *compositor;
-	struct xdg_wm_base *wm_base;
-	struct wl_seat *seat;
-	struct wl_pointer *pointer;
-	struct wl_touch *touch;
-	struct wl_keyboard *keyboard;
-	struct wl_shm *shm;
-	struct wl_cursor_theme *cursor_theme;
-	struct wl_cursor *default_cursor;
-	struct wl_surface *cursor_surface;
-	struct {
-		EGLDisplay dpy;
-		EGLContext ctx;
-		EGLConfig conf;
-	} egl;
-	struct window *window;
-
-	PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage;
+  struct wl_display *display;
+  struct wl_registry *registry;
+  struct wl_compositor *compositor;
+  struct wl_shell *shell;
+  struct {
+    EGLDisplay dpy;
+    EGLContext ctx;
+    EGLConfig conf;
+  } egl;
+  struct window *window;
 };
 
 struct geometry {
-	int width, height;
+  int width, height;
 };
 
 struct window {
-	struct display *display;
-	struct geometry geometry, window_size;
-	struct {
-		GLuint rotation_uniform;
-		GLuint pos;
-		GLuint col;
-	} gl;
+  struct display *display;
+  struct geometry geometry, window_size;
+  struct {
+    GLuint rotation_uniform;
+    GLuint pos;
+    GLuint col;
+  } gl;
 
-	uint32_t benchmark_time, frames;
-	struct wl_egl_window *native;
-	struct wl_surface *surface;
-	struct xdg_surface *xdg_surface;
-	struct xdg_toplevel *xdg_toplevel;
-	EGLSurface egl_surface;
-	struct wl_callback *callback;
-	int fullscreen, maximized, opaque, buffer_size, frame_sync, delay;
-	bool wait_for_configure;
+  uint32_t benchmark_time, frames;
+  struct wl_egl_window *native;
+  struct wl_surface *surface;
+  EGLSurface egl_surface;
+  int fullscreen, maximized, opaque, buffer_size, frame_sync, delay;
+  bool wait_for_configure;
 };
 
+extern void RunGears(void *);
+
+/* return current time (in seconds) */
+static double
+    current_time(void)
+{
+  struct timeval tv;
+  (void) gettimeofday(&tv, NULL );
+
+  return (double) tv.tv_sec + tv.tv_usec / 1000000.0;
+}
+
+static struct window *glwindow;
+static GLubyte pixeldata[WINDOW_WIDTH * WINDOW_HEIGHT * 4];
+static GLubyte golden_image_data[WINDOW_WIDTH * WINDOW_HEIGHT * 4];
+void CheckFrame(int frame) {
+  // This is a bit ugly and should be threaded, but for the purpose of
+  // this testing it's okay
+  FILE *fp;
+  char filename[50];
+  int size;
+  sprintf(filename, "%s/%s_frame%d", GOLDEN_IMG_DIR, AppName, frame);
+
+  // Read the framebuffer
+  glReadPixels(0, 0, glwindow->geometry.width,
+	       glwindow->geometry.height,
+	       GL_RGBA,
+	       GL_UNSIGNED_BYTE,
+	       pixeldata);
+  if (test) {
+    // Compare the current frame with a saved golden image
+    fp = fopen(filename, "r");
+    if (fp == 0) {
+      if (frame == 0) {
+        printf("FAIL : No golden images to compare with\n");
+        exit(1);
+      } else {
+        printf("PASS : All %d frames identical to golden images\n", frame - 1);
+        exit(0);
+      }
+    }
+    size = fread(golden_image_data, 4,
+		 sizeof(golden_image_data)/4, fp);
+    if (size != sizeof(golden_image_data)/4) {
+      printf("FAIL : golden image has wrong size\n");
+      fclose(fp);
+      exit(1);
+    }
+    for (int i = 0; i < sizeof(golden_image_data); i++) {
+      if (golden_image_data[i] != pixeldata[i]) {
+	printf("FAIL : golden image mismatch frame: %d\n", frame);
+	fclose(fp);
+	exit(1);
+      }
+    }
+  } else if (generate_ref_images) {
+    // Save the frame as a golden image
+    fp = fopen(filename, "w");
+    fwrite(pixeldata, 4, sizeof(pixeldata)/4, fp);
+    fclose(fp);
+    if (frame == NUM_GOLDEN_IMAGES) {
+      printf("Done generating golden images, exiting\n");
+      exit(1);
+    }
+  }
+}
+
+void HandleFrame(void) {
+  static int frame0, frame = 0;
+  static double tRate0 = -1.0;
+  double t = current_time();
+
+  if (frame % 60 == 0) {
+    CheckFrame(frame/60);
+  }
+  eglSwapBuffers(glwindow->display->egl.dpy, glwindow->egl_surface);
+  frame++;
+
+  if (tRate0 < 0.0) {
+    tRate0 = t;
+    frame0 = frame;
+  }
+  if (t - tRate0 >= 5.0) {
+    GLfloat seconds = t - tRate0;
+    GLfloat fps = (frame - frame0) / seconds;
+    printf("%d frames in %3.1f seconds = %6.3f FPS\n",
+	   (frame - frame0), seconds, fps);
+    fflush(stdout);
+    tRate0 = t;
+    frame0 = frame;
+  }
+
+}
+
 static const char *vert_shader_text =
-	"uniform mat4 rotation;\n"
-	"attribute vec4 pos;\n"
-	"attribute vec4 color;\n"
-	"varying vec4 v_color;\n"
-	"void main() {\n"
-	"  gl_Position = rotation * pos;\n"
-	"  v_color = color;\n"
-	"}\n";
+    "uniform mat4 rotation;\n"
+    "attribute vec4 pos;\n"
+    "attribute vec4 color;\n"
+    "varying vec4 v_color;\n"
+    "void main() {\n"
+    "  gl_Position = rotation * pos;\n"
+    "  v_color = color;\n"
+    "}\n";
 
 static const char *frag_shader_text =
-	"precision mediump float;\n"
-	"varying vec4 v_color;\n"
-	"void main() {\n"
-	"  gl_FragColor = v_color;\n"
-	"}\n";
+    "precision mediump float;\n"
+    "varying vec4 v_color;\n"
+    "void main() {\n"
+    "  gl_FragColor = v_color;\n"
+    "}\n";
 
 static int running = 1;
 
 static void
-init_egl(struct display *display, struct window *window)
+    init_egl(struct display *display, struct window *window)
 {
-	static const struct {
-		char *extension, *entrypoint;
-	} swap_damage_ext_to_entrypoint[] = {
-		{
-			.extension = "EGL_EXT_swap_buffers_with_damage",
-			.entrypoint = "eglSwapBuffersWithDamageEXT",
-		},
-		{
-			.extension = "EGL_KHR_swap_buffers_with_damage",
-			.entrypoint = "eglSwapBuffersWithDamageKHR",
-		},
-	};
+  static const EGLint context_attribs[] = {
+    EGL_CONTEXT_CLIENT_VERSION, GLES,
+    EGL_NONE
+  };
+  const char *extensions;
 
-	static const EGLint context_attribs[] = {
-		EGL_CONTEXT_CLIENT_VERSION, 2,
-		EGL_NONE
-	};
-	const char *extensions;
+  EGLint config_attribs[] = {
+    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
+    EGL_RED_SIZE, 8,
+    EGL_GREEN_SIZE, 8,
+    EGL_BLUE_SIZE, 8,
+    EGL_DEPTH_SIZE, 16,
+    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+    EGL_NONE
+  };
 
-	EGLint config_attribs[] = {
-		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
-		EGL_RED_SIZE, 1,
-		EGL_GREEN_SIZE, 1,
-		EGL_BLUE_SIZE, 1,
-		EGL_ALPHA_SIZE, 1,
-		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
-		EGL_NONE
-	};
+  EGLint major, minor, n, count, i, size;
+  EGLConfig *configs;
+  EGLBoolean ret;
 
-	EGLint major, minor, n, count, i, size;
-	EGLConfig *configs;
-	EGLBoolean ret;
+  if (window->opaque || window->buffer_size == 16)
+    config_attribs[9] = 0;
 
-	if (window->opaque || window->buffer_size == 16)
-		config_attribs[9] = 0;
+  display->egl.dpy = eglGetDisplay(display->display);
 
-	display->egl.dpy =
-		weston_platform_get_egl_display(EGL_PLATFORM_WAYLAND_KHR,
-						display->display, NULL);
-	assert(display->egl.dpy);
+  ret = eglInitialize(display->egl.dpy, &major, &minor);
+  assert(ret == EGL_TRUE);
+  ret = eglBindAPI(EGL_OPENGL_ES_API);
+  assert(ret == EGL_TRUE);
 
-	ret = eglInitialize(display->egl.dpy, &major, &minor);
-	assert(ret == EGL_TRUE);
-	ret = eglBindAPI(EGL_OPENGL_ES_API);
-	assert(ret == EGL_TRUE);
+  if (!eglGetConfigs(display->egl.dpy, NULL, 0, &count) || count < 1)
+    assert(0);
 
-	if (!eglGetConfigs(display->egl.dpy, NULL, 0, &count) || count < 1)
-		assert(0);
+  configs = calloc(count, sizeof *configs);
+  assert(configs);
 
-	configs = calloc(count, sizeof *configs);
-	assert(configs);
+  ret = eglChooseConfig(display->egl.dpy, config_attribs,
+			configs, 1, &n);
+  assert(ret && n >= 1);
 
-	ret = eglChooseConfig(display->egl.dpy, config_attribs,
-			      configs, count, &n);
-	assert(ret && n >= 1);
+  display->egl.conf = configs[0];
 
-	for (i = 0; i < n; i++) {
-		eglGetConfigAttrib(display->egl.dpy,
-				   configs[i], EGL_BUFFER_SIZE, &size);
-		if (window->buffer_size == size) {
-			display->egl.conf = configs[i];
-			break;
-		}
-	}
-	free(configs);
-	if (display->egl.conf == NULL) {
-		fprintf(stderr, "did not find config with buffer size %d\n",
-			window->buffer_size);
-		exit(EXIT_FAILURE);
-	}
+  free(configs);
+  if (display->egl.conf == NULL) {
+    fprintf(stderr, "did not find config with buffer size %d\n",
+	    window->buffer_size);
+    exit(EXIT_FAILURE);
+  }
 
-	display->egl.ctx = eglCreateContext(display->egl.dpy,
-					    display->egl.conf,
-					    EGL_NO_CONTEXT, context_attribs);
-	assert(display->egl.ctx);
-
-	display->swap_buffers_with_damage = NULL;
-	extensions = eglQueryString(display->egl.dpy, EGL_EXTENSIONS);
-	if (extensions &&
-	    weston_check_egl_extension(extensions, "EGL_EXT_buffer_age")) {
-		for (i = 0; i < (int) ARRAY_LENGTH(swap_damage_ext_to_entrypoint); i++) {
-			if (weston_check_egl_extension(extensions,
-						       swap_damage_ext_to_entrypoint[i].extension)) {
-				/* The EXTPROC is identical to the KHR one */
-				display->swap_buffers_with_damage =
-					(PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC)
-					eglGetProcAddress(swap_damage_ext_to_entrypoint[i].entrypoint);
-				break;
-			}
-		}
-	}
-
-	if (display->swap_buffers_with_damage)
-		printf("has EGL_EXT_buffer_age and %s\n", swap_damage_ext_to_entrypoint[i].extension);
+  display->egl.ctx = eglCreateContext(display->egl.dpy,
+				      display->egl.conf,
+				      EGL_NO_CONTEXT, context_attribs);
+  assert(display->egl.ctx);
 
 }
 
 static void
-fini_egl(struct display *display)
+    fini_egl(struct display *display)
 {
-	eglTerminate(display->egl.dpy);
-	eglReleaseThread();
-}
-
-static GLuint
-create_shader(struct window *window, const char *source, GLenum shader_type)
-{
-	GLuint shader;
-	GLint status;
-
-	shader = glCreateShader(shader_type);
-	assert(shader != 0);
-
-	glShaderSource(shader, 1, (const char **) &source, NULL);
-	glCompileShader(shader);
-
-	glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
-	if (!status) {
-		char log[1000];
-		GLsizei len;
-		glGetShaderInfoLog(shader, 1000, &len, log);
-		fprintf(stderr, "Error: compiling %s: %.*s\n",
-			shader_type == GL_VERTEX_SHADER ? "vertex" : "fragment",
-			len, log);
-		exit(1);
-	}
-
-	return shader;
+  eglTerminate(display->egl.dpy);
+  eglReleaseThread();
 }
 
 static void
-init_gl(struct window *window)
+    create_surface(struct window *window)
 {
-	GLuint frag, vert;
-	GLuint program;
-	GLint status;
+  struct display *display = window->display;
+  struct wl_shell_surface *shell_surface;
 
-	frag = create_shader(window, frag_shader_text, GL_FRAGMENT_SHADER);
-	vert = create_shader(window, vert_shader_text, GL_VERTEX_SHADER);
+  EGLBoolean ret;
 
-	program = glCreateProgram();
-	glAttachShader(program, frag);
-	glAttachShader(program, vert);
-	glLinkProgram(program);
+  window->surface = wl_compositor_create_surface(display->compositor);
 
-	glGetProgramiv(program, GL_LINK_STATUS, &status);
-	if (!status) {
-		char log[1000];
-		GLsizei len;
-		glGetProgramInfoLog(program, 1000, &len, log);
-		fprintf(stderr, "Error: linking:\n%.*s\n", len, log);
-		exit(1);
-	}
+  shell_surface = wl_shell_get_shell_surface(display->shell,
+					     window->surface);
+  wl_shell_surface_set_toplevel(shell_surface);
 
-	glUseProgram(program);
+  window->native =
+      wl_egl_window_create(window->surface,
+			   window->geometry.width,
+			   window->geometry.height);
+  window->egl_surface = eglCreateWindowSurface(display->egl.dpy,
+					       display->egl.conf,
+					       window->native, NULL);
+  window->wait_for_configure = true;
+  wl_surface_commit(window->surface);
 
-	window->gl.pos = 0;
-	window->gl.col = 1;
+  ret = eglMakeCurrent(window->display->egl.dpy, window->egl_surface,
+		       window->egl_surface, window->display->egl.ctx);
+  assert(ret == EGL_TRUE);
 
-	glBindAttribLocation(program, window->gl.pos, "pos");
-	glBindAttribLocation(program, window->gl.col, "color");
-	glLinkProgram(program);
+  if (!window->frame_sync)
+    eglSwapInterval(display->egl.dpy, 0);
 
-	window->gl.rotation_uniform =
-		glGetUniformLocation(program, "rotation");
 }
 
 static void
-handle_surface_configure(void *data, struct xdg_surface *surface,
-			 uint32_t serial)
+    destroy_surface(struct window *window)
 {
-	struct window *window = data;
+  /* Required, otherwise segfault in egl_dri2.c: dri2_make_current()
+   * on eglReleaseThread(). */
+  eglMakeCurrent(window->display->egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
+		 EGL_NO_CONTEXT);
 
-	xdg_surface_ack_configure(surface, serial);
+  eglDestroySurface(window->display->egl.dpy,
+		    window->egl_surface);
+  wl_egl_window_destroy(window->native);
+  wl_surface_destroy(window->surface);
 
-	window->wait_for_configure = false;
-}
-
-static const struct xdg_surface_listener xdg_surface_listener = {
-	handle_surface_configure
-};
-
-static void
-handle_toplevel_configure(void *data, struct xdg_toplevel *toplevel,
-			  int32_t width, int32_t height,
-			  struct wl_array *states)
-{
-	struct window *window = data;
-	uint32_t *p;
-
-	window->fullscreen = 0;
-	window->maximized = 0;
-	wl_array_for_each(p, states) {
-		uint32_t state = *p;
-		switch (state) {
-		case XDG_TOPLEVEL_STATE_FULLSCREEN:
-			window->fullscreen = 1;
-			break;
-		case XDG_TOPLEVEL_STATE_MAXIMIZED:
-			window->maximized = 1;
-			break;
-		}
-	}
-
-	if (width > 0 && height > 0) {
-		if (!window->fullscreen && !window->maximized) {
-			window->window_size.width = width;
-			window->window_size.height = height;
-		}
-		window->geometry.width = width;
-		window->geometry.height = height;
-	} else if (!window->fullscreen && !window->maximized) {
-		window->geometry = window->window_size;
-	}
-
-	if (window->native)
-		wl_egl_window_resize(window->native,
-				     window->geometry.width,
-				     window->geometry.height, 0, 0);
 }
 
 static void
-handle_toplevel_close(void *data, struct xdg_toplevel *xdg_toplevel)
+    registry_handle_global(void *data, struct wl_registry *registry,
+			   uint32_t name, const char *interface, uint32_t version)
 {
-	running = 0;
-}
+  struct display *d = data;
 
-static const struct xdg_toplevel_listener xdg_toplevel_listener = {
-	handle_toplevel_configure,
-	handle_toplevel_close,
-};
-
-static void
-create_surface(struct window *window)
-{
-	struct display *display = window->display;
-	EGLBoolean ret;
-
-	window->surface = wl_compositor_create_surface(display->compositor);
-
-	window->native =
-		wl_egl_window_create(window->surface,
-				     window->geometry.width,
-				     window->geometry.height);
-	window->egl_surface =
-		weston_platform_create_egl_surface(display->egl.dpy,
-						   display->egl.conf,
-						   window->native, NULL);
-
-	window->xdg_surface = xdg_wm_base_get_xdg_surface(display->wm_base,
-							  window->surface);
-	xdg_surface_add_listener(window->xdg_surface,
-				 &xdg_surface_listener, window);
-
-	window->xdg_toplevel =
-		xdg_surface_get_toplevel(window->xdg_surface);
-	xdg_toplevel_add_listener(window->xdg_toplevel,
-				  &xdg_toplevel_listener, window);
-
-	xdg_toplevel_set_title(window->xdg_toplevel, "simple-egl");
-
-	window->wait_for_configure = true;
-	wl_surface_commit(window->surface);
-
-	ret = eglMakeCurrent(window->display->egl.dpy, window->egl_surface,
-			     window->egl_surface, window->display->egl.ctx);
-	assert(ret == EGL_TRUE);
-
-	if (!window->frame_sync)
-		eglSwapInterval(display->egl.dpy, 0);
-
-	if (!display->wm_base)
-		return;
-
-	if (window->fullscreen)
-		xdg_toplevel_set_fullscreen(window->xdg_toplevel, NULL);
+  if (strcmp(interface, "wl_compositor") == 0) {
+    d->compositor =
+	wl_registry_bind(registry, name,
+			 &wl_compositor_interface,
+			 1);
+  } else if (strcmp(interface, "wl_shell") == 0) {
+    d->shell = wl_registry_bind(registry, name,
+				&wl_shell_interface, 1);
+  }
 }
 
 static void
-destroy_surface(struct window *window)
-{
-	/* Required, otherwise segfault in egl_dri2.c: dri2_make_current()
-	 * on eglReleaseThread(). */
-	eglMakeCurrent(window->display->egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
-		       EGL_NO_CONTEXT);
-
-	weston_platform_destroy_egl_surface(window->display->egl.dpy,
-					    window->egl_surface);
-	wl_egl_window_destroy(window->native);
-
-	if (window->xdg_toplevel)
-		xdg_toplevel_destroy(window->xdg_toplevel);
-	if (window->xdg_surface)
-		xdg_surface_destroy(window->xdg_surface);
-	wl_surface_destroy(window->surface);
-
-	if (window->callback)
-		wl_callback_destroy(window->callback);
-}
-
-static void
-redraw(void *data, struct wl_callback *callback, uint32_t time)
-{
-	struct window *window = data;
-	struct display *display = window->display;
-	static const GLfloat verts[3][2] = {
-		{ -0.5, -0.5 },
-		{  0.5, -0.5 },
-		{  0,    0.5 }
-	};
-	static const GLfloat colors[3][3] = {
-		{ 1, 0, 0 },
-		{ 0, 1, 0 },
-		{ 0, 0, 1 }
-	};
-	GLfloat angle;
-	GLfloat rotation[4][4] = {
-		{ 1, 0, 0, 0 },
-		{ 0, 1, 0, 0 },
-		{ 0, 0, 1, 0 },
-		{ 0, 0, 0, 1 }
-	};
-	static const uint32_t speed_div = 5, benchmark_interval = 5;
-	struct wl_region *region;
-	EGLint rect[4];
-	EGLint buffer_age = 0;
-	struct timeval tv;
-
-	assert(window->callback == callback);
-	window->callback = NULL;
-
-	if (callback)
-		wl_callback_destroy(callback);
-
-	gettimeofday(&tv, NULL);
-	time = tv.tv_sec * 1000 + tv.tv_usec / 1000;
-	if (window->frames == 0)
-		window->benchmark_time = time;
-	if (time - window->benchmark_time > (benchmark_interval * 1000)) {
-		printf("%d frames in %d seconds: %f fps\n",
-		       window->frames,
-		       benchmark_interval,
-		       (float) window->frames / benchmark_interval);
-		window->benchmark_time = time;
-		window->frames = 0;
-	}
-
-	angle = (time / speed_div) % 360 * M_PI / 180.0;
-	rotation[0][0] =  cos(angle);
-	rotation[0][2] =  sin(angle);
-	rotation[2][0] = -sin(angle);
-	rotation[2][2] =  cos(angle);
-
-	if (display->swap_buffers_with_damage)
-		eglQuerySurface(display->egl.dpy, window->egl_surface,
-				EGL_BUFFER_AGE_EXT, &buffer_age);
-
-	glViewport(0, 0, window->geometry.width, window->geometry.height);
-
-	glUniformMatrix4fv(window->gl.rotation_uniform, 1, GL_FALSE,
-			   (GLfloat *) rotation);
-
-	glClearColor(0.0, 0.0, 0.0, 0.5);
-	glClear(GL_COLOR_BUFFER_BIT);
-
-	glVertexAttribPointer(window->gl.pos, 2, GL_FLOAT, GL_FALSE, 0, verts);
-	glVertexAttribPointer(window->gl.col, 3, GL_FLOAT, GL_FALSE, 0, colors);
-	glEnableVertexAttribArray(window->gl.pos);
-	glEnableVertexAttribArray(window->gl.col);
-
-	glDrawArrays(GL_TRIANGLES, 0, 3);
-
-	glDisableVertexAttribArray(window->gl.pos);
-	glDisableVertexAttribArray(window->gl.col);
-
-	usleep(window->delay);
-
-	if (window->opaque || window->fullscreen) {
-		region = wl_compositor_create_region(window->display->compositor);
-		wl_region_add(region, 0, 0,
-			      window->geometry.width,
-			      window->geometry.height);
-		wl_surface_set_opaque_region(window->surface, region);
-		wl_region_destroy(region);
-	} else {
-		wl_surface_set_opaque_region(window->surface, NULL);
-	}
-
-	if (display->swap_buffers_with_damage && buffer_age > 0) {
-		rect[0] = window->geometry.width / 4 - 1;
-		rect[1] = window->geometry.height / 4 - 1;
-		rect[2] = window->geometry.width / 2 + 2;
-		rect[3] = window->geometry.height / 2 + 2;
-		display->swap_buffers_with_damage(display->egl.dpy,
-						  window->egl_surface,
-						  rect, 1);
-	} else {
-		eglSwapBuffers(display->egl.dpy, window->egl_surface);
-	}
-	window->frames++;
-}
-
-static void
-pointer_handle_enter(void *data, struct wl_pointer *pointer,
-		     uint32_t serial, struct wl_surface *surface,
-		     wl_fixed_t sx, wl_fixed_t sy)
-{
-	struct display *display = data;
-	struct wl_buffer *buffer;
-	struct wl_cursor *cursor = display->default_cursor;
-	struct wl_cursor_image *image;
-
-	if (display->window->fullscreen)
-		wl_pointer_set_cursor(pointer, serial, NULL, 0, 0);
-	else if (cursor) {
-		image = display->default_cursor->images[0];
-		buffer = wl_cursor_image_get_buffer(image);
-		if (!buffer)
-			return;
-		wl_pointer_set_cursor(pointer, serial,
-				      display->cursor_surface,
-				      image->hotspot_x,
-				      image->hotspot_y);
-		wl_surface_attach(display->cursor_surface, buffer, 0, 0);
-		wl_surface_damage(display->cursor_surface, 0, 0,
-				  image->width, image->height);
-		wl_surface_commit(display->cursor_surface);
-	}
-}
-
-static void
-pointer_handle_leave(void *data, struct wl_pointer *pointer,
-		     uint32_t serial, struct wl_surface *surface)
-{
-}
-
-static void
-pointer_handle_motion(void *data, struct wl_pointer *pointer,
-		      uint32_t time, wl_fixed_t sx, wl_fixed_t sy)
-{
-}
-
-static void
-pointer_handle_button(void *data, struct wl_pointer *wl_pointer,
-		      uint32_t serial, uint32_t time, uint32_t button,
-		      uint32_t state)
-{
-	struct display *display = data;
-
-	if (!display->window->xdg_toplevel)
-		return;
-
-	if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED)
-		xdg_toplevel_move(display->window->xdg_toplevel,
-				  display->seat, serial);
-}
-
-static void
-pointer_handle_axis(void *data, struct wl_pointer *wl_pointer,
-		    uint32_t time, uint32_t axis, wl_fixed_t value)
-{
-}
-
-static const struct wl_pointer_listener pointer_listener = {
-	pointer_handle_enter,
-	pointer_handle_leave,
-	pointer_handle_motion,
-	pointer_handle_button,
-	pointer_handle_axis,
-};
-
-static void
-touch_handle_down(void *data, struct wl_touch *wl_touch,
-		  uint32_t serial, uint32_t time, struct wl_surface *surface,
-		  int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
-{
-	struct display *d = (struct display *)data;
-
-	if (!d->wm_base)
-		return;
-
-	xdg_toplevel_move(d->window->xdg_toplevel, d->seat, serial);
-}
-
-static void
-touch_handle_up(void *data, struct wl_touch *wl_touch,
-		uint32_t serial, uint32_t time, int32_t id)
-{
-}
-
-static void
-touch_handle_motion(void *data, struct wl_touch *wl_touch,
-		    uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
-{
-}
-
-static void
-touch_handle_frame(void *data, struct wl_touch *wl_touch)
-{
-}
-
-static void
-touch_handle_cancel(void *data, struct wl_touch *wl_touch)
-{
-}
-
-static const struct wl_touch_listener touch_listener = {
-	touch_handle_down,
-	touch_handle_up,
-	touch_handle_motion,
-	touch_handle_frame,
-	touch_handle_cancel,
-};
-
-static void
-keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
-		       uint32_t format, int fd, uint32_t size)
-{
-	/* Just so we don’t leak the keymap fd */
-	close(fd);
-}
-
-static void
-keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
-		      uint32_t serial, struct wl_surface *surface,
-		      struct wl_array *keys)
-{
-}
-
-static void
-keyboard_handle_leave(void *data, struct wl_keyboard *keyboard,
-		      uint32_t serial, struct wl_surface *surface)
-{
-}
-
-static void
-keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
-		    uint32_t serial, uint32_t time, uint32_t key,
-		    uint32_t state)
-{
-	struct display *d = data;
-
-	if (!d->wm_base)
-		return;
-
-	if (key == KEY_F11 && state) {
-		if (d->window->fullscreen)
-			xdg_toplevel_unset_fullscreen(d->window->xdg_toplevel);
-		else
-			xdg_toplevel_set_fullscreen(d->window->xdg_toplevel, NULL);
-	} else if (key == KEY_ESC && state)
-		running = 0;
-}
-
-static void
-keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard,
-			  uint32_t serial, uint32_t mods_depressed,
-			  uint32_t mods_latched, uint32_t mods_locked,
-			  uint32_t group)
-{
-}
-
-static const struct wl_keyboard_listener keyboard_listener = {
-	keyboard_handle_keymap,
-	keyboard_handle_enter,
-	keyboard_handle_leave,
-	keyboard_handle_key,
-	keyboard_handle_modifiers,
-};
-
-static void
-seat_handle_capabilities(void *data, struct wl_seat *seat,
-			 enum wl_seat_capability caps)
-{
-	struct display *d = data;
-
-	if ((caps & WL_SEAT_CAPABILITY_POINTER) && !d->pointer) {
-		d->pointer = wl_seat_get_pointer(seat);
-		wl_pointer_add_listener(d->pointer, &pointer_listener, d);
-	} else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && d->pointer) {
-		wl_pointer_destroy(d->pointer);
-		d->pointer = NULL;
-	}
-
-	if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !d->keyboard) {
-		d->keyboard = wl_seat_get_keyboard(seat);
-		wl_keyboard_add_listener(d->keyboard, &keyboard_listener, d);
-	} else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && d->keyboard) {
-		wl_keyboard_destroy(d->keyboard);
-		d->keyboard = NULL;
-	}
-
-	if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !d->touch) {
-		d->touch = wl_seat_get_touch(seat);
-		wl_touch_set_user_data(d->touch, d);
-		wl_touch_add_listener(d->touch, &touch_listener, d);
-	} else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && d->touch) {
-		wl_touch_destroy(d->touch);
-		d->touch = NULL;
-	}
-}
-
-static const struct wl_seat_listener seat_listener = {
-	seat_handle_capabilities,
-};
-
-static void
-xdg_wm_base_ping(void *data, struct xdg_wm_base *shell, uint32_t serial)
-{
-	xdg_wm_base_pong(shell, serial);
-}
-
-static const struct xdg_wm_base_listener wm_base_listener = {
-	xdg_wm_base_ping,
-};
-
-static void
-registry_handle_global(void *data, struct wl_registry *registry,
-		       uint32_t name, const char *interface, uint32_t version)
-{
-	struct display *d = data;
-
-	if (strcmp(interface, "wl_compositor") == 0) {
-		d->compositor =
-			wl_registry_bind(registry, name,
-					 &wl_compositor_interface,
-					 MIN(version, 4));
-	} else if (strcmp(interface, "xdg_wm_base") == 0) {
-		d->wm_base = wl_registry_bind(registry, name,
-					      &xdg_wm_base_interface, 1);
-		xdg_wm_base_add_listener(d->wm_base, &wm_base_listener, d);
-	} else if (strcmp(interface, "wl_seat") == 0) {
-		d->seat = wl_registry_bind(registry, name,
-					   &wl_seat_interface, 1);
-		wl_seat_add_listener(d->seat, &seat_listener, d);
-	} else if (strcmp(interface, "wl_shm") == 0) {
-		d->shm = wl_registry_bind(registry, name,
-					  &wl_shm_interface, 1);
-		d->cursor_theme = wl_cursor_theme_load(NULL, 32, d->shm);
-		if (!d->cursor_theme) {
-			fprintf(stderr, "unable to load default theme\n");
-			return;
-		}
-		d->default_cursor =
-			wl_cursor_theme_get_cursor(d->cursor_theme, "left_ptr");
-		if (!d->default_cursor) {
-			fprintf(stderr, "unable to load default left pointer\n");
-			// TODO: abort ?
-		}
-	}
-}
-
-static void
-registry_handle_global_remove(void *data, struct wl_registry *registry,
-			      uint32_t name)
+    registry_handle_global_remove(void *data, struct wl_registry *registry,
+				  uint32_t name)
 {
 }
 
 static const struct wl_registry_listener registry_listener = {
-	registry_handle_global,
-	registry_handle_global_remove
+  registry_handle_global,
+  registry_handle_global_remove
 };
 
 static void
-signal_int(int signum)
+    signal_int(int signum)
 {
-	running = 0;
+  running = 0;
 }
 
-static void
-usage(int error_code)
-{
-	fprintf(stderr, "Usage: simple-egl [OPTIONS]\n\n"
-		"  -d <us>\tBuffer swap delay in microseconds\n"
-		"  -f\tRun in fullscreen mode\n"
-		"  -o\tCreate an opaque surface\n"
-		"  -s\tUse a 16 bpp EGL config\n"
-		"  -b\tDon't sync to compositor redraw (eglSwapInterval 0)\n"
-		"  -h\tThis help text\n\n");
-
-	exit(error_code);
+static void usage(char *appname) {
+  printf("Usage: %s [-golden | -test | -h]\n", appname);
 }
 
 int
-main(int argc, char **argv)
+    main(int argc, char **argv)
 {
-	struct sigaction sigint;
-	struct display display = { 0 };
-	struct window  window  = { 0 };
-	int i, ret = 0;
+  struct sigaction sigint;
+  struct display display = { 0 };
+  struct window	 window	 = { 0 };
+  int i, ret = 0;
 
-	window.display = &display;
-	display.window = &window;
-	window.geometry.width  = 250;
-	window.geometry.height = 250;
-	window.window_size = window.geometry;
-	window.buffer_size = 32;
-	window.frame_sync = 1;
-	window.delay = 0;
+  window.display = &display;
+  glwindow = display.window = &window;
+  window.geometry.width	 = WINDOW_WIDTH;
+  window.geometry.height = WINDOW_HEIGHT;
+  window.window_size = window.geometry;
+  window.buffer_size = 32;
+  window.frame_sync = 1;
+  window.delay = 0;
 
-	for (i = 1; i < argc; i++) {
-		if (strcmp("-d", argv[i]) == 0 && i+1 < argc)
-			window.delay = atoi(argv[++i]);
-		else if (strcmp("-f", argv[i]) == 0)
-			window.fullscreen = 1;
-		else if (strcmp("-o", argv[i]) == 0)
-			window.opaque = 1;
-		else if (strcmp("-s", argv[i]) == 0)
-			window.buffer_size = 16;
-		else if (strcmp("-b", argv[i]) == 0)
-			window.frame_sync = 0;
-		else if (strcmp("-h", argv[i]) == 0)
-			usage(EXIT_SUCCESS);
-		else
-			usage(EXIT_FAILURE);
-	}
+  AppName = basename(argv[0]);
+  if (argc > 2) {
+    usage(AppName);
+    exit(1);
+  }
 
-	display.display = wl_display_connect(NULL);
-	assert(display.display);
+  if (argc == 2) {
+    if (strcmp("-golden", argv[1]) == 0) {
+      struct stat st = {0};
+      if (stat(GOLDEN_IMG_DIR, &st) == -1) {
+	mkdir(GOLDEN_IMG_DIR, 0700);
+      }
+      generate_ref_images = true;
+    } else if (strcmp("-test", argv[1]) == 0) {
+      test = true;
+    } else if (strcmp("-h", argv[1]) == 0) {
+      usage(AppName);
+      exit(0);
+    } else {
+      usage(AppName);
+      exit(1);
+    }
+  }
 
-	display.registry = wl_display_get_registry(display.display);
-	wl_registry_add_listener(display.registry,
-				 &registry_listener, &display);
+  display.display = wl_display_connect(NULL);
+  assert(display.display);
 
-	wl_display_roundtrip(display.display);
+  display.registry = wl_display_get_registry(display.display);
+  wl_registry_add_listener(display.registry,
+			   &registry_listener, &display);
 
-	init_egl(&display, &window);
-	create_surface(&window);
-	init_gl(&window);
+  ret = wl_display_dispatch(display.display);
+  wl_display_roundtrip(display.display);
 
-	display.cursor_surface =
-		wl_compositor_create_surface(display.compositor);
+  init_egl(&display, &window);
+  create_surface(&window);
 
-	sigint.sa_handler = signal_int;
-	sigemptyset(&sigint.sa_mask);
-	sigint.sa_flags = SA_RESETHAND;
-	sigaction(SIGINT, &sigint, NULL);
+  sigint.sa_handler = signal_int;
+  sigemptyset(&sigint.sa_mask);
+  sigint.sa_flags = SA_RESETHAND;
+  sigaction(SIGINT, &sigint, NULL);
 
-	/* The mainloop here is a little subtle.  Redrawing will cause
-	 * EGL to read events so we can just call
-	 * wl_display_dispatch_pending() to handle any events that got
-	 * queued up as a side effect. */
-	while (running && ret != -1) {
-		if (window.wait_for_configure) {
-			ret = wl_display_dispatch(display.display);
-		} else {
-			ret = wl_display_dispatch_pending(display.display);
-			redraw(&window, NULL, 0);
-		}
-	}
+  /* The mainloop here is a little subtle.  Redrawing will cause
+   * EGL to read events so we can just call
+   * wl_display_dispatch_pending() to handle any events that got
+   * queued up as a side effect. */
 
-	fprintf(stderr, "simple-egl exiting\n");
+  RunGears((void *)&window);
 
-	destroy_surface(&window);
-	fini_egl(&display);
+  fprintf(stderr, "simple-egl exiting\n");
 
-	wl_surface_destroy(display.cursor_surface);
-	if (display.cursor_theme)
-		wl_cursor_theme_destroy(display.cursor_theme);
+  destroy_surface(&window);
+  fini_egl(&display);
 
-	if (display.wm_base)
-		xdg_wm_base_destroy(display.wm_base);
+  if (display.compositor)
+    wl_compositor_destroy(display.compositor);
 
-	if (display.compositor)
-		wl_compositor_destroy(display.compositor);
+  wl_registry_destroy(display.registry);
+  wl_display_flush(display.display);
+  wl_display_disconnect(display.display);
 
-	wl_registry_destroy(display.registry);
-	wl_display_flush(display.display);
-	wl_display_disconnect(display.display);
-
-	return 0;
+  return 0;
 }