fixed a bug somewhere. Ready for modularisation