working version
not well tested