Refactor and made all functionality work