Style remark: this code is very dense. Inserting some blank lines above comments will help.