Work in progress (refactored, removed duplicate code - where possible, optimized)