Improved scheduling code - not finished