refactor and cleanup based on Matei's feedback