Fixed the bugs to make code more robust, still doesn't pass case 12.