Imported code from https://bitbucket.org/artofsequence/aos