More sophisticated cleanup for math module