code to automatically determine optimal offset