Bugfixes and speed improvements.

Moved the mask into the template datastructure. Made the error
termination more strict. Made the bad data conditions more strict.