Fixed a few bugs dealing with edge cases for invalid inputs and a few improved some other code by general cleaning up and refactoring.