I couldn't bother reviewing this carefully, just a utility script