Tidied up the gaps code and adding more logging.