Greatly simplified main if statement. Other cleaning.