Extract main method + fixed bug with nearest boxes