Now works up to 3999. Code still needs to be refactured.