Updated with comments and cleaned up code