cleaned up and reorganized code