Reorganized/slightly commented code for easier perusing