Further improve logic and do some cleanup