refractored. fixed some newly introduced bugs