diff --git a/mi/mieq.c b/mi/mieq.c
index a03fff1..df7efa3 100644
--- a/mi/mieq.c
+++ b/mi/mieq.c
@@ -108,14 +108,19 @@ mieqEnqueue(DeviceIntPtr pDev, xEvent *e)
     HWEventQueueType       oldtail = miEventQueue.tail, newtail;
     int                    isMotion = 0;
     deviceValuator         *v = (deviceValuator *) e;
-    EventPtr               laste = &miEventQueue.events[oldtail - 1];
-    deviceKeyButtonPointer *lastkbp = (deviceKeyButtonPointer *)
-                                      &laste->event[0];
+    EventPtr               laste;
+    deviceKeyButtonPointer *lastkbp;
 
     if (e->u.u.type == MotionNotify)
         isMotion = inputInfo.pointer->id;
     else if (e->u.u.type == DeviceMotionNotify)
         isMotion = pDev->id;
+    
+    /* deal with case that oldtail == 0*/ 
+    if (oldtail == 0)
+        laste = &miEventQueue.events[QUEUE_SIZE - 1];
+    else
+        laste = &miEventQueue.events[oldtail - 1];
 
     /* We silently steal valuator events: just tack them on to the last
      * motion event they need to be attached to.  Sigh. */
@@ -124,6 +129,7 @@ mieqEnqueue(DeviceIntPtr pDev, xEvent *e)
             ErrorF("mieqEnqueue: more than six valuator events; dropping.\n");
             return;
         }
+        lastkbp = (deviceKeyButtonPointer *) &laste->event[0];
         if (oldtail == miEventQueue.head ||
             !(lastkbp->type == DeviceMotionNotify ||
               lastkbp->type == DeviceButtonPress ||
