structured and cleaned up code