Refactor and add mathcheck

Nit: localize variables.