Adding in changes made by baileylo in his awesomely coded fork.