cleaned up code and added extra check before run