Completed working version. Needs tidying up.