Table key handling and some refactoring