rewriting a lot based on Ivy's suggestions.