Cleaner code based on Avi's talk