Fixed some NPE's and made optimisations