Working version. Needs cleanup