moving id generation outside loop