Lots more refactoring and removing library dependency