Reorganized code to be more flexible.