Added unit tests for better code coverage, tweaked some minor functions with NPE handlng.