/*
 * IBM_DB::close --  Closes a database connection
 *
 * ===Description
 *
 * bool IBM_DB::close ( resource connection )
 *
 * This function closes a DB2 client connection created with IBM_DB::connect() and returns 
 * the corresponding resources to the database server.
 * 
 * If you attempt to close a persistent DB2 client connection created with IBM_DB::pconnect(), the close request
 * returns TRUE and the persistent DB2 client connection remains available for the next caller.
 * 
 * ===Parameters
 *
 * connection
 *   Specifies an active DB2 client connection. 
 *
 * ===Return Values
 * Returns TRUE on success or FALSE on failure. 
 */
VALUE ibm_db_close(int argc, VALUE *argv, VALUE self)
{
  VALUE connection = Qnil;
  conn_handle *conn_res;
  int rc;

  rb_scan_args(argc, argv, "1", &connection);

  if (!NIL_P(connection)) {
    /* Check to see if it's a persistent connection; if so, just return true */
    Data_Get_Struct(connection, conn_handle, conn_res);

    if (!conn_res->handle_active) {
      rb_throw("Connection is not active", Qnil);
    }

    if ( conn_res->handle_active && !conn_res->flag_pconnect ) {
      /* Disconnect from DB. If stmt is allocated, it is freed automatically */
      if (conn_res->auto_commit == 0) {
        rc = SQLEndTran(SQL_HANDLE_DBC, (SQLHDBC)conn_res->hdbc, SQL_ROLLBACK);
        if ( rc == SQL_ERROR ) {
          _ruby_ibm_db_check_sql_errors(conn_res->hdbc, SQL_HANDLE_DBC, rc, 1, NULL, -1, 1);
          return Qfalse;
        }
      }
      rc = SQLDisconnect((SQLHDBC)conn_res->hdbc);
      if ( rc == SQL_ERROR ) {
        _ruby_ibm_db_check_sql_errors(conn_res->hdbc, SQL_HANDLE_DBC, rc, 1, NULL, -1, 1);
        return Qfalse;
      }

      rc = SQLFreeHandle( SQL_HANDLE_DBC, conn_res->hdbc);
      if ( rc == SQL_ERROR ) {
        _ruby_ibm_db_check_sql_errors(conn_res->hdbc, SQL_HANDLE_DBC, rc, 1, NULL, -1, 1);
        return Qfalse;
      }
      conn_res->handle_active = 0;

      connection = Qnil;

      return Qtrue;
    } else if ( conn_res->flag_pconnect ) {
      /* Do we need to call FreeStmt or something to close cursors? */
      return Qtrue;
    } else {
      return Qfalse;
    }
  } else {
    return Qfalse;
  }
}