cleaning up, some syntax fixed and edge cases considered