Rewrote to be cleaner and work without forking