Added unit tests, improved fd handling