code cleanup, some improvements, fixed some logical errors.