Fixed some buggery to make it more robust