Simplyfy and speed up the code