// This file is a part of the xMule Project.
//
// Clean Up, Fix some things and partly rewrite this File: Plaenky 
//
// Copyright (c) 2004 Theodore R. Smith (hopeseekr@xmule.ws / http://www.xmule.ws/)
// DSA-1024 Fingerprint: 10A0 6372 9092 85A2 BB7F 907B CB8B 654B E33B F1ED
//
// Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.emule-project.net )
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

#include "config.h"

// Test if we have _GNU_SOURCE before the next step will mess up
// setting __USE_GNU
// (only needed for gcc-2.95 compatibility, gcc 3.2 always defines it)
#include "wx/setup.h"

// Mario Sergio Fujikawa Ferreira <lioux@FreeBSD.org>
// to detect if this is a *BSD system
#if defined(HAVE_SYS_PARAM_H)
#include <sys/param.h>
#endif

#ifdef PRECOMP
#	include "xmule-headers.h"
#else
#	include "Preferences.h"
#	include "opcodes.h"
#	include "otherfunctions.h"
#	include "ini2.h"
#	include "stdlib.h"
#	include "stdio.h"
#	include "resource.h"
#include "xmule.h"                          // Needed for theApp - audited 4 Nov 2004
#endif

#include <DynPrefs/DynPrefs.h>              // Needed for DynamicPreferences

#include <cstdlib>
#include <ctime>
#include <fstream>                          // Needed for std::ofstream std::endl
#include <iomanip>                          // std::hex std::setprecision
#include <locale.h>
#include <sstream>                          // Needed for std::stringstream
#include <string>                           // Needed for std::string
#include <wx/filename.h>

#define ELEMENT_COUNT(X) (sizeof(X) / sizeof(X[0]))
#define RGB(a,b,c) ((a&0xff)<<16|(b&0xff)<<8|(c&0xff))

#include <sys/stat.h>
#include <sys/types.h>

#ifndef MAX_PATH
// *BSD compatibility
#if (defined(BSD) && (BSD >= 199103))
#define MAX_PATH MAXPATHLEN
#else
#define MAX_PATH 2048
#endif
#endif

#ifdef __FreeBSD__
extern long long atoll(char *s);
#endif /* __FreeBSD__ */

using std::endl;
using std::hex;
using std::ifstream;
using std::ios;
using std::ofstream;
using std::stringstream;

CPreferences::CPreferences()
{
    // we need random numbers sometimes:
    srand((uint32_t) time(0));
    // Define prefs 
    prefs = new Preferences_Struct;
    memset(prefs, 0, sizeof(Preferences_Struct));
    prefsExt = new Preferences_Ext_Struct;
    memset(prefsExt, 0, sizeof(Preferences_Ext_Struct));
    // Use home directory to save preferences
    char buffer[490];
    snprintf(buffer, 400, "%s/." PACKAGE_NAME, getenv("HOME"));
    theApp.dynprefs->Add("app-directory", wxString(buffer, *wxConvCurrent) + wxT("/"));
    mkdir(buffer, 0777);

    // Create UserHash
    CreateUserHash();
    md4cpy(&prefs->userhash, &userhash);
    if (((int *) prefs->userhash) [0] == 0 && ((int *) prefs->userhash) [1] == 0 && ((int *) prefs->userhash) [2] == 0 && ((int *) prefs->userhash) [3] == 0)
    {
       CreateUserHash();
    }
    // Load Preferences
    Load(true);
    // ???
    prefs->m_bUseSecureIdent = true;
}

CPreferences::~CPreferences()
{
    Category_Struct *delcat;
    while (!catMap.IsEmpty())
    {
        delcat = catMap.GetAt(0);
        catMap.RemoveAt(0);
        delete delcat;
    }
    delete prefs;
    delete prefsExt;
}


void CPreferences::SetStandartValues()
{
    wxString buffer;
    CreateUserHash();
    md4cpy( &prefs->userhash, &userhash);
    WINDOWPLACEMENT defaultWPM;
    defaultWPM.length = sizeof(WINDOWPLACEMENT);
    defaultWPM.rcNormalPosition.left = 10;
    defaultWPM.rcNormalPosition.top = 10;
    defaultWPM.rcNormalPosition.right = 700;
    defaultWPM.rcNormalPosition.bottom = 500;
    defaultWPM.showCmd = 0;
    prefs->EmuleWindowPlacement = defaultWPM;
    prefs->versioncheckLastAutomatic = 0;
}

bool CPreferences::Load(bool startup)
{
    bool error = false;
    if(LoadPreferences())
    {
        if(startup)
	{
	    //Can't find Preferences file, but in LoadPreferences() the standard was defined. Now we have to save it.
            SetStandartValues(); 
            if(Save(1)) 
	    {
                error = true;
            }
        }
        else
	{
	    //Not at Application start. The File was deleted while the Application is running ?
            error = true;
        }
    }
    if (startup)
    {
         if(LoadCats())
         {
             //Catfile don't exist, let's create one
             if(Save(2))
	     {
	       error = true;
             }
         }
         if(Load_Shared_Dirs())
         {
	     ; //Maybe the User has not shared dirs 
         }
          if(Load_Adresses())
         {
	     ; //And also no Adresslist
         }
    }
    return error;
}

bool CPreferences::Save(unsigned char selection_mask)
{
    bool error = false;
    if (selection_mask &1)
    {
      SavePreferences();
    }
    if (selection_mask &2)
    {
       if (SaveCats())
       {
           error = true;
       }
    }
    if (selection_mask &4)
    {
       if (Save_Shared_Dirs())
       { 
           error = true;
       }
    }
    if (selection_mask &8)
    {
       if (Save_Adresses())
       {
           error = true;
       }        
    }
    return error;
}

void CPreferences::CreateUserHash()
{
    for (int i = 0 ; i != 8 ; i++)
    {
        uint16_t random = rand();
        memcpy( &userhash[i*2], &random, 2);
    }
    // mark as emule client. that will be need in later version
    userhash[5] = 14;
    userhash[14] = 111;
}

int CPreferences::GetRecommendedMaxConnections()
{
    int iRealMax =::GetMaxConnections();
    if (iRealMax == - 1 || iRealMax > 520)
    return 500;
    if (iRealMax < 20)
    return iRealMax;
    if (iRealMax <= 256)
    return iRealMax - 10;
    return iRealMax - 20;
}

WORD CPreferences::GetWindowsVersion()
{
    return 1;
}

uint16_t CPreferences::GetDefaultMaxConperFive()
{
    return MAXCONPER5SEC;
}


void CPreferences::ResetStatsColor(int index)
{
    switch (index)
    {
    case 0: prefs->statcolors[0] = RGB(0, 0, 64);
            break;
    case 1: prefs->statcolors[1] = RGB(192, 192, 255);
            break;
    case 2: prefs->statcolors[2] = RGB(128, 255, 128);
            break;
    case 3: prefs->statcolors[3] = RGB(0, 210, 0);
            break;
    case 4: prefs->statcolors[4] = RGB(0, 128, 0);
            break;
    case 5: prefs->statcolors[5] = RGB(255, 128, 128);
            break;
    case 6: prefs->statcolors[6] = RGB(200, 0, 0);
            break;
    case 7: prefs->statcolors[7] = RGB(140, 0, 0);
            break;
    case 8: prefs->statcolors[8] = RGB(150, 150, 255);
            break;
    case 9: prefs->statcolors[9] = RGB(192, 0, 192);
            break;
    case 10:prefs->statcolors[10] = RGB(255, 255, 128);
            break;
    case 11:prefs->statcolors[11] = RGB(0, 0, 0);
            break;
    case 12:prefs->statcolors[12] = RGB(255, 255, 255);
            break;
    default:break;
    }
}

void CPreferences::SavePreferences(void)
{
    wxString buffer;
    wxString buffer2;
    wxString full_path(getenv("HOME"), *wxConvCurrent);
    full_path += "/";
    CIni ini(full_path, "eMule");

    ini.WriteString("AppVersion", PACKAGE_STRING);
    ini.WriteString("Nick",                         theApp.dynprefs->Get<wxString>("nickname"));
    ini.WriteString("IncomingDir",                  theApp.dynprefs->Get<wxString>("incoming-directory"));
    ini.WriteString("TempDir",                      theApp.dynprefs->Get<wxString>("temp-directory"));
    ini.WriteInt("MaxUpload",                       theApp.dynprefs->Get<long>( "limits-upload"));
    ini.WriteInt("MaxDownload",                     theApp.dynprefs->Get<long>("limits-download"));
    ini.WriteInt("MaxConnections",                  theApp.dynprefs->Get<long>("max-connections"));
    ini.WriteInt("RemoveDeadServer",                theApp.dynprefs->Get<bool>("remove-dead-server"));
    ini.WriteInt("Port",                            theApp.dynprefs->Get<long>("tcp-port"));
    ini.WriteInt("UDPPort",                         theApp.dynprefs->Get<long>("udp-port"));
    ini.WriteInt("MaxSourcesPerFile",               theApp.dynprefs->Get<long>("max-sources"));
    ini.WriteWORD("Language", prefs->languageID);
    ini.WriteInt("SeeShare",                        theApp.dynprefs->Get<long>("see-share"));
    ini.WriteInt("ToolTipDelay", prefs->m_iToolDelayTime);
    ini.WriteInt("StatGraphsInterval",              theApp.dynprefs->Get<long>("graph-delay"));
    ini.WriteInt("StatsInterval",                   theApp.dynprefs->Get<long>("tree-delay"));
    ini.WriteInt("DownloadCapacity",                theApp.dynprefs->Get<long>("capacities-download"));
    ini.WriteInt("UploadCapacity",                  theApp.dynprefs->Get<long>("capacities-upload"));
    ini.WriteInt("DeadServerRetry",                 theApp.dynprefs->Get<long>("server-connect-tries"));
    ini.WriteInt("SplitterbarPosition", prefs->splitterbarPosition + 2);
    ini.WriteInt("StatsAverageMinutes",             theApp.dynprefs->Get<long>("graph-average"));
    ini.WriteInt("MaxConnectionsPerFiveSeconds",    theApp.dynprefs->Get<long>("max-per-5"));
    ini.WriteInt("Check4NewVersionDelay", prefs->versioncheckdays);
    ini.WriteBool("Reconnect",                      theApp.dynprefs->Get<bool>("reconnect-on-loss"));
    ini.WriteBool("Scoresystem",                    theApp.dynprefs->Get<bool>("priority-system"));
    ini.WriteBool("ICH",                            theApp.dynprefs->Get<bool>("enable-ich"));
    ini.WriteBool("Serverlist",                     theApp.dynprefs->Get<bool>("autoupdate-server"));
    ini.WriteString("LRUServermetURL", prefs->m_szLRUServermetURL);
    ini.WriteBool("UpdateNotify", prefs->updatenotify);
    ini.WriteBool("MinToTray",                      theApp.dynprefs->Get<bool>("minimize-to-tray"));
    ini.WriteBool("AddServersFromServer",           theApp.dynprefs->Get<bool>("add-server-server"));
    ini.WriteBool("AddServersFromClient",           theApp.dynprefs->Get<bool>("add-server-client"));
    ini.WriteBool("Splashscreen",                   theApp.dynprefs->Get<bool>("show-splashscreen"));
    ini.WriteBool("BringToFront",                   theApp.dynprefs->Get<bool>("bring-to-front"));
    ini.WriteBool("TransferDoubleClick",            theApp.dynprefs->Get<bool>("download-doubleclick"));
    ini.WriteBool("BeepOnError",                    theApp.dynprefs->Get<bool>("beep-on-errors"));
    ini.WriteBool("ConfirmExit",                    theApp.dynprefs->Get<bool>("prompt-on-exit"));
    ini.WriteBool("FilterBadIPs",                   theApp.dynprefs->Get<bool>("filter-bad-ip"));
    ini.WriteBool("Autoconnect",                    theApp.dynprefs->Get<bool>("autoconnect"));
    ini.WriteBool("OnlineSignature",                theApp.dynprefs->Get<bool>("online-signature"));
    ini.WriteBool("StartupMinimized",               theApp.dynprefs->Get<bool>("start-minimized"));
    ini.WriteBool("SafeServerConnect",              theApp.dynprefs->Get<bool>("use-safe-connect"));
    ini.WriteBool("ShowRatesOnTitle",               theApp.dynprefs->Get<bool>("xfer-on-title"));
    ini.WriteBool("IndicateRatings", prefs->indicateratings);
    ini.WriteBool("WatchClipboard4ED2kFilelinks", prefs->watchclipboard);
    ini.WriteBool("AutoConnectStaticOnly",          theApp.dynprefs->Get<bool>("auto-static"));
    ini.WriteBool("AutoTakeED2KLinks", prefs->autotakeed2klinks);
    ini.WriteBool("AddNewFilesPaused",              theApp.dynprefs->Get<bool>("add-paused"));
    ini.WriteInt("3DDepth",                         theApp.dynprefs->Get<long>("progress-bar-style"));
    ini.WriteBool("NotifyOnDownload", prefs->useDownloadNotifier);
    ini.WriteBool("NotifyOnChat", prefs->useChatNotifier);
    ini.WriteBool("NotifyOnLog", prefs->useLogNotifier);
    ini.WriteBool("NotifierUseSound", prefs->useSoundInNotifier);
    ini.WriteBool("NotifierPopEveryChatMessage", prefs->notifierPopsEveryChatMsg);
    ini.WriteBool("NotifierPopNewVersion", prefs->notifierNewVersion);
    buffer.Printf("%s", prefs->notifierSoundFilePath);
    ini.WriteString("NotifierSoundPath", buffer);
    buffer.Printf("%s", prefs->notifierConfiguration);
    ini.WriteString("NotifierConfiguration", buffer);
    ini.WriteString("TxtEditor", prefs->TxtEditor);
    ini.WriteString("VideoPlayer", prefs->VideoPlayer);
    ini.WriteString("MessageFilter", prefs->messageFilter);
    ini.WriteString("CommentFilter", prefs->commentFilter);
    ini.WriteString("DateTimeFormat", GetDateTimeFormat());
    ini.WriteString("WebTemplateFile", prefs->m_sTemplateFile);
    ini.WriteString("DefaultIRCServer", prefs->m_sircserver);
    ini.WriteString("IRCNick", prefs->m_sircnick);
    ini.WriteBool("IRCAddTimestamp", prefs->m_bircaddtimestamp);
    ini.WriteString("IRCFilterName", prefs->m_sircchannamefilter);
    ini.WriteInt("IRCFilterUser", prefs->m_iircchanneluserfilter);
    ini.WriteBool("IRCUseFilter", prefs->m_bircusechanfilter);
    ini.WriteString("IRCPerformString", prefs->m_sircperformstring);
    ini.WriteBool("IRCUsePerform", prefs->m_bircuseperform);
    ini.WriteBool("IRCListOnConnect", prefs->m_birclistonconnect);
    ini.WriteBool("IRCAcceptLinks", prefs->m_bircacceptlinks);
    ini.WriteBool("IRCIgnoreInfoMessage", prefs->m_bircignoreinfomessage);
    ini.WriteBool("IRCIgnoreEmuleProtoInfoMessage", prefs->m_bircignoreemuleprotoinfomessage);
    ini.WriteBool("NotifyOnImportantError", prefs->notifierImportantError);
    ini.WriteBool("SmartIdCheck",                   theApp.dynprefs->Get<bool>("smart-lowid-check"));
    ini.WriteBool("Verbose", prefs->m_bVerbose);
    ini.WriteBool("PreviewPrio",                    theApp.dynprefs->Get<bool>("last-chunk-first"));
    ini.WriteBool("UpdateQueueListPref",            theApp.dynprefs->Get<bool>("realtime-queue"));
    ini.WriteBool("ManualHighPrio",                 theApp.dynprefs->Get<bool>("add-server-high"));
    ini.WriteBool("FullChunkTransfers",             theApp.dynprefs->Get<bool>("transfer-full-chunks"));
    ini.WriteBool("StartNextFile",                  theApp.dynprefs->Get<bool>("start-next-file"));
    ini.WriteBool("ShowOverhead",                   theApp.dynprefs->Get<bool>("show-overhead"));
    ini.WriteBool("VideoPreviewBackupped", prefs->moviePreviewBackup);
    ini.WriteInt("FileBufferSizePref",              theApp.dynprefs->Get<long>("file-buffer-size"));
    ini.WriteInt("QueueSizePref",                   theApp.dynprefs->Get<long>("upload-queue-size"));
    ini.WriteBool("UAPPref",                        theApp.dynprefs->Get<bool>("auto-priority-share"));
    ini.WriteInt("AllcatType", prefs->allcatType);
    ini.WriteBool("ShowAllNotCats", prefs->showAllNotCats);
    ini.WriteBool("DisableKnownClientList", prefs->m_bDisableKnownClientList);
    ini.WriteBool("DisableQueueList", prefs->m_bDisableQueueList);
    ini.WriteBool("UseCreditSystem", prefs->m_bCreditSystem);
    ini.WriteBool("SaveLogToDisk", prefs->log2disk);
    ini.WriteBool("SaveDebugToDisk", prefs->debug2disk);
    ini.WriteBool("EnableScheduler", prefs->scheduler);
    ini.WriteBool("MessagesFromFriendsOnly", prefs->msgonlyfriends);
    ini.WriteBool("MessageFromValidSourcesOnly", prefs->msgsecure);
    ini.WriteBool("ShowInfoOnCatTabs", prefs->showCatTabInfos);
    ini.WriteBool("ResumeNextFromSameCat", prefs->resumeSameCat);
    ini.WriteBool("DontRecreateStatGraphsOnResize", prefs->dontRecreateGraphs);
    ini.WriteInt("VersionCheckLastAutomatic", prefs->versioncheckLastAutomatic);
    ini.WriteInt("FilterLevel", prefs->filterlevel);
    ini.SerGet(false, prefs->downloadColumnWidths, ELEMENT_COUNT(prefs->downloadColumnWidths), "DownloadColumnWidths");
    ini.SerGet(false, prefs->downloadColumnHidden, ELEMENT_COUNT(prefs->downloadColumnHidden), "DownloadColumnHidden");
    ini.SerGet(false, prefs->downloadColumnOrder, ELEMENT_COUNT(prefs->downloadColumnOrder), "DownloadColumnOrder");
    ini.SerGet(false, prefs->uploadColumnWidths, ELEMENT_COUNT(prefs->uploadColumnWidths), "UploadColumnWidths");
    ini.SerGet(false, prefs->uploadColumnHidden, ELEMENT_COUNT(prefs->uploadColumnHidden), "UploadColumnHidden");
    ini.SerGet(false, prefs->uploadColumnOrder, ELEMENT_COUNT(prefs->uploadColumnOrder), "UploadColumnOrder");
    ini.SerGet(false, prefs->queueColumnWidths, ELEMENT_COUNT(prefs->queueColumnWidths), "QueueColumnWidths");
    ini.SerGet(false, prefs->queueColumnHidden, ELEMENT_COUNT(prefs->queueColumnHidden), "QueueColumnHidden");
    ini.SerGet(false, prefs->queueColumnOrder, ELEMENT_COUNT(prefs->queueColumnOrder), "QueueColumnOrder");
    ini.SerGet(false, prefs->searchColumnWidths, ELEMENT_COUNT(prefs->searchColumnWidths), "SearchColumnWidths");
    ini.SerGet(false, prefs->searchColumnHidden, ELEMENT_COUNT(prefs->searchColumnHidden), "SearchColumnHidden");
    ini.SerGet(false, prefs->searchColumnOrder, ELEMENT_COUNT(prefs->searchColumnOrder), "SearchColumnOrder");
    ini.SerGet(false, prefs->sharedColumnWidths, ELEMENT_COUNT(prefs->sharedColumnWidths), "SharedColumnWidths");
    ini.SerGet(false, prefs->sharedColumnHidden, ELEMENT_COUNT(prefs->sharedColumnHidden), "SharedColumnHidden");
    ini.SerGet(false, prefs->sharedColumnOrder, ELEMENT_COUNT(prefs->sharedColumnOrder), "SharedColumnOrder");
    ini.SerGet(false, prefs->serverColumnWidths, ELEMENT_COUNT(prefs->serverColumnWidths), "ServerColumnWidths");
    ini.SerGet(false, prefs->serverColumnHidden, ELEMENT_COUNT(prefs->serverColumnHidden), "ServerColumnHidden");
    ini.SerGet(false, prefs->serverColumnOrder, ELEMENT_COUNT(prefs->serverColumnOrder), "ServerColumnOrder");
    ini.SerGet(false, prefs->clientListColumnWidths, ELEMENT_COUNT(prefs->clientListColumnWidths), "ClientListColumnWidths");
    ini.SerGet(false, prefs->clientListColumnHidden, ELEMENT_COUNT(prefs->clientListColumnHidden), "ClientListColumnHidden");
    ini.SerGet(false, prefs->clientListColumnOrder, ELEMENT_COUNT(prefs->clientListColumnOrder), "ClientListColumnOrder");
    ini.WriteInt("TableSortItemDownload", prefs->tableSortItemDownload);
    ini.WriteInt("TableSortItemUpload", prefs->tableSortItemUpload);
    ini.WriteInt("TableSortItemQueue", prefs->tableSortItemQueue);
    ini.WriteInt("TableSortItemSearch", prefs->tableSortItemSearch);
    ini.WriteInt("TableSortItemShared", prefs->tableSortItemShared);
    ini.WriteInt("TableSortItemServer", prefs->tableSortItemServer);
    ini.WriteInt("TableSortItemClientList", prefs->tableSortItemClientList);
    ini.WriteBool("TableSortAscendingDownload", prefs->tableSortAscendingDownload);
    ini.WriteBool("TableSortAscendingUpload", prefs->tableSortAscendingUpload);
    ini.WriteBool("TableSortAscendingQueue", prefs->tableSortAscendingQueue);
    ini.WriteBool("TableSortAscendingSearch", prefs->tableSortAscendingSearch);
    ini.WriteBool("TableSortAscendingShared", prefs->tableSortAscendingShared);
    ini.WriteBool("TableSortAscendingServer", prefs->tableSortAscendingServer);
    ini.WriteBool("TableSortAscendingClientList", prefs->tableSortAscendingClientList);
    ini.WriteBool("ProxyEnablePassword", prefs->proxy.EnablePassword, "Proxy");
    ini.WriteBool("ProxyEnableProxy", prefs->proxy.UseProxy, "Proxy");
    ini.WriteString("ProxyName", prefs->proxy.name, "Proxy");
    ini.WriteString("ProxyPassword", prefs->proxy.password, "Proxy");
    ini.WriteString("ProxyUser", prefs->proxy.user, "Proxy");
    ini.WriteInt("ProxyPort", prefs->proxy.port, "Proxy");
    ini.WriteInt("ProxyType", prefs->proxy.type, "Proxy");
    for (int i = 0 ; i < 13 ; i++)
    {
        buffer.Printf("%lu", (unsigned long) GetStatsColor(i));
        buffer2.Printf("StatColor%i", i);
        ini.WriteString(buffer2, buffer, "eMule");
    }
    buffer.Printf("%llu", (unsigned long long) prefs->totalDownloadedBytes);
    ini.WriteString("TotalDownloadedBytes", buffer, "Statistics");
    buffer.Printf("%llu", (unsigned long long) prefs->totalUploadedBytes);
    ini.WriteString("TotalUploadedBytes", buffer, "Statistics");
    ini.WriteInt("DesktopMode", theApp.dynprefs->Get<long>("systray-integration"));
    ini.WriteString("Password", GetWSPass(), "WebServer");
    ini.WriteString("PasswordLow", GetWSLowPass());
    ini.WriteInt("Port", prefs->m_nWebPort);
    ini.WriteBool("Enabled", prefs->m_bWebEnabled);
    ini.WriteBool("UseGzip", prefs->m_bWebUseGzip);
    ini.WriteInt("PageRefreshTime", prefs->m_nWebPageRefresh);
    ini.WriteBool("UseLowRightsUser", prefs->m_bWebLowEnabled);
    ini.WriteBool("NoNeededSources", prefs->DropNoNeededSources, "Razor_Preferences");
    ini.WriteBool("SwapNoNeededSources", prefs->SwapNoNeededSources);
    ini.WriteBool("FullQueueSources", prefs->DropFullQueueSources);
    ini.WriteBool("HighQueueRankingSources", prefs->DropHighQueueRankingSources);
    ini.WriteInt("HighQueueRanking", prefs->HighQueueRanking);
    ini.WriteInt("AutoDropTimer", prefs->AutoDropTimer);
}

bool CPreferences::LoadPreferences(void)
{
    bool error = false;
    bool NoColor = true;    
    wxString buffer2;
    char buffer[200];
    //Open File for Test
    wxString full_path(getenv("HOME"), *wxConvCurrent);

    full_path += wxT("/.eMule");

    error = wxFileExists(full_path) == false;
    // Use CIni anyway to load or to create the values
    CIni ini(full_path, "eMule");

    theApp.dynprefs->Add("nickname",               ini.GetString("Nick", "http://www.xmule.ws/"));
    theApp.dynprefs->Add("incoming-directory",     ini.GetString("IncomingDir", const_cast<char *>(wxString(theApp.dynprefs->Get<wxString>("app-directory") + "Incoming").c_str())));
    theApp.dynprefs->Add("temp-directory",         ini.GetString("TempDir", const_cast<char *>(wxString(theApp.dynprefs->Get<wxString>("app-directory") + "Temp").c_str())));
    theApp.dynprefs->Add("limits-upload",          static_cast<long>(ini.GetInt("MaxUpload", UNLIMITED)));
    theApp.dynprefs->Add("limits-download",        static_cast<long>(ini.GetInt("MaxDownload", UNLIMITED)));
    theApp.dynprefs->Add("max-connections",        static_cast<long>(ini.GetInt("MaxConnections", 500)));
    theApp.dynprefs->Add("remove-dead-server",     static_cast<long>(ini.GetInt("RemoveDeadServer", 2)));
    theApp.dynprefs->Add("tcp-port",               static_cast<long>(ini.GetInt("Port", 4662)));
    theApp.dynprefs->Add("udp-port",               static_cast<long>(ini.GetInt("UDPPort", theApp.dynprefs->Get<long>("tcp-port") + 10)));
    theApp.dynprefs->Add("max-sources",            static_cast<long>(ini.GetInt("MaxSourcesPerFile", 400)));
    prefs->languageID = ini.GetWORD("Language", 0);
    theApp.dynprefs->Add("see-share",              static_cast<long>(ini.GetInt("SeeShare", 2)));
    prefs->m_iToolDelayTime = ini.GetInt("ToolTipDelay", 1);
    theApp.dynprefs->Add("graph-delay",            static_cast<long>(ini.GetInt("StatGraphsInterval", 3)));
    theApp.dynprefs->Add("tree-delay",             static_cast<long>(ini.GetInt("statsInterval", 5)));
    theApp.dynprefs->Add("capacities-download",    static_cast<long>(ini.GetInt("DownloadCapacity", 96)));
    theApp.dynprefs->Add("capacities-upload",      static_cast<long>(ini.GetInt("UploadCapacity", 16)));
    theApp.dynprefs->Add("server-connect-retries", static_cast<long>(ini.GetInt("DeadServerRetry", 1)));
    prefs->splitterbarPosition = ini.GetInt("SplitterbarPosition", 75);
    theApp.dynprefs->Add("graph-average",          static_cast<long>(ini.GetInt("StatsAverageMinutes", 5)));
    theApp.dynprefs->Add("max-per-5",              static_cast<long>(ini.GetInt("MaxConnectionsPerFiveSeconds", GetDefaultMaxConperFive())));
    theApp.dynprefs->Add("reconnect-on-loss",      ini.GetBool("Reconnect", true));
    theApp.dynprefs->Add("priority-system",        ini.GetBool("Scoresystem", true));
    theApp.dynprefs->Add("enable-ich",             ini.GetBool("ICH", true));
    theApp.dynprefs->Add("autoupdate-server",      ini.GetBool("Serverlist", false));    
    snprintf(prefs->m_szLRUServermetURL, sizeof prefs->m_szLRUServermetURL, "%s", ini.GetString("LRUServermetURL") .GetData());
    prefs->updatenotify = ini.GetBool("UpdateNotify", false);
    theApp.dynprefs->Add("minimize-to-tray",       ini.GetBool("MinToTray", false));
    theApp.dynprefs->Add("add-server-server",      ini.GetBool("AddServersFromServer", true));
    theApp.dynprefs->Add("add-server-client",      ini.GetBool("AddServersFromClient", true));
    theApp.dynprefs->Add("show-splashscreen",      ini.GetBool("Splashscreen", true));
    theApp.dynprefs->Add("bring-to-front",         ini.GetBool("BringToFront", true));
    theApp.dynprefs->Add("download-doubleclick",   ini.GetBool("TransferDoubleClick", true));
    theApp.dynprefs->Add("beep-on-errors",         ini.GetBool("BeepOnError", true));
    theApp.dynprefs->Add("prompt-on-exit",         ini.GetBool("ConfirmExit", false));
    theApp.dynprefs->Add("filter-bad-ip",          ini.GetBool("FilterBadIPs", true));
    theApp.dynprefs->Add("autoconnect",            ini.GetBool("Autoconnect", false));
    theApp.dynprefs->Add("xfer-on-title",          ini.GetBool("ShowRatesOnTitle", false));
    theApp.dynprefs->Add("online-signature",       ini.GetBool("OnlineSignature", false));
    theApp.dynprefs->Add("start-minimized",        ini.GetBool("StartupMinimized", false));
    theApp.dynprefs->Add("use-safe-connect",       ini.GetBool("SafeServerConnect", false));
    prefs->filterlevel = ini.GetInt("FilterLevel", 127);
    theApp.dynprefs->Add("auto-static",            ini.GetBool("AutoConnectStaticOnly", false));
    prefs->autotakeed2klinks = ini.GetBool("AutoTakeED2KLinks", true);
    theApp.dynprefs->Add("add-paused",             ini.GetBool("AddNewFilesPaused", false));
    theApp.dynprefs->Add("progress-bar-style",     static_cast<long>(ini.GetInt("3DDepth", 0)));
    prefs->useDownloadNotifier = ini.GetBool("NotifyOnDownload", false);
    prefs->useChatNotifier = ini.GetBool("NotifyOnChat", false);
    prefs->useLogNotifier = ini.GetBool("NotifyOnLog", false);
    prefs->useSoundInNotifier = ini.GetBool("NotifierUseSound", false);
    prefs->notifierPopsEveryChatMsg = ini.GetBool("NotifierPopEveryChatMessage", false);
    prefs->notifierImportantError = ini.GetBool("NotifyOnImportantError", false);
    prefs->notifierNewVersion = ini.GetBool("NotifierPopNewVersion", false);
    sprintf(prefs->notifierSoundFilePath, "%s", ini.GetString("NotifierSoundPath", "") .GetData());
    sprintf(prefs->notifierConfiguration, "%s", ini.GetString("NotifierConfiguration", "") .GetData());
    sprintf(prefs->datetimeformat, "%s", ini.GetString("DateTimeFormat", "%A, %x, %X") .GetData());
    sprintf(prefs->m_sircserver, "%s", ini.GetString("DefaultIRCServer", "irc.emule-project.net") .GetData());
    sprintf(prefs->m_sircnick, "%s", ini.GetString("IRCNick", "eMule") .GetData());
    prefs->m_bircaddtimestamp = ini.GetBool("IRCAddTimestamp", true);
    sprintf(prefs->m_sircchannamefilter, "%s", ini.GetString("IRCFilterName", "") .GetData());
    prefs->m_bircusechanfilter = ini.GetBool("IRCUseFilter", false);
    prefs->m_iircchanneluserfilter = ini.GetInt("IRCFilterUser", 0);
    sprintf(prefs->m_sircperformstring, "%s", ini.GetString("IRCPerformString", "/join #emule") .GetData());
    prefs->m_bircuseperform = ini.GetBool("IRCUsePerform", false);
    prefs->m_birclistonconnect = ini.GetBool("IRCListOnConnect", true);
    prefs->m_bircacceptlinks = ini.GetBool("IRCAcceptLinks", false);
    prefs->m_bircignoreinfomessage = ini.GetBool("IRCIgnoreInfoMessage", false);
    prefs->m_bircignoreemuleprotoinfomessage = ini.GetBool("IRCIgnoreEmuleProtoInfoMessage", true);
    theApp.dynprefs->Add("smart-lowid-check",      ini.GetBool("SmartIdCheck", true));
    prefs->m_bVerbose = ini.GetBool("Verbose", false);
    theApp.dynprefs->Add("last-chunk-first",       ini.GetBool("PreviewPrio", false));
    theApp.dynprefs->Add("realtime-queue",         ini.GetBool("UpdateQueueListPref", false));
    theApp.dynprefs->Add("add-server-high",        ini.GetBool("ManualHighPrio", false));
    theApp.dynprefs->Add("transfer-full-chunks",   ini.GetBool("FullChunkTransfers", true));
    theApp.dynprefs->Add("start-next-file",        ini.GetBool("StartNextFile", false));
    theApp.dynprefs->Add("show-overhead",          ini.GetBool("ShowOverhead", false));
    prefs->moviePreviewBackup = ini.GetBool("VideoPreviewBackupped", true);
    theApp.dynprefs->Add("file-buffer-size",       static_cast<long>(ini.GetInt("FileBufferSizePref", 16)));
    theApp.dynprefs->Add("upload-queue-size",      static_cast<long>(ini.GetInt("QueueSizePref", 50)));
    prefs->versioncheckdays = ini.GetInt("Check4NewVersionDelay", 5);
    theApp.dynprefs->Add("auto-priority-share",    ini.GetBool("UAPPref", true));
    prefs->indicateratings = ini.GetBool("IndicateRatings", true);
    prefs->allcatType = ini.GetInt("AllcatType", 0);
    prefs->showAllNotCats = ini.GetBool("ShowAllNotCats", false);
    prefs->watchclipboard = ini.GetBool("WatchClipboard4ED2kFilelinks", false);
    prefs->log2disk = ini.GetBool("SaveLogToDisk", false);
    prefs->debug2disk = ini.GetBool("SaveDebugToDisk", false);
    prefs->iMaxLogMessages = ini.GetInt("MaxLogMessages", 1000);
    prefs->showCatTabInfos = ini.GetBool("ShowInfoOnCatTabs", false);
    prefs->resumeSameCat = ini.GetBool("ResumeNextFromSameCat", false);
    prefs->resumeSameCat = ini.GetBool("DontRecreateStatGraphsOnResize", false);
    prefs->versioncheckLastAutomatic = ini.GetInt("VersionCheckLastAutomatic", 0);
    prefs->m_bDisableKnownClientList = ini.GetInt("DisableKnownClientList", false);
    prefs->m_bDisableQueueList = ini.GetInt("DisableQueueList", false);
    prefs->m_bCreditSystem = ini.GetInt("UseCreditSystem", true);
    prefs->scheduler = ini.GetBool("EnableScheduler", false);
    prefs->msgonlyfriends = ini.GetBool("MessagesFromFriendsOnly", false);
    prefs->msgsecure = ini.GetBool("MessageFromValidSourcesOnly", true);
    prefs->maxmsgsessions = ini.GetInt("MaxMessageSessions", 50);
    sprintf(prefs->TxtEditor, "%s", ini.GetString("TxtEditor", "notepad.exe") .GetData());
    sprintf(prefs->VideoPlayer, "%s", ini.GetString("VideoPlayer", "") .GetData());
    sprintf(prefs->m_sTemplateFile, "%s", ini.GetString("WebTemplateFile", "eMule.tmpl") .GetData());
    sprintf(prefs->messageFilter, "%s", ini.GetString("MessageFilter", "Your client has an infinite queue") .GetData());
    sprintf(prefs->commentFilter, "%s", ini.GetString("CommentFilter", "http://") .GetData());
    ini.SerGet(true, prefs->downloadColumnWidths, ELEMENT_COUNT(prefs->downloadColumnWidths), "DownloadColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->downloadColumnHidden, ELEMENT_COUNT(prefs->downloadColumnHidden), "DownloadColumnHidden");
    ini.SerGet(true, prefs->downloadColumnOrder, ELEMENT_COUNT(prefs->downloadColumnOrder), "DownloadColumnOrder");
    ini.SerGet(true, prefs->uploadColumnWidths, ELEMENT_COUNT(prefs->uploadColumnWidths), "UploadColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->uploadColumnHidden, ELEMENT_COUNT(prefs->uploadColumnHidden), "UploadColumnHidden");
    ini.SerGet(true, prefs->uploadColumnOrder, ELEMENT_COUNT(prefs->uploadColumnOrder), "UploadColumnOrder");
    ini.SerGet(true, prefs->queueColumnWidths, ELEMENT_COUNT(prefs->queueColumnWidths), "QueueColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->queueColumnHidden, ELEMENT_COUNT(prefs->queueColumnHidden), "QueueColumnHidden");
    ini.SerGet(true, prefs->queueColumnOrder, ELEMENT_COUNT(prefs->queueColumnOrder), "QueueColumnOrder");
    ini.SerGet(true, prefs->searchColumnWidths, ELEMENT_COUNT(prefs->searchColumnWidths), "SearchColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->searchColumnHidden, ELEMENT_COUNT(prefs->searchColumnHidden), "SearchColumnHidden");
    ini.SerGet(true, prefs->searchColumnOrder, ELEMENT_COUNT(prefs->searchColumnOrder), "SearchColumnOrder");
    ini.SerGet(true, prefs->sharedColumnWidths, ELEMENT_COUNT(prefs->sharedColumnWidths), "SharedColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->sharedColumnHidden, ELEMENT_COUNT(prefs->sharedColumnHidden), "SharedColumnHidden");
    ini.SerGet(true, prefs->sharedColumnOrder, ELEMENT_COUNT(prefs->sharedColumnOrder), "SharedColumnOrder");
    ini.SerGet(true, prefs->serverColumnWidths, ELEMENT_COUNT(prefs->serverColumnWidths), "ServerColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->serverColumnHidden, ELEMENT_COUNT(prefs->serverColumnHidden), "ServerColumnHidden");
    ini.SerGet(true, prefs->serverColumnOrder, ELEMENT_COUNT(prefs->serverColumnOrder), "ServerColumnOrder");
    ini.SerGet(true, prefs->clientListColumnWidths, ELEMENT_COUNT(prefs->clientListColumnWidths), "ClientListColumnWidths", NULL, DEFAULT_COL_SIZE);
    ini.SerGet(true, prefs->clientListColumnHidden, ELEMENT_COUNT(prefs->clientListColumnHidden), "ClientListColumnHidden");
    ini.SerGet(true, prefs->clientListColumnOrder, ELEMENT_COUNT(prefs->clientListColumnOrder), "ClientListColumnOrder");
    prefs->tableSortItemDownload = ini.GetInt("TableSortItemDownload", 0);
    prefs->tableSortItemUpload = ini.GetInt("TableSortItemUpload", 0);
    prefs->tableSortItemQueue = ini.GetInt("TableSortItemQueue", 0);
    prefs->tableSortItemSearch = ini.GetInt("TableSortItemSearch", 0);
    prefs->tableSortItemShared = ini.GetInt("TableSortItemShared", 0);
    prefs->tableSortItemServer = ini.GetInt("TableSortItemServer", 0);
    prefs->tableSortItemClientList = ini.GetInt("TableSortItemClientList", 0);
    prefs->tableSortAscendingDownload = ini.GetBool("TableSortAscendingDownload", true);
    prefs->tableSortAscendingUpload = ini.GetBool("TableSortAscendingUpload", true);
    prefs->tableSortAscendingQueue = ini.GetBool("TableSortAscendingQueue", true);
    prefs->tableSortAscendingSearch = ini.GetBool("TableSortAscendingSearch", true);
    prefs->tableSortAscendingShared = ini.GetBool("TableSortAscendingShared", true);
    prefs->tableSortAscendingServer = ini.GetBool("TableSortAscendingServer", true);
    prefs->tableSortAscendingClientList = ini.GetBool("TableSortAscendingClientList", true);
    prefs->proxy.EnablePassword = ini.GetBool("ProxyEnablePassword", false, "Proxy");
    prefs->proxy.UseProxy = ini.GetBool("ProxyEnableProxy", false, "Proxy");
    sprintf(buffer, "");
    sprintf(prefs->proxy.name, "%s", ini.GetString("ProxyName", buffer, "Proxy") .GetData());
    sprintf(prefs->proxy.password, "%s", ini.GetString("ProxyPassword", buffer, "Proxy") .GetData());
    sprintf(prefs->proxy.user, "%s", ini.GetString("ProxyUser", buffer, "Proxy") .GetData());
    
    for (int i = 0 ; i < 13 ; i++)
    {
         buffer2.Printf("StatColor%i", i);
         sprintf(buffer, "%s", ini.GetString(buffer2, "0", "eMule") .c_str());
         if ((prefs->statcolors[i] = atoll(buffer))) NoColor = false;
    }
    
    if (NoColor)
    {
         for (int i = 0 ; i < 13 ; i++)
         {
              ResetStatsColor(i);
         }
    }
    
    sprintf(buffer, "%s", ini.GetString("TotalDownloadedBytes", 0, "Statistics") .c_str());
    prefs->totalDownloadedBytes = atoll(buffer);
    sprintf(buffer, "%s", ini.GetString("TotalUploadedBytes", 0, "Statistics") .c_str());
    prefs->totalUploadedBytes = atoll(buffer);
    theApp.dynprefs->Add("systray-integration", static_cast<long>(ini.GetInt("DesktopMode", 0)));
    sprintf(prefs->m_sWebPassword, "%s", ini.GetString("Password", "", "WebServer") .GetData());
    sprintf(prefs->m_sWebLowPassword, "%s", ini.GetString("PasswordLow", "") .GetData());
    prefs->m_nWebPort = ini.GetInt("Port", 4711);
    prefs->m_bWebEnabled = ini.GetBool("Enabled", false);
    prefs->m_bWebUseGzip = ini.GetBool("UseGzip", true);
    prefs->m_bWebLowEnabled = ini.GetBool("UseLowRightsUser", false);
    prefs->m_nWebPageRefresh = ini.GetInt("PageRefreshTime", 120);
    prefs->dontcompressavi = ini.GetBool("DontCompressAvi", false);
    prefs->DropNoNeededSources = ini.GetBool("NoNeededSources", false, "Razor_Preferences");
    prefs->SwapNoNeededSources = ini.GetBool("SwapNoNeededSources", false);
    prefs->DropFullQueueSources = ini.GetBool("FullQueueSources", false);
    prefs->DropHighQueueRankingSources = ini.GetBool("HighQueueRankingSources", false);
    prefs->HighQueueRanking = ini.GetInt("HighQueueRanking", 1200);
    prefs->AutoDropTimer = ini.GetInt("AutoDropTimer", 240);

    return error;
}

bool CPreferences::Load_Adresses(void)
{
    //serverlist adresses
    bool error = false;
    char *full_path = new char[theApp.dynprefs->Get<wxString>("app-directory").length() + 13];
    sprintf(full_path, "%sadresses.dat", static_cast<const char *>(theApp.dynprefs->Get<wxString>("app-directory").c_str()));
    FILE *sdirfile = fopen(full_path, "r");
    delete[] full_path;

    if (sdirfile)
    {
        char buffer[MAX_PATH];

        while (!feof(sdirfile))
        {
            memset(buffer, 0, sizeof(buffer));
            fgets(buffer, sizeof(buffer) - 1, sdirfile);
            char *ptr = strchr(buffer, '\n');

            if (ptr)
            {
                *ptr = 0;
            }

            if (strlen(buffer) > 1)
            {
                addresses_list.push_back(wxString(buffer, *wxConvCurrent));
            }
        }

        fclose(sdirfile);
    }
    else
    {
        error = true;
    }

    return error;
}

bool CPreferences::Save_Adresses(void)
{
    bool error = false;
    ; // I am to lazy atm :)
    return error;
}

bool CPreferences::Load_Shared_Dirs(void)
{
    bool error;
    char *full_path = new char[theApp.dynprefs->Get<wxString>("app-directory").length() + 14];
    sprintf(full_path, "%sshareddir.dat", static_cast<const char *>(theApp.dynprefs->Get<wxString>("app-directory").c_str()));
    FILE *sdirfile = fopen(full_path, "r");
    delete[] full_path;
    if (sdirfile)
    {
        char buffer[MAX_PATH];
        while (!feof(sdirfile))
        {
            memset(buffer, 0, sizeof(buffer));
            fgets(buffer, sizeof(buffer) - 1, sdirfile);
            char *ptr = strchr(buffer, '\n');
            if (ptr) *ptr = 0;
            if (strlen(buffer) > 1)
            shareddir_list.Add(buffer);
        }
        fclose(sdirfile);
    }
    else
    {
        error = true;
    }
    return error;
}

bool CPreferences::Save_Shared_Dirs(void)
{
    bool error = false;
    char *full_path = new char[theApp.dynprefs->Get<wxString>("app-directory").length() + 14];
    sprintf(full_path, "%sshareddir.dat", static_cast<const char *>(theApp.dynprefs->Get<wxString>("app-directory").c_str()));
    FILE *sdirfile = fopen(full_path, "w");
    delete[] full_path;
    if (sdirfile)
    {
        for (int i = 0 ; i < shareddir_list.GetCount() ; i++)
        {
            fprintf(sdirfile, "%s\n", shareddir_list[i].GetData());
        }
        fclose(sdirfile);
    }
    else
    {
        error = true;
    }
    return error;
}


bool CPreferences::SaveCats(void)
{
    bool error = false;
    ofstream fout;
    wxString buffer;
    wxString catinif(theApp.dynprefs->Get<wxString>("app-directory") + wxT("Category.dat"));

    if (GetCatCount() > 0)
    {
        fout.open(catinif.c_str());

        if (fout.good() == true)
        {
            fout << catMap.GetCount() - 1 << " ";

            for (int ix = 1; ix < catMap.GetCount(); ++ix)
            { 
                fout << catMap.GetAt(ix)->title << endl;
                fout << catMap.GetAt(ix)->incomingpath << endl;

                if (catMap.GetAt(ix)->comment != "")
                {
                    fout << catMap.GetAt(ix)->comment << endl;
                }
                else
                {
                    fout << "-1" << endl;
                }

                fout << "0x" << std::hex << catMap.GetAt(ix)->color << endl;
                fout << std::setprecision(3) << std::fixed << catMap.GetAt(ix)->prio + 1 << endl;
            }

            fout.close();
        } 
        else
        {
            error = true;
        }
    }
    return error;
}
#include <iostream>
using std::cout;
bool CPreferences::LoadCats(void)
{
    bool error = false;
    int max;
    char buffer[2051];
    char *dummy;

    // default cat
    Category_Struct* newcat = new Category_Struct;
    newcat->prio = 0;
    newcat->color = 0;
    AddCat(newcat);
    // Load cats
    wxString catinif(theApp.dynprefs->Get<wxString>("app-directory") + wxT("Category.dat"));

    ifstream fin(catinif.c_str());
    
    if (fin.good() == true)
    {
        fin >> max;

        std::string temp;

        for (int i = 1; i <= max; ++i)
        {
            Category_Struct* newcat = new Category_Struct;

            fin >> temp;
            newcat->title = wxString(temp.c_str(), *wxConvCurrent);

            fin >> temp;
            newcat->incomingpath = wxString(temp.c_str(), *wxConvCurrent);

            fin >> temp;

            if (temp == "-1")
            {
                newcat->comment = "";
            }
            else
            {
                newcat->comment = wxString(temp.c_str(), *wxConvCurrent);
            }

            fin >> std::hex >> newcat->color;
            fin >> std::dec >> newcat->prio;

            AddCat(newcat);

            if (!wxFileName::DirExists(newcat->incomingpath)) 
            {
                wxMkdir(newcat->incomingpath, 0777);
            }
        }

        fin.close();
    } 
    else
    {
       error = true;
    }
    return error;
}

void CPreferences::RemoveCat(int index)
{
    if (index >= 0 &&index < catMap.GetCount())
    {
        Category_Struct *delcat;
        delcat = catMap.GetAt(index);
        catMap.RemoveAt(index);
        delete delcat;
    }
}

int CPreferences::GetColumnSortItem(Table t) const
{

    switch (t)
    {
    case tableDownload:
        return prefs->tableSortItemDownload;
    case tableUpload:
        return prefs->tableSortItemUpload;
    case tableQueue:
        return prefs->tableSortItemQueue;
    case tableSearch:
        return prefs->tableSortItemSearch;
    case tableShared:
        return prefs->tableSortItemShared;
    case tableServer:
        return prefs->tableSortItemServer;
    case tableClientList:
        return prefs->tableSortItemClientList;
    }
    return 0;
}

bool CPreferences::GetColumnSortAscending(Table t) const
{
    switch (t)
    {
    case tableDownload:
        return prefs->tableSortAscendingDownload;
    case tableUpload:
        return prefs->tableSortAscendingUpload;
    case tableQueue:
        return prefs->tableSortAscendingQueue;
    case tableSearch:
        return prefs->tableSortAscendingSearch;
    case tableShared:
        return prefs->tableSortAscendingShared;
    case tableServer:
        return prefs->tableSortAscendingServer;
    case tableClientList:
        return prefs->tableSortAscendingClientList;
    }
    return true;

}

void CPreferences::SetColumnSortItem(Table t, int sortItem)
{
    switch (t)
    {
    case tableDownload:
        prefs->tableSortItemDownload = sortItem;
        break;
    case tableUpload:
        prefs->tableSortItemUpload = sortItem;
        break;
    case tableQueue:
        prefs->tableSortItemQueue = sortItem;
        break;
    case tableSearch:
        prefs->tableSortItemSearch = sortItem;
        break;
    case tableShared:
        prefs->tableSortItemShared = sortItem;
        break;
    case tableServer:
        prefs->tableSortItemServer = sortItem;
        break;
    case tableClientList:
        prefs->tableSortItemClientList = sortItem;
        break;
    }
}

void CPreferences::SetColumnSortAscending(Table t, bool sortAscending)
{
    switch (t)
    {
    case tableDownload:
        prefs->tableSortAscendingDownload = sortAscending;
        break;
    case tableUpload:
        prefs->tableSortAscendingUpload = sortAscending;
        break;
    case tableQueue:
        prefs->tableSortAscendingQueue = sortAscending;
        break;
    case tableSearch:
        prefs->tableSortAscendingSearch = sortAscending;
        break;
    case tableShared:
        prefs->tableSortAscendingShared = sortAscending;
        break;
    case tableServer:
        prefs->tableSortAscendingServer = sortAscending;
        break;
    case tableClientList:
        prefs->tableSortAscendingClientList = sortAscending;
        break;
    }
}

int CPreferences::GetColumnWidth(const short int t, int index) const
{
    switch (t)
    {
    case tableDownload:
        return prefs->downloadColumnWidths[index];
    case tableUpload:
        return prefs->uploadColumnWidths[index];
    case tableQueue:
        return prefs->queueColumnWidths[index];
    case tableSearch:
        return prefs->searchColumnWidths[index];
    case tableShared:
        return prefs->sharedColumnWidths[index];
    case tableServer:
        return prefs->serverColumnWidths[index];
    case tableClientList:
        return prefs->clientListColumnWidths[index];
    }
    return 0;

}

void CPreferences::SetColumnWidth(const short int t, int index, int width)
{
    switch (t)
    {
    case tableDownload:
        prefs->downloadColumnWidths[index] = width;
        break;
    case tableUpload:
        prefs->uploadColumnWidths[index] = width;
        break;
    case tableQueue:
        prefs->queueColumnWidths[index] = width;
        break;
    case tableSearch:
        prefs->searchColumnWidths[index] = width;
        break;
    case tableShared:
        prefs->sharedColumnWidths[index] = width;
        break;
    case tableServer:
        prefs->serverColumnWidths[index] = width;
        break;
    case tableClientList:
        prefs->clientListColumnWidths[index] = width;
        break;
    }
}

bool CPreferences::GetColumnHidden(Table t, int index) const
{
    switch (t)
    {
    case tableDownload:
        return prefs->downloadColumnHidden[index];
    case tableUpload:
        return prefs->uploadColumnHidden[index];
    case tableQueue:
        return prefs->queueColumnHidden[index];
    case tableSearch:
        return prefs->searchColumnHidden[index];
    case tableShared:
        return prefs->sharedColumnHidden[index];
    case tableServer:
        return prefs->serverColumnHidden[index];
    case tableClientList:
        return prefs->clientListColumnHidden[index];
    }
    return FALSE;
}

void CPreferences::SetColumnHidden(Table t, int index, bool bHidden)
{
    switch (t)
    {
    case tableDownload:
        prefs->downloadColumnHidden[index] = bHidden;
        break;
    case tableUpload:
        prefs->uploadColumnHidden[index] = bHidden;
        break;
    case tableQueue:
        prefs->queueColumnHidden[index] = bHidden;
        break;
    case tableSearch:
        prefs->searchColumnHidden[index] = bHidden;
        break;
    case tableShared:
        prefs->sharedColumnHidden[index] = bHidden;
        break;
    case tableServer:
        prefs->serverColumnHidden[index] = bHidden;
        break;
    case tableClientList:
        prefs->clientListColumnHidden[index] = bHidden;
        break;
    }
}

int CPreferences::GetColumnOrder(const short int t, int index) const
{
    switch (t)
    {
    case tableDownload:
        return prefs->downloadColumnOrder[index];
    case tableUpload:
        return prefs->uploadColumnOrder[index];
    case tableQueue:
        return prefs->queueColumnOrder[index];
    case tableSearch:
        return prefs->searchColumnOrder[index];
    case tableShared:
        return prefs->sharedColumnOrder[index];
    case tableServer:
        return prefs->serverColumnOrder[index];
    case tableClientList:
        return prefs->clientListColumnOrder[index];
    }
    return 0;
}

void CPreferences::SetColumnOrder(const short int t, INT *piOrder)
{
    switch (t)
    {
    case tableDownload:
        memcpy(prefs->downloadColumnOrder, piOrder, sizeof(prefs->downloadColumnOrder));
        break;
    case tableUpload:
        memcpy(prefs->uploadColumnOrder, piOrder, sizeof(prefs->uploadColumnOrder));
        break;
    case tableQueue:
        memcpy(prefs->queueColumnOrder, piOrder, sizeof(prefs->queueColumnOrder));
        break;
    case tableSearch:
        memcpy(prefs->searchColumnOrder, piOrder, sizeof(prefs->searchColumnOrder));
        break;
    case tableShared:
        memcpy(prefs->sharedColumnOrder, piOrder, sizeof(prefs->sharedColumnOrder));
        break;
    case tableServer:
        memcpy(prefs->serverColumnOrder, piOrder, sizeof(prefs->serverColumnOrder));
        break;
    case tableClientList:
        memcpy(prefs->clientListColumnOrder, piOrder, sizeof(prefs->clientListColumnOrder));
        break;
    }
}

//bool CPreferences::IsSecureIdentEnabled()
//{
//    if (theApp.dynprefs->Get<bool>("secure-ident"))
//    {
//        return true;
//    }
//    else
//    {
//        return false;
//
//    }
//}
