QgsProjectionSelectionTreeWidget::~QgsProjectionSelectionTreeWidget()
{
  qDeleteAll( mLayers );
  delete mPreviewBand;
  delete mPreviewBand2;
  delete mVertexMarker;

  if ( !mPushProjectionToFront )
  {
    return;
  }

  // Push current projection to front, only if set
  long crsId = selectedCrsId();
  if ( crsId == 0 )
    return;

  // Save persistent list of projects
  mRecentProjections.removeAll( QString::number( crsId ) );
  mRecentProjections.prepend( QString::number( crsId ) );
  // Prune size of list
  while ( mRecentProjections.size() > 8 )
  {
    mRecentProjections.removeLast();
  }

  // Save to file *** Should be removed sometims in the future ***
  QgsSettings settings;
  settings.setValue( QStringLiteral( "/UI/recentProjections" ), mRecentProjections );

  // Convert to EPSG and proj4, and save those values also

  QStringList projectionsProj4;
  QStringList projectionsAuthId;
  for ( int i = 0; i <  mRecentProjections.size(); i++ )
  {
    // Create a crs from the crsId
    QgsCoordinateReferenceSystem crs( mRecentProjections.at( i ).toLong(), QgsCoordinateReferenceSystem::InternalCrsId );
    if ( ! crs.isValid() )
    {
      // No? Skip this entry
      continue;
    }
    projectionsProj4 << crs.toProj4();
    projectionsAuthId << crs.authid();
  }
  settings.setValue( QStringLiteral( "/UI/recentProjectionsProj4" ), projectionsProj4 );
  settings.setValue( QStringLiteral( "/UI/recentProjectionsAuthId" ), projectionsAuthId );
}
// New coordinate system selected from the list
void QgsProjectionSelector::coordinateSystemSelected( QTreeWidgetItem * theItem )
{
    // If the item has children, it's not an end node in the tree, and
    // hence is just a grouping thingy, not an actual CRS.
    if ( theItem != NULL && theItem->childCount() == 0 )
    {
        // Found a real CRS
        QString myDescription;
        emit sridSelected( QString::number( selectedCrsId() ) );
        QString myProjString = selectedProj4String();
        lstCoordinateSystems->scrollToItem( theItem );
        teProjection->setText( myProjString );
    }
    else
    {
        // Not an CRS - remove the highlight so the user doesn't get too confused
        lstCoordinateSystems->setItemSelected( theItem, FALSE );  // TODO - make this work.
        teProjection->setText( "" );
    }
}
void QgsProjectionSelector::on_pbnFind_clicked()
{

    QgsDebugMsg( "pbnFind..." );

    QString mySearchString( sqlSafeString( leSearch->text() ) );
    // Set up the query to retrieve the projection information needed to populate the list
    QString mySql;
    if ( radEpsgCrsId->isChecked() )
    {
        mySql = "select srs_id from tbl_srs where epsg=" + mySearchString;
    }
    else if ( radName->isChecked() ) //name search
    {
        //we need to find what the largest srsid matching our query so we know whether to
        //loop backto the beginning
        mySql = "select srs_id from tbl_srs where description like '%" + mySearchString + "%'" +
                " order by srs_id desc limit 1";
        long myLargestSrsId = getLargestCRSIDMatch( mySql );
        QgsDebugMsg( QString( "Largest CRSID%1" ).arg( myLargestSrsId ) );
        //a name search is ambiguous, so we find the first srsid after the current seelcted srsid
        // each time the find button is pressed. This means we can loop through all matches.
        if ( myLargestSrsId <= selectedCrsId() )
        {
            //roll search around to the beginning
            mySql = "select srs_id from tbl_srs where description like '%" + mySearchString + "%'" +
                    " order by srs_id limit 1";
        }
        else
        {
            // search ahead of the current postion
            mySql = "select srs_id from tbl_srs where description like '%" + mySearchString + "%'" +
                    " and srs_id > " + QString::number( selectedCrsId() ) + " order by srs_id limit 1";
        }
    }
    QgsDebugMsg( QString( " Search sql: %1" ).arg( mySql ) );

    //
    // Now perform the actual search
    //

    sqlite3      *myDatabase;
    const char   *myTail;
    sqlite3_stmt *myPreparedStatement;
    int           myResult;
    //check the db is available
    myResult = sqlite3_open( mSrsDatabaseFileName.toUtf8().data(), &myDatabase );
    if ( myResult )
    {
        // XXX This will likely never happen since on open, sqlite creates the
        //     database if it does not exist. But we checked earlier for its existance
        //     and aborted in that case. This is because we may be runnig from read only
        //     media such as live cd and dont want to force trying to create a db.
        showDBMissingWarning( mSrsDatabaseFileName );
        return;
    }

    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.length(), &myPreparedStatement, &myTail );
    // XXX Need to free memory from the error msg if one is set
    if ( myResult == SQLITE_OK )
    {
        myResult = sqlite3_step( myPreparedStatement );
        if ( myResult == SQLITE_ROW )
        {
            QString mySrsId = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 0 ) );
            setSelectedCrsId( mySrsId.toLong() );
            // close the sqlite3 statement
            sqlite3_finalize( myPreparedStatement );
            sqlite3_close( myDatabase );
            return;
        }
    }
    //search the users db
    QString myDatabaseFileName = QgsApplication::qgisUserDbFilePath();
    QFileInfo myFileInfo;
    myFileInfo.setFile( myDatabaseFileName );
    if ( !myFileInfo.exists( ) ) //its not critical if this happens
    {
        qDebug( "%s\nUser db does not exist", myDatabaseFileName.toUtf8().constData() );
        return ;
    }
    myResult = sqlite3_open( myDatabaseFileName.toUtf8().data(), &myDatabase );
    if ( myResult )
    {
        QgsDebugMsg( QString( "Can't open * user * database: %1" ).arg( sqlite3_errmsg( myDatabase ) ) );
        //no need for assert because user db may not have been created yet
        return;
    }

    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.length(), &myPreparedStatement, &myTail );
    // XXX Need to free memory from the error msg if one is set
    if ( myResult == SQLITE_OK )
    {
        myResult = sqlite3_step( myPreparedStatement );
        if ( myResult == SQLITE_ROW )
        {
            QString mySrsId = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 0 ) );
            setSelectedCrsId( mySrsId.toLong() );
            // close the sqlite3 statement
            sqlite3_finalize( myPreparedStatement );
            sqlite3_close( myDatabase );
        }
    }
}