working solution! still needs refactoring