working version, not sufficiently tested