Re-written connection and fixed a lot of bugs