Working version

needs further refactoring