bt_status_t btif_sock_init(void) {
  assert(thread_handle == -1);
  assert(thread == NULL);

  btsock_thread_init();
  thread_handle = btsock_thread_create(btsock_signaled, NULL);
  if (thread_handle == -1) {
    LOG_ERROR("%s unable to create btsock_thread.", __func__);
    goto error;
  }

  bt_status_t status = btsock_rfc_init(thread_handle);
  if (status != BT_STATUS_SUCCESS) {
    LOG_ERROR("%s error initializing RFCOMM sockets: %d", __func__, status);
    goto error;
  }

  status = btsock_l2cap_init(thread_handle);
  if (status != BT_STATUS_SUCCESS) {
    LOG_ERROR("%s error initializing L2CAP sockets: %d", __func__, status);
    goto error;
  }

  thread = thread_new("btif_sock");
  if (!thread) {
    LOG_ERROR("%s error creating new thread.", __func__);
    btsock_rfc_cleanup();
    goto error;
  }

  status = btsock_sco_init(thread);
  if (status != BT_STATUS_SUCCESS) {
    LOG_ERROR("%s error initializing SCO sockets: %d", __func__, status);
    btsock_rfc_cleanup();
    goto error;
  }

  return BT_STATUS_SUCCESS;

error:;
  thread_free(thread);
  thread = NULL;
  if (thread_handle != -1)
    btsock_thread_exit(thread_handle);
  thread_handle = -1;
  return BT_STATUS_FAIL;
}
bt_status_t btif_sock_init()
{
    static volatile int binit;
    if(!binit)
    {
        //fix me, the process doesn't exit right now. don't set the init flag for now
        //binit = 1;
        BTIF_TRACE_DEBUG0("btsock initializing...");
        btsock_thread_init();
        int handle = btsock_thread_create(btsock_signaled, NULL);
        if(handle >= 0 && btsock_rfc_init(handle) == BT_STATUS_SUCCESS)
        {
            BTIF_TRACE_DEBUG0("btsock successfully initialized");
            return BT_STATUS_SUCCESS;
        }
    }
    else BTIF_TRACE_ERROR0("btsock interface already initialized");
    return BT_STATUS_FAIL;
}