Added some checks to prevent a NPE