Implemented changes from Kaylan
Copied from mpellegri fork