Latest refactored semi-working version