+/**
+ * Returns the difference between two unsigned short values. The calculated
+ * value is always smaller or equal to 0x8000.
+ * This is useful if you have an overflowing counter and you want to determine
+ * when you have to "wrap over" the value.
+ */
+int nearest_diff(unsigned short last, unsigned short current) {
+ int d = current - last;
+ if(d < -0x8000) { // overflow in positive direction
+ d = (0x10000 - last_i + this_i);
+ }
+ if(d >= 0x8000) { // overflow in negative direction
+ d = -(0x10000 - this_i + last_i);
+ }
+}
+