Returns statistics, positions and rescaled events for mouse events.

def stats_mouse(events, table):
    """Returns statistics, positions and rescaled events for mouse events."""
    if not events: return [], [], []
    distance, last, deltas = 0, None, []
    HS = conf.MouseHeatmapSize
    SC = dict(("xy"[i], conf.DefaultScreenSize[i] / float(HS[i])) for i in [0, 1])
    xymap = collections.defaultdict(int)
    sizes = db.fetch("screen_sizes", order=("dt",))
    sizeidx, sizelen = -1, len(sizes) # Scale by desktop size at event time
    for e in events:
        if last:
            deltas.append(e["dt"] - last["dt"])
            distance += math.sqrt(sum(abs(e[k] - last[k])**2 for k in "xy"))
        last = dict(e) # Copy, as we modify coordinates
        if sizeidx < 0: # Find latest size from before event
            for i, size in reversed(list(enumerate(sizes))):
                if e["dt"] >= size["dt"]:
                    SC = dict((k, size[k] / float(HS["y" == k])) for k in "xy")
                    sizeidx = i
                    break # for i, size
        else: # Find next size from before event
            while sizeidx < sizelen - 2 and e["dt"] >= sizes[sizeidx + 1]["dt"]:
                sizeidx += 1
            if sizeidx < sizelen - 1 and e["dt"] >= sizes[sizeidx]["dt"]:
                SC = dict((k, sizes[sizeidx][k] / float(HS["y" == k])) for k in "xy")
        e["x"], e["y"] = tuple(min(int(e[k] / SC[k]), HS["y" == k]) for k in "xy")
        xymap[(e["x"], e["y"])] += 1

    stats, positions = [], [dict(x=x, y=y, count=v) for (x, y), v in xymap.items()]
    if "moves" == table:
        px = re.sub(r"(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % math.ceil(distance))
        seconds = timedelta_seconds(events[-1]["dt"] - events[0]["dt"])
        stats = [("Total distance", "%s pixels " % px),
                 ("", "%.1f meters (if pixel is %smm)" %
                  (distance * conf.PixelLength, conf.PixelLength * 1000)),
                 ("Average speed", "%.1f pixels per second" % (distance / (seconds or 1))),
                 ("", "%.4f meters per second" %
                  (distance * conf.PixelLength / (seconds or 1))), ]
    elif "scrolls" == table:
        counts = collections.Counter(e["wheel"] for e in events)
        stats = [("Scrolls per hour", 
                  int(len(events) / (timedelta_seconds(events[-1]["dt"] - events[0]["dt"]) / 3600 or 1))),
                 ("Average interval", sum(deltas, datetime.timedelta()) / (len(deltas) or 1)),
                 ("Scrolls down", counts[-1]),
                 ("Scrolls up", counts[1]), ]
    elif "clicks" == table:
        counts = collections.Counter(e["button"] for e in events)
        NAMES = {1: "Left", 2: "Right", 3: "Middle"}
        stats = [("Clicks per hour", 
                  int(len(events) / (timedelta_seconds(events[-1]["dt"] - events[0]["dt"]) / 3600 or 1))),
                 ("Average interval between clicks",
                  sum(deltas, datetime.timedelta()) / (len(deltas) or 1)),
                 ("Average distance between clicks",
                  "%.1f pixels" % (distance / (len(events) or 1))), ]
        for k, v in sorted(counts.items()):
            stats += [("%s button clicks" % NAMES.get(k, "%s." % k), v)]
    return stats, positions, events