made the code more robust and changed interface