rearanged order, added debugger check, minor code cleaning