Implemented native type derivation. Minor refactoring and fixes.