updated code with leadin time and tidied states