Added some checks to avoid NPE.