It would be great if you documented the logic here or commented throughout to make it more understandable.