optimize loops
fix undefined keys