Reorganizing some files, refactoring...

Reorganizing some files, refactoring, adding some additional checks, optimizing lookups.