Replaced while loops with foreach, added try-catch
Updated TODO