working version, still needs tests