Working code with device clustering