Working version. Minor bug fix pending