Safe double close

Should fix #21. Also adds some tests around opening ports.