Updated code to have better comments etc.