Lifecycle

Add lifecycle callbacks. Completely refactor code to be cleaner and more efficient.