Implemented most of the nested optimizations, also added a couple of unit tests.