Almost working copy
Merged with github version