Refactor a bit and partially finish POSIX version