Fixed error handling parameter.
Added real usage of $q.
A lot of refactoring...