Some re-organisation, added error handling code