Refactoring architecture and fixing undefined issue