Well, the reason why the code is somewhat duplicated is because each block is just slightly different. Note that the data for each admin level is just a bit different. Likewise, the calculated population is different depending on the admin level (for admin0, the time of day pop ratio is taken into account, whereas at the subnational level it is not).

I will break these out into separate helper functions to make it easier to read.