Cleanup: removed some potential bugs and removed magic numbers.