Clean up code and fix boundary bug