cleaning up final code, with some slight improvements