Updated code and optimized, much faster