Theory of K-loops