Added debugging check and reorganized code