code rewrite, added missing lib, allmost everything complete