Modularize and add flags. Also add some safety checks.