diff --git a/rotate.c b/rotate.c
index d2fe925..88f0a15 100644
--- a/rotate.c
+++ b/rotate.c
@@ -1,6 +1,7 @@
 /* -*-  tab-width:4; c-basic-offset:4  -*- 
  * rotate.c -- determine Freerunner orientation.
- * Author   -- Chris Ball <cjb@laptop.org>
+ * Authors  -- © 2008 Chris Ball <cjb@laptop.org>
+ *             © 2008 Rui Miguel Silva Seabra <rms@1407.org>
  *
  * This file is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License as published by the
@@ -12,6 +13,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
+#include <X11/Xlib.h>
+#include <X11/extensions/Xrandr.h>
 
 #define EVENT_PATH "/dev/input/event3"
 #define ORIENTATION_NORMAL    0
@@ -19,27 +22,52 @@
 #define ORIENTATION_RIGHT     2
 #define ORIENTATION_INVERTED  3
 
+static Display  *display;
+static Window   rootWindow;
+
 void set_rotation (int rotation) {
+    Rotation r_to,r;
+    int screen = -1;
+    int do_rotate=1;
+    XRRScreenConfiguration * config;
+    int current_size=0;
+
     printf("In set_rotation, rotation = %d\n", rotation);
     switch (rotation)
     {
     case 0:
-        system("xrandr -o normal");
+        r_to=RR_Rotate_0;
         break;
     case 1:
-        system("xrandr -o left");
+        r_to=RR_Rotate_90;
         break;
     case 2:
-        system("xrandr -o right");
+        r_to=RR_Rotate_270;
         break;
     case 3:
-        system("xrandr -o inverted");
+        r_to=RR_Rotate_180;
         break;
     default:
+        do_rotate=0;
         break;
     }
-    /* Sleep for two seconds to give randr a chance to catch up. */
-    sleep(2);
+    if(do_rotate) {
+        display = XOpenDisplay(":0");
+        if (display == NULL) {
+            fprintf (stderr, "Can't open display %s\n", XDisplayName(":0"));
+            exit (1);
+        }
+
+        screen = DefaultScreen(display);
+        rootWindow = RootWindow(display, screen);
+        XRRRotations(display, screen, &r);
+        config = XRRGetScreenInfo(display, rootWindow);
+        current_size = XRRConfigCurrentConfiguration (config, &r);
+        XRRSetScreenConfig(display, config, rootWindow, current_size, r_to, CurrentTime);
+ 
+        /* Sleep for two seconds to give randr a chance to catch up. */
+        sleep(2);
+    }
 }
 
 int process_packet (FILE *eventfp) {
@@ -174,7 +202,7 @@ int main (int argc, char *argv[]) {
         sleep(1);
         if (rotation != -1)
             oldrotation = rotation;
-		
+
         rotation = process_packet(eventfp);
         if (rotation != oldrotation && rotation != -1)
             set_rotation(rotation);

