Updated with safety checks and removed printf debug