Added flash functionality and tidied up code