cleanup _link code generation
fix last page generation
reorder some lines for better readability
set ids cache after adding the self and source links
fix _links generation, was trying to be too clever