Fix bugs; improve code