Many changes, added more error checking, fixed mistakes, made more robust etc.