Refactor and add mathcheck

Why not localizing these variables? Same for the variables below.