Major rewrite of the entire script.