Motion detection algorithm