Code simplified as suggested by @alberskib