Added null checks and debugging prints.