I believe there's still room for improvement here, code looks more complex than it should be.