complete re-write of layers courtesy of https://gist.github.com/whardier/