Some basic refactoring. Still a bug exists in the code.