Fixed some of the crashes
1. Added calls to Mat::release(). Also moved some members to be local variables.
2. Made sure window is in bounds (partial, see TODO).
Still crashes