seems to work properly, now need to test and debug all edge cases.