Hmm, not happy about the large chunk of cuda code living in this file. Think it should live in cuda specific files.