Refactor and add mathcheck

Localize variables.