                            (if (.equals "READY" (get (json/read-str %) "t"))
                              (reset! the-ready (json/read-str %))))))
   (ws/send-msg @the-socket (json/write-str {:op 2, :d {:token @the-token,:properties {:$browser "clj-discord"}}}))
-  (while (nil? @the-ready) (Thread/sleep 1000))
+  (while (and @the-keepalive (nil? @the-ready)) (Thread/sleep 1000))
   (.start (Thread. (fn [] (while @the-keepalive
                             (do
-                              (println (get (get @the-ready "d") "heartbeat_interval"))
                               (ws/send-msg @the-socket (json/write-str {:op 1, :d (System/currentTimeMillis)}))
-                              (Thread/sleep (get (get @the-ready "d") "heartbeat_interval"))))))))
+                              (Thread/sleep (get (get @the-ready "d") "heartbeat_interval")))))))
+  (println "Connected."))
+
 
 (defn disconnect []
   (reset! the-keepalive false)
-  (ws/close @the-socket))
+  (if (not (nil? @the-socket)) (ws/close @the-socket))
+  (reset! the-token nil)
+  (reset! the-gateway nil)
+  (reset! the-socket nil)
+  (reset! the-ready nil))
 

      (get (json/read-str (:body response)) "url")
      (println "Gateway obtention failed with status code " status))))

(defn connect [email password]
  (reset! the-keepalive true)
  (reset! the-token (obtain-token email password))
  (reset! the-gateway (obtain-gateway @the-token))
  (reset! the-socket   
          (ws/connect 
            @the-gateway
            :on-receive #(do 

      (get (json/read-str (:body response)) "token")
      (println "Token obtention failed with status code " status))))


(defn obtain-gateway [token]
  (let [response (client/get "https://discordapp.com/api/gateway"
                             {:headers {:authorization token}})
