Completed Algorithm, added terminal support