Added some safe checks and initial tests