Completely rewrote whole script, but it's not tested at all. Post bugs if you find anything.