Major refactoring/cleanup/style corrections across the board