First working version, needs refactoring