Made offset code a bit more robust