Cleaned code, added fail check