recompiled and added some extra theory