Move detection code to the top