Optimized the code a bit and fixed a bug
(Thanks techshinobi for finding it)