<?php

spl_autoload_register("mfAutoload", true);
//require_once PEARDIR.'/PEAR2/Autoload.php';

/**
 * From http://php.net/manual/en/language.oop5.autoload.php:
 * 
 * You may define an __autoload() function which is automatically
 * called in case you are trying to use a class/interface which
 * hasn't been defined yet.
 * 
 * @throws Exception
 */
function mfAutoload($name) {
	if(strstr($name,"..") || strstr($name,"/")) {
		return false;
	}
	
	if(mfAutoload_loadLib($name)) {
		return true;
	}
  
	$type="";
	if(preg_match('/^(.+)(Controller|Model)$/',$name,$m)) {
		$name=$m[1];
		$type=$m[2];
	} elseif(preg_match('/^(.+)_(.+)/',$name,$m)) {
		$name=$m[1];
		$type=$m[2];
	}
	
	$filename=APPDIR."/$name/$name$type.php";
	if(file_exists($filename)) {
    require_once($filename);
		if(class_exists($name.$type)) return true;
	} else {
		$filename=APPDIR."/$name/".$name."_".$type.".php";
		if(file_exists($filename)) {
			require_once($filename);
			if(class_exists("{$name}_{$type}")) return true;
		}
	}
	
	//throw new Exception("Autoloader Exception: $name $type not found");
}

function mfAutoload_loadLib($name) {
	if(preg_match('/^mf.+/',$name)) {
		$filename=LIBDIR."/mvcfronk/$name/$name.php";
		if(preg_match('/^(.*)Controller$/',$name,$m)) {
			$filename=LIBDIR."/mvcfronk/".$m[1]."/$name.php";
		}
		if(file_exists($filename)) {
			require_once($filename);
		}
	} elseif(preg_match('/^([^_]+)_(.+)$/',$name,$m)) {
		$filename=LIBDIR."/".$m[1]."/".$m[2].".php";
	} else {
		$filename=LIBDIR."/$name/$name.php";
	}
  
	if(file_exists($filename)) {
		require_once($filename);
		return true;
	}
	return false;
}

