Merged in changes from MrGreenStuff/master, and modifified for readability and functionality to ensure it actually works now.