Full rewrite; cleaner and optimized