Several code fixes + small rearrangements