Defensive codiing on some functions and more test cases