Functioning version after major refactoring