Handle end of input. Speed improvements. Deleted legacy code.