Replaced while loops with foreach, added try-catch