Tidied up overlay code. Split code into multiple functions.