Code re-write and bug fixes