Fixed null pointer issues - the code is still s**t and needs to be refactored!