/**
  * It creates a module instance
  * @param string $module module name
  * @param string $type instance type, (e.g., view, controller, model)
  * @param string $kind admin or svc
  * @return ModuleObject module instance (if failed it returns null)
  * @remarks if there exists a module instance created before, returns it.
  * */
 function &getModuleInstance($module, $type = 'view', $kind = '')
 {
     if (__DEBUG__ == 3) {
         $start_time = getMicroTime();
     }
     $parent_module = $module;
     $kind = strtolower($kind);
     $type = strtolower($type);
     $kinds = array('svc' => 1, 'admin' => 1);
     if (!isset($kinds[$kind])) {
         $kind = 'svc';
     }
     $key = $module . '.' . ($kind != 'admin' ? '' : 'admin') . '.' . $type;
     if (is_array($GLOBALS['__MODULE_EXTEND__']) && array_key_exists($key, $GLOBALS['__MODULE_EXTEND__'])) {
         $module = $extend_module = $GLOBALS['__MODULE_EXTEND__'][$key];
     }
     // if there is no instance of the module in global variable, create a new one
     if (!isset($GLOBALS['_loaded_module'][$module][$type][$kind])) {
         ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
         if ($extend_module && (!is_readable($high_class_file) || !is_readable($class_file))) {
             $module = $parent_module;
             ModuleHandler::_getModuleFilePath($module, $type, $kind, $class_path, $high_class_file, $class_file, $instance_name);
         }
         // Check if the base class and instance class exist
         if (!class_exists($module, true)) {
             return NULL;
         }
         if (!class_exists($instance_name, true)) {
             return NULL;
         }
         // Create an instance
         $oModule = new $instance_name();
         if (!is_object($oModule)) {
             return NULL;
         }
         // Load language files for the class
         Context::loadLang($class_path . 'lang');
         if ($extend_module) {
             Context::loadLang(ModuleHandler::getModulePath($parent_module) . 'lang');
         }
         // Set variables to the instance
         $oModule->setModule($module);
         $oModule->setModulePath($class_path);
         // If the module has a constructor, run it.
         if (!isset($GLOBALS['_called_constructor'][$instance_name])) {
             $GLOBALS['_called_constructor'][$instance_name] = TRUE;
             if (@method_exists($oModule, $instance_name)) {
                 $oModule->{$instance_name}();
             }
         }
         // Store the created instance into GLOBALS variable
         $GLOBALS['_loaded_module'][$module][$type][$kind] = $oModule;
     }
     if (__DEBUG__ == 3) {
         $GLOBALS['__elapsed_class_load__'] += getMicroTime() - $start_time;
     }
     // return the instance
     return $GLOBALS['_loaded_module'][$module][$type][$kind];
 }