<commit_before>/**
 * @file examples/megacmd/client/megacmdclient.cpp
 * @brief MegaCMDClient: Client application of MEGAcmd
 *
 * (c) 2013-2016 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include <stdio.h>
#include <iostream>
#include <errno.h>
#include <string>
#include <vector>
#include <memory.h>
#include <limits.h>

#include <sys/types.h>
#ifdef _WIN32
#include <WinSock2.h>
#include <Shlwapi.h> //PathAppend
#else
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/un.h>
#endif
#define MEGACMDINITIALPORTNUMBER 12300

#ifdef _WIN32
#include <windows.h>
#define ERRNO WSAGetLastError()
#else
#define ERRNO errno
#endif

#ifndef SOCKET_ERROR
#define SOCKET_ERROR -1
#endif

#ifdef __MACH__
#define MSG_NOSIGNAL 0
#elif _WIN32
#define MSG_NOSIGNAL 0
#endif

bool socketValid(int socket)
{
#ifdef _WIN32
    return socket != INVALID_SOCKET;
#else
    return socket >= 0;
#endif
}

#ifndef INVALID_SOCKET
#define INVALID_SOCKET -1
#endif

void closeSocket(int socket){
#ifdef _WIN32
    closesocket(socket);
#else
    close(socket);
#endif
}

using namespace std;

#ifdef _WIN32
// convert UTF-8 to Windows Unicode
void path2local(string* path, string* local)
{
    // make space for the worst case
    local->resize((path->size() + 1) * sizeof(wchar_t));

    int len = MultiByteToWideChar(CP_UTF8, 0,
                                  path->c_str(),
                                  -1,
                                  (wchar_t*)local->data(),
                                  local->size() / sizeof(wchar_t) + 1);
    if (len)
    {
        // resize to actual result
        local->resize(sizeof(wchar_t) * (len - 1));
    }
    else
    {
        local->clear();
    }
}

// convert to Windows Unicode Utf8
void local2path(string* local, string* path)
{
    path->resize((local->size() + 1) * 4 / sizeof(wchar_t));

    path->resize(WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)local->data(),
                                     local->size() / sizeof(wchar_t),
                                     (char*)path->data(),
                                     path->size() + 1,
                                     NULL, NULL));
    //normalize(path);
}
#endif
string getAbsPath(string relativePath)
{
    if (!relativePath.size())
    {
        return relativePath;
    }

#ifdef _WIN32
    string utf8absolutepath;
    string localpath;
    path2local(&relativePath, &localpath);

    string absolutelocalpath;
    localpath.append("", 1);

   if (!PathIsRelativeW((LPCWSTR)localpath.data()))
   {
       utf8absolutepath = relativePath;
       if (utf8absolutepath.find("\\\\?\\") != 0)
       {
           utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1);
       }
       return utf8absolutepath;
   }

   int len = GetFullPathNameW((LPCWSTR)localpath.data(), 0, NULL, NULL);
   if (len <= 0)
   {
      return relativePath;
   }

   absolutelocalpath.resize(len * sizeof(wchar_t)-1);
   int newlen = GetFullPathNameW((LPCWSTR)localpath.data(), len, (LPWSTR)absolutelocalpath.data(), NULL);
   if (newlen <= 0 || newlen >= len)
   {
       cerr << " failed to get CWD" << endl;
       return relativePath;
   }

   local2path(&absolutelocalpath, &utf8absolutepath);

   if (utf8absolutepath.find("\\\\?\\") != 0)
   {
       utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1);
   }

   return utf8absolutepath;

#else
    if (relativePath.size() && relativePath.at(0) == '/')
    {
        return relativePath;
    }
    else
    {
        char cCurrentPath[PATH_MAX];
        if (!getcwd(cCurrentPath, sizeof(cCurrentPath)))
        {
            cerr << " failed to get CWD" << endl;
            return relativePath;
        }

        string absolutepath = cCurrentPath;
        absolutepath.append("/");
        absolutepath.append(relativePath);
        return absolutepath;
    }

    return relativePath;
#endif

}

string parseArgs(int argc, char* argv[])
{
    vector<string> absolutedargs;
    int itochange = -1;
    int totalRealArgs = 0;
    if (argc>1)
    {
        absolutedargs.push_back(argv[1]);

        if (!strcmp(argv[1],"sync"))
        {
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    totalRealArgs++;
                    itochange = i;
                }
            }

            for (int i = 2; i < argc; i++)
            {
                if (i==itochange && totalRealArgs>=2)
                {
                    absolutedargs.push_back(getAbsPath(argv[i]));
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
        }
        else if (!strcmp(argv[1],"lcd")) //localpath args
        {
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    absolutedargs.push_back(getAbsPath(argv[i]));
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
        }
        else if (!strcmp(argv[1],"get") || !strcmp(argv[1],"preview") || !strcmp(argv[1],"thumbnail"))
        {
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] != '-' )
                {
                    totalRealArgs++;
                    if (totalRealArgs>1)
                    {
                        absolutedargs.push_back(getAbsPath(argv[i]));
                    }
                    else
                    {
                        absolutedargs.push_back(argv[i]);
                    }
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
            if (totalRealArgs == 1)
            {
                absolutedargs.push_back(getAbsPath("."));

            }
        }
        else if (!strcmp(argv[1],"put"))
        {
            int lastRealArg = 0;
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    lastRealArg = i;
                }
            }
            bool firstRealArg = true;
            for  (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-')
                {
                    if (firstRealArg || i <lastRealArg)
                    {
                        absolutedargs.push_back(getAbsPath(argv[i]));
                        firstRealArg = false;
                    }
                    else
                    {
                        absolutedargs.push_back(argv[i]);
                    }
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
        }
        else
        {
            for (int i = 2; i < argc; i++)
            {
                absolutedargs.push_back(argv[i]);
            }
        }
    }

    string toret="";
    for (u_int i=0; i < absolutedargs.size(); i++)
    {
        if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size())
        {
            toret += "\"";
        }
        toret+=absolutedargs.at(i);
        if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size())
        {
            toret += "\"";
        }

        if (i != (absolutedargs.size()-1))
        {
            toret += " ";
        }
    }

    return toret;
}

#ifdef _WIN32
int createSocket(int number = 0, bool net = true)
#else
int createSocket(int number = 0, bool net = false)
#endif
{
if (net)
{
    int thesock = socket(AF_INET, SOCK_STREAM, 0);
    if (!socketValid(thesock))
    {
        cerr << "ERROR opening socket: " << ERRNO << endl;
        return INVALID_SOCKET;
    }
    int portno=MEGACMDINITIALPORTNUMBER+number;

    struct sockaddr_in addr;

    memset(&addr, 0, sizeof( addr ));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
    addr.sin_port = htons(portno);

    if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR)
    {
        cerr << "Unable to connect to " << (number?("response socket N "+number):"service") << ": error=" << ERRNO << endl;
        if (!number)
        {
            cerr << "Please ensure MegaCMD is running" << endl;
        }
        return INVALID_SOCKET;
    }
    return thesock;
}

#ifndef _WIN32
else
{
    int thesock = socket(AF_UNIX, SOCK_STREAM, 0);
    char socket_path[60];
    if (!socketValid(thesock))
    {
        cerr << "ERROR opening socket: " << ERRNO << endl;
        return INVALID_SOCKET;
    }

    bzero(socket_path, sizeof( socket_path ) * sizeof( *socket_path ));
    if (number)
    {
        sprintf(socket_path, "/tmp/megaCMD_%d/srv_%d", getuid(), number);
    }
    else
    {
        sprintf(socket_path, "/tmp/megaCMD_%d/srv", getuid() );
    }

    struct sockaddr_un addr;

    memset(&addr, 0, sizeof( addr ));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_path, sizeof( addr.sun_path ) - 1);

    if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR)
    {
        cerr << "Unable to connect to " << (number?("response socket N "+number):"service") << ": error=" << ERRNO << endl;
        if (!number)
        {
            cerr << "Please ensure MegaCMD is running" << endl;
        }
        return INVALID_SOCKET;
    }

    return thesock;
}
return INVALID_SOCKET;

#endif
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "Too few arguments" << endl;
        return -1;
    }
    string parsedArgs = parseArgs(argc,argv);

#if _WIN32
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        cerr << "ERROR initializing WSA" << endl;
    }
#endif

    int thesock = createSocket();
    if (thesock == INVALID_SOCKET)
    {
        return INVALID_SOCKET;
    }

    int n = send(thesock,parsedArgs.data(),parsedArgs.size(), MSG_NOSIGNAL);
    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR writing output Code to socket: " << ERRNO << endl;
        return -1;;
    }

    int receiveSocket = SOCKET_ERROR ;

    n = recv(thesock, (char *)&receiveSocket, sizeof(receiveSocket), MSG_NOSIGNAL);
    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR reading output socket" << endl;
        return -1;;
    }

    int newsockfd =createSocket(receiveSocket);
    if (newsockfd == INVALID_SOCKET)
        return INVALID_SOCKET;

    int outcode = -1;

    n = recv(newsockfd, (char *)&outcode, sizeof(outcode), MSG_NOSIGNAL);
    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR reading output code: " << ERRNO << endl;
        return -1;
    }

    int BUFFERSIZE = 1024;
    char buffer[1025];
    do{
        n = recv(newsockfd, buffer, BUFFERSIZE, MSG_NOSIGNAL);
        if (n)
        {
            buffer[n]='\0';
            cout << buffer;
        }
    } while(n == BUFFERSIZE && n !=SOCKET_ERROR);

    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR reading output: " << ERRNO << endl;
        return -1;;
    }

    closeSocket(thesock);
    closeSocket(newsockfd);
#if _WIN32
    WSACleanup();
#endif
    return outcode;
}
<commit_msg>fixed megaclient for "sync"<commit_after>/**
 * @file examples/megacmd/client/megacmdclient.cpp
 * @brief MegaCMDClient: Client application of MEGAcmd
 *
 * (c) 2013-2016 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include <stdio.h>
#include <iostream>
#include <errno.h>
#include <string>
#include <vector>
#include <memory.h>
#include <limits.h>

#include <sys/types.h>
#ifdef _WIN32
#include <WinSock2.h>
#include <Shlwapi.h> //PathAppend
#else
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/un.h>
#endif
#define MEGACMDINITIALPORTNUMBER 12300

#ifdef _WIN32
#include <windows.h>
#define ERRNO WSAGetLastError()
#else
#define ERRNO errno
#endif

#ifndef SOCKET_ERROR
#define SOCKET_ERROR -1
#endif

#ifdef __MACH__
#define MSG_NOSIGNAL 0
#elif _WIN32
#define MSG_NOSIGNAL 0
#endif

bool socketValid(int socket)
{
#ifdef _WIN32
    return socket != INVALID_SOCKET;
#else
    return socket >= 0;
#endif
}

#ifndef INVALID_SOCKET
#define INVALID_SOCKET -1
#endif

void closeSocket(int socket){
#ifdef _WIN32
    closesocket(socket);
#else
    close(socket);
#endif
}

using namespace std;

#ifdef _WIN32
// convert UTF-8 to Windows Unicode
void path2local(string* path, string* local)
{
    // make space for the worst case
    local->resize((path->size() + 1) * sizeof(wchar_t));

    int len = MultiByteToWideChar(CP_UTF8, 0,
                                  path->c_str(),
                                  -1,
                                  (wchar_t*)local->data(),
                                  local->size() / sizeof(wchar_t) + 1);
    if (len)
    {
        // resize to actual result
        local->resize(sizeof(wchar_t) * (len - 1));
    }
    else
    {
        local->clear();
    }
}

// convert to Windows Unicode Utf8
void local2path(string* local, string* path)
{
    path->resize((local->size() + 1) * 4 / sizeof(wchar_t));

    path->resize(WideCharToMultiByte(CP_UTF8, 0, (wchar_t*)local->data(),
                                     local->size() / sizeof(wchar_t),
                                     (char*)path->data(),
                                     path->size() + 1,
                                     NULL, NULL));
    //normalize(path);
}
#endif
string getAbsPath(string relativePath)
{
    if (!relativePath.size())
    {
        return relativePath;
    }

#ifdef _WIN32
    string utf8absolutepath;
    string localpath;
    path2local(&relativePath, &localpath);

    string absolutelocalpath;
    localpath.append("", 1);

   if (!PathIsRelativeW((LPCWSTR)localpath.data()))
   {
       utf8absolutepath = relativePath;
       if (utf8absolutepath.find("\\\\?\\") != 0)
       {
           utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1);
       }
       return utf8absolutepath;
   }

   int len = GetFullPathNameW((LPCWSTR)localpath.data(), 0, NULL, NULL);
   if (len <= 0)
   {
      return relativePath;
   }

   absolutelocalpath.resize(len * sizeof(wchar_t)-1);
   int newlen = GetFullPathNameW((LPCWSTR)localpath.data(), len, (LPWSTR)absolutelocalpath.data(), NULL);
   if (newlen <= 0 || newlen >= len)
   {
       cerr << " failed to get CWD" << endl;
       return relativePath;
   }

   local2path(&absolutelocalpath, &utf8absolutepath);

   if (utf8absolutepath.find("\\\\?\\") != 0)
   {
       utf8absolutepath.insert(0, "\\\\?\\", sizeof("\\\\?\\")-1);
   }

   return utf8absolutepath;

#else
    if (relativePath.size() && relativePath.at(0) == '/')
    {
        return relativePath;
    }
    else
    {
        char cCurrentPath[PATH_MAX];
        if (!getcwd(cCurrentPath, sizeof(cCurrentPath)))
        {
            cerr << " failed to get CWD" << endl;
            return relativePath;
        }

        string absolutepath = cCurrentPath;
        absolutepath.append("/");
        absolutepath.append(relativePath);
        return absolutepath;
    }

    return relativePath;
#endif

}

string parseArgs(int argc, char* argv[])
{
    vector<string> absolutedargs;
    int itochange = -1;
    int totalRealArgs = 0;
    if (argc>1)
    {
        absolutedargs.push_back(argv[1]);

        if (!strcmp(argv[1],"sync"))
        {
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    totalRealArgs++;
                }
            }
            bool firstrealArg = true;
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    if (totalRealArgs >=2 && firstrealArg)
                    {
                        absolutedargs.push_back(getAbsPath(argv[i]));
                        firstrealArg=false;
                    }
                    else
                    {
                        absolutedargs.push_back(argv[i]);
                    }
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
        }
        else if (!strcmp(argv[1],"lcd")) //localpath args
        {
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    absolutedargs.push_back(getAbsPath(argv[i]));
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
        }
        else if (!strcmp(argv[1],"get") || !strcmp(argv[1],"preview") || !strcmp(argv[1],"thumbnail"))
        {
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] != '-' )
                {
                    totalRealArgs++;
                    if (totalRealArgs>1)
                    {
                        absolutedargs.push_back(getAbsPath(argv[i]));
                    }
                    else
                    {
                        absolutedargs.push_back(argv[i]);
                    }
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
            if (totalRealArgs == 1)
            {
                absolutedargs.push_back(getAbsPath("."));

            }
        }
        else if (!strcmp(argv[1],"put"))
        {
            int lastRealArg = 0;
            for (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-' )
                {
                    lastRealArg = i;
                }
            }
            bool firstRealArg = true;
            for  (int i = 2; i < argc; i++)
            {
                if (strlen(argv[i]) && argv[i][0] !='-')
                {
                    if (firstRealArg || i <lastRealArg)
                    {
                        absolutedargs.push_back(getAbsPath(argv[i]));
                        firstRealArg = false;
                    }
                    else
                    {
                        absolutedargs.push_back(argv[i]);
                    }
                }
                else
                {
                    absolutedargs.push_back(argv[i]);
                }
            }
        }
        else
        {
            for (int i = 2; i < argc; i++)
            {
                absolutedargs.push_back(argv[i]);
            }
        }
    }

    string toret="";
    for (u_int i=0; i < absolutedargs.size(); i++)
    {
        if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size())
        {
            toret += "\"";
        }
        toret+=absolutedargs.at(i);
        if (absolutedargs.at(i).find(" ") != string::npos || !absolutedargs.at(i).size())
        {
            toret += "\"";
        }

        if (i != (absolutedargs.size()-1))
        {
            toret += " ";
        }
    }

    return toret;
}

#ifdef _WIN32
int createSocket(int number = 0, bool net = true)
#else
int createSocket(int number = 0, bool net = false)
#endif
{
if (net)
{
    int thesock = socket(AF_INET, SOCK_STREAM, 0);
    if (!socketValid(thesock))
    {
        cerr << "ERROR opening socket: " << ERRNO << endl;
        return INVALID_SOCKET;
    }
    int portno=MEGACMDINITIALPORTNUMBER+number;

    struct sockaddr_in addr;

    memset(&addr, 0, sizeof( addr ));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
    addr.sin_port = htons(portno);

    if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR)
    {
        cerr << "Unable to connect to " << (number?("response socket N "+number):"service") << ": error=" << ERRNO << endl;
        if (!number)
        {
            cerr << "Please ensure MegaCMD is running" << endl;
        }
        return INVALID_SOCKET;
    }
    return thesock;
}

#ifndef _WIN32
else
{
    int thesock = socket(AF_UNIX, SOCK_STREAM, 0);
    char socket_path[60];
    if (!socketValid(thesock))
    {
        cerr << "ERROR opening socket: " << ERRNO << endl;
        return INVALID_SOCKET;
    }

    bzero(socket_path, sizeof( socket_path ) * sizeof( *socket_path ));
    if (number)
    {
        sprintf(socket_path, "/tmp/megaCMD_%d/srv_%d", getuid(), number);
    }
    else
    {
        sprintf(socket_path, "/tmp/megaCMD_%d/srv", getuid() );
    }

    struct sockaddr_un addr;

    memset(&addr, 0, sizeof( addr ));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_path, sizeof( addr.sun_path ) - 1);

    if (::connect(thesock, (struct sockaddr*)&addr, sizeof( addr )) == SOCKET_ERROR)
    {
        cerr << "Unable to connect to " << (number?("response socket N "+number):"service") << ": error=" << ERRNO << endl;
        if (!number)
        {
            cerr << "Please ensure MegaCMD is running" << endl;
        }
        return INVALID_SOCKET;
    }

    return thesock;
}
return INVALID_SOCKET;

#endif
}

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "Too few arguments" << endl;
        return -1;
    }
    string parsedArgs = parseArgs(argc,argv);

#if _WIN32
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        cerr << "ERROR initializing WSA" << endl;
    }
#endif

    int thesock = createSocket();
    if (thesock == INVALID_SOCKET)
    {
        return INVALID_SOCKET;
    }

    int n = send(thesock,parsedArgs.data(),parsedArgs.size(), MSG_NOSIGNAL);
    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR writing output Code to socket: " << ERRNO << endl;
        return -1;;
    }

    int receiveSocket = SOCKET_ERROR ;

    n = recv(thesock, (char *)&receiveSocket, sizeof(receiveSocket), MSG_NOSIGNAL);
    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR reading output socket" << endl;
        return -1;;
    }

    int newsockfd =createSocket(receiveSocket);
    if (newsockfd == INVALID_SOCKET)
        return INVALID_SOCKET;

    int outcode = -1;

    n = recv(newsockfd, (char *)&outcode, sizeof(outcode), MSG_NOSIGNAL);
    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR reading output code: " << ERRNO << endl;
        return -1;
    }

    int BUFFERSIZE = 1024;
    char buffer[1025];
    do{
        n = recv(newsockfd, buffer, BUFFERSIZE, MSG_NOSIGNAL);
        if (n)
        {
            buffer[n]='\0';
            cout << buffer;
        }
    } while(n == BUFFERSIZE && n !=SOCKET_ERROR);

    if (n == SOCKET_ERROR)
    {
        cerr << "ERROR reading output: " << ERRNO << endl;
        return -1;;
    }

    closeSocket(thesock);
    closeSocket(newsockfd);
#if _WIN32
    WSACleanup();
#endif
    return outcode;
}
<|endoftext|>


<commit_before>#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/gist.hh>
#include <gecode/search.hh>

#include "dep_selector_to_gecode.h"

#include <limits>
#include <iostream>
#include <vector>

#undef DEBUG

using namespace Gecode;
const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;

VersionProblem::VersionProblem(int packageCount)
  : finalized(false), cur_package(0), package_versions(*this, packageCount),
    disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount)
{
}

VersionProblem::VersionProblem(bool share, VersionProblem & s)
  : MinimizeSpace(share, s),
    finalized(s.finalized), cur_package(s.cur_package),
    disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled)
{
  package_versions.update(*this, share, s.package_versions);
  disabled_package_variables.update(*this, share, s.disabled_package_variables);
  total_disabled.update(*this, share, s.total_disabled);
}

// Support for gecode
Space* VersionProblem::copy(bool share)
{
  return new VersionProblem(share,*this);
}

VersionProblem::~VersionProblem()
{

}

int VersionProblem::Size()
{
  return package_versions.size();
}

int VersionProblem::PackageCount()
{
  return cur_package;
}

int
VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion)
{
  if (cur_package == package_versions.size()) {
    return -1;
  }

#ifdef DEBUG
  std::cout << cur_package << '/' << package_versions.size() << ":" << minVersion << ", " << maxVersion << ", " << currentVersion << std::endl;
  std::cout.flush();
#endif // DEBUG
  int index = cur_package;
  cur_package++;
  //  IntVar version(*this, minVersion, maxVersion);
  package_versions[index] = IntVar(*this, minVersion, maxVersion);
  return index;
}

bool
VersionProblem::AddVersionConstraint(int packageId, int version,
							int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
  BoolVar version_match(*this, 0, 1);
  BoolVar depend_match(*this, 0, 1);
  BoolVar predicated_depend_match(*this, 0, 1);

  //version_flags << version_match;
  // Constrain pred to reify package @ version
  rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
  // Add the predicated version constraints imposed on dependent package
  dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);

  // disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match
  rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);

  rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}

void VersionProblem::Finalize()
{
#ifdef DEBUG
  std::cout << "Finalization Started" << std::endl;
  std::cout.flush();
#endif // DEBUG
  finalized = true;
  // Setup constraint for cost
  linear(*this, disabled_package_variables, IRT_EQ, total_disabled);

  // Assign a dummy variable to elements greater than actually used.
  for (int i = cur_package; i < package_versions.size(); i++) {
    package_versions[i] = IntVar(*this, -1, -1);
    disabled_package_variables[i] = BoolVar(*this, 1, 1);
  }
#ifdef DEBUG
  std::cout << "Branch Started" << std::endl;
  std::cout.flush();
#endif // DEBUG
  branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
  branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
#ifdef DEBUG
  std::cout << "Finalization Done" << std::endl;
  std::cout.flush();
#endif // DEBUG
}

IntVar VersionProblem::cost(void) const {
  return total_disabled;
}

IntVar & VersionProblem::GetPackageVersionVar(int packageId)
{
  if (packageId < cur_package) {
    return package_versions[packageId];
  } else {
#ifdef DEBUG
    std::cout << "Bad package Id " << packageId << " >= " << cur_package << std::endl;
    std::cout.flush();
#endif //DEBUG
    //    return 0;
  }
}

int VersionProblem::GetPackageVersion(int packageId)
{
  IntVar & var = GetPackageVersionVar(packageId);
  if (1 == var.size()) return var.val();
  return UNRESOLVED_VARIABLE;
}
bool VersionProblem::GetPackageDisabledState(int packageId)
{
  return disabled_package_variables[packageId].val() == 1;
}

int VersionProblem::GetAFC(int packageId)
{
  return GetPackageVersionVar(packageId).afc();
}

int VersionProblem::GetMax(int packageId)
{
  return GetPackageVersionVar(packageId).max();
}
int VersionProblem::GetMin(int packageId)
{
  return GetPackageVersionVar(packageId).min();
}

int VersionProblem::GetDisabledVariableCount()
{
  if (total_disabled.min() == total_disabled.max()) {
    return total_disabled.min();
  } else {
    return UNRESOLVED_VARIABLE;
  }
}

// Utility
void VersionProblem::Print(std::ostream & out)
{
  out << "Version problem dump: " << cur_package << "/" << package_versions.size() << " packages used/allocated" << std::endl;
  for (int i = 0; i < cur_package; i++) {
    out << "\t";
    PrintPackageVar(out, i);
    out << std::endl;
  }
  out.flush();
}

// TODO: Validate package ids !

void VersionProblem::PrintPackageVar(std::ostream & out, int packageId)
{
  // Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.
  IntVar & var = GetPackageVersionVar(packageId);
  out << "PackageId: " << packageId <<  " Sltn: " << var.min() << " - " << var.max() << " afc: " << var.afc();

  out << " disabled: ";
  if (disabled_package_variables[packageId].min() == disabled_package_variables[packageId].max()) {
    out << disabled_package_variables[packageId].min();
  } else {
    out << disabled_package_variables[packageId].min() << " - " << disabled_package_variables[packageId].max();
  }
}

bool VersionProblem::CheckPackageId(int id)
{
  return (id < package_versions.size());
}

VersionProblem * VersionProblem::Solve(VersionProblem * problem)
{
  problem->Finalize();
  problem->status();
#ifdef DEBUG
  problem->Print(std::cout);
#endif //DEBUG
  Restart<VersionProblem> solver(problem);

  // std::cout << solver.statistics();

  if (VersionProblem * solution = solver.next())
    {
      return solution;
    }
  return 0;
}

//
//
//

//
// Version Problem
//
//
//
//
<commit_msg>Add a little more detail to the dump routine<commit_after>#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/gist.hh>
#include <gecode/search.hh>

#include "dep_selector_to_gecode.h"

#include <limits>
#include <iostream>
#include <vector>

#undef DEBUG

using namespace Gecode;
const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;

VersionProblem::VersionProblem(int packageCount)
  : finalized(false), cur_package(0), package_versions(*this, packageCount),
    disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount)
{
}

VersionProblem::VersionProblem(bool share, VersionProblem & s)
  : MinimizeSpace(share, s),
    finalized(s.finalized), cur_package(s.cur_package),
    disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled)
{
  package_versions.update(*this, share, s.package_versions);
  disabled_package_variables.update(*this, share, s.disabled_package_variables);
  total_disabled.update(*this, share, s.total_disabled);
}

// Support for gecode
Space* VersionProblem::copy(bool share)
{
  return new VersionProblem(share,*this);
}

VersionProblem::~VersionProblem()
{

}

int VersionProblem::Size()
{
  return package_versions.size();
}

int VersionProblem::PackageCount()
{
  return cur_package;
}

int
VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion)
{
  if (cur_package == package_versions.size()) {
    return -1;
  }

#ifdef DEBUG
  std::cout << cur_package << '/' << package_versions.size() << ":" << minVersion << ", " << maxVersion << ", " << currentVersion << std::endl;
  std::cout.flush();
#endif // DEBUG
  int index = cur_package;
  cur_package++;
  //  IntVar version(*this, minVersion, maxVersion);
  package_versions[index] = IntVar(*this, minVersion, maxVersion);
  return index;
}

bool
VersionProblem::AddVersionConstraint(int packageId, int version,
							int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
  BoolVar version_match(*this, 0, 1);
  BoolVar depend_match(*this, 0, 1);
  BoolVar predicated_depend_match(*this, 0, 1);

  //version_flags << version_match;
  // Constrain pred to reify package @ version
  rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
  // Add the predicated version constraints imposed on dependent package
  dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);

  // disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match
  rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);

  rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}

void VersionProblem::Finalize()
{
#ifdef DEBUG
  std::cout << "Finalization Started" << std::endl;
  std::cout.flush();
#endif // DEBUG
  finalized = true;
  // Setup constraint for cost
  linear(*this, disabled_package_variables, IRT_EQ, total_disabled);

  // Assign a dummy variable to elements greater than actually used.
  for (int i = cur_package; i < package_versions.size(); i++) {
    package_versions[i] = IntVar(*this, -1, -1);
    disabled_package_variables[i] = BoolVar(*this, 1, 1);
  }
#ifdef DEBUG
  std::cout << "Branch Started" << std::endl;
  std::cout.flush();
#endif // DEBUG
  branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
  branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
#ifdef DEBUG
  std::cout << "Finalization Done" << std::endl;
  std::cout.flush();
#endif // DEBUG
}

IntVar VersionProblem::cost(void) const {
  return total_disabled;
}

IntVar & VersionProblem::GetPackageVersionVar(int packageId)
{
  if (packageId < cur_package) {
    return package_versions[packageId];
  } else {
#ifdef DEBUG
    std::cout << "Bad package Id " << packageId << " >= " << cur_package << std::endl;
    std::cout.flush();
#endif //DEBUG
    //    return 0;
  }
}

int VersionProblem::GetPackageVersion(int packageId)
{
  IntVar & var = GetPackageVersionVar(packageId);
  if (1 == var.size()) return var.val();
  return UNRESOLVED_VARIABLE;
}
bool VersionProblem::GetPackageDisabledState(int packageId)
{
  return disabled_package_variables[packageId].val() == 1;
}

int VersionProblem::GetAFC(int packageId)
{
  return GetPackageVersionVar(packageId).afc();
}

int VersionProblem::GetMax(int packageId)
{
  return GetPackageVersionVar(packageId).max();
}
int VersionProblem::GetMin(int packageId)
{
  return GetPackageVersionVar(packageId).min();
}

int VersionProblem::GetDisabledVariableCount()
{
  if (total_disabled.min() == total_disabled.max()) {
    return total_disabled.min();
  } else {
    return UNRESOLVED_VARIABLE;
  }
}

// Utility
void VersionProblem::Print(std::ostream & out)
{
  out << "Version problem dump: " << cur_package << "/" << package_versions.size() << " packages used/allocated" << std::endl;
  out << "Total Disabled variables: " << total_disabled.min() << " - " << total_disabled.max() << std::endl;
  for (int i = 0; i < cur_package; i++) {
    out << "\t";
    PrintPackageVar(out, i);
    out << std::endl;
  }
  out.flush();
}

// TODO: Validate package ids !

void VersionProblem::PrintPackageVar(std::ostream & out, int packageId)
{
  // Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.
  IntVar & var = GetPackageVersionVar(packageId);
  out << "PackageId: " << packageId <<  " Sltn: " << var.min() << " - " << var.max() << " afc: " << var.afc();

  out << " disabled: ";
  if (disabled_package_variables[packageId].min() == disabled_package_variables[packageId].max()) {
    out << disabled_package_variables[packageId].min();
  } else {
    out << disabled_package_variables[packageId].min() << " - " << disabled_package_variables[packageId].max();
  }
}

bool VersionProblem::CheckPackageId(int id)
{
  return (id < package_versions.size());
}

VersionProblem * VersionProblem::Solve(VersionProblem * problem)
{
  problem->Finalize();
  problem->status();
#ifdef DEBUG
  problem->Print(std::cout);
#endif //DEBUG
  Restart<VersionProblem> solver(problem);

  // std::cout << solver.statistics();

  if (VersionProblem * solution = solver.next())
    {
      return solution;
    }
  return 0;
}

//
//
//

//
// Version Problem
//
//
//
//
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// discrete time simulation clock for SteerTest
//
// Keeps track of real clock time and simulation time.  Encapsulates OS's
// time API.  Can be put in either "as fast as possible" variable time step
// mode (where simulation time steps are based on real time elapsed between
// updates), or in fixed "target FPS" mode where the simulation steps are
// constrained to start on 1/FPS boundaries (e.g. on a 60 hertz video game
// console).  Also handles the notion of "pausing" simulation time.
//
// Usage: allocate a clock, set its "paused" or "targetFPS" parameters,
// then call updateGlobalSimulationClock before each simulation step.
//
// 10-04-03 dp:  made members private; added accessors, removed frameRateSync
// 09-24-02 cwr: major overhaul
// 06-26-02 cwr: created
//
//
// ----------------------------------------------------------------------------

#include "Clock.h"

// ----------------------------------------------------------------------------
// XXX This is a bit ad hoc.  Need to revisit conditionalization on operating
// XXX system.  As of 5-5-03, this module knows about Win32 (code thanks to
// XXX Leaf Garland and Bruce Mitchener) and Linux/Unix (Craig's original
// XXX version).  It tests for Win32 and assumes Linux/Unix otherwise.

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

// ----------------------------------------------------------------------------
// Constructor

Clock::Clock (void)
{
    // is simulation running or paused?
    paused = false;

    // real "wall clock" time since launch
    totalRealTime = 0;

    // time simulation has run
    totalSimulationTime = 0;

    // time spent paused
    totalPausedTime = 0;

    // sum of (non-realtime driven) advances to simulation time
    totalAdvanceTime = 0;

    // interval since last simulation time
    elapsedSimulationTime = 0;

    // interval since last clock update time
    elapsedRealTime = 0;

    // interval since last clock update,
    // exclusive of time spent waiting for frame boundary when targetFPS>0
    elapsedNonWaitRealTime = 0;

    // "manually" advance clock by this amount on next update
    newAdvanceTime = 0;

    // "Calendar time" in seconds and microseconds (obtained from
    // the OS by gettimeofday) when this clock was first updated
    baseRealTimeSec = 0;
    baseRealTimeUsec = 0;
}

// ----------------------------------------------------------------------------
// update this clock, called once per simulation step ("frame")

void Clock::Update (void)
{
	// save previous real time to measure elapsed time
    const TimeVal previousRealTime = totalRealTime;

    // real "wall clock" time since this application was launched
    totalRealTime = RealTimeSinceFirstClockUpdate ();

    // time since last clock update
    elapsedRealTime = totalRealTime - previousRealTime;

    // accumulate paused time
	if (paused) {
		totalPausedTime += elapsedRealTime;
	}

    // save previous simulation time to measure elapsed time
    const TimeVal previousSimulationTime = totalSimulationTime;

    // update total "manual advance" time
    totalAdvanceTime += newAdvanceTime;

    // new simulation time is total run time minus time spent paused
    totalSimulationTime = (totalRealTime
                           + totalAdvanceTime
                           - totalPausedTime);

    // how much time has elapsed since the last simulation step?
    elapsedSimulationTime = (paused ?
                             newAdvanceTime :
                             (totalSimulationTime - previousSimulationTime));

    // reset advance amount
    newAdvanceTime = 0;
}

// ----------------------------------------------------------------------------
// ("manually") force simulation time ahead, unrelated to the passage of
// real time, currently used only for SteerTest's "single step forward"

void Clock::AdvanceSimulationTime (const TimeVal seconds)
{
	if (seconds > 0) {
		newAdvanceTime += seconds;
	}
}

// ----------------------------------------------------------------------------
// Returns the number of seconds of real time (represented as a float) since
// the clock was first updated.
//
// XXX Need to revisit conditionalization on operating system.
//
// XXX as of 5-5-03: two versions, one for Linux/Unix (by Craig Reynolds) and
// XXX one for Windows (by Leaf Garland).  As Leaf's comment suggests, the
// XXX original version of this function mirrored the Linux/Unix clock model.
// XXX This should be redesigned to be more agnostic to operating system.

// original version:
//
// float Clock::realTimeSinceFirstClockUpdate (void)
// {
//     timeval t;
//     if (gettimeofday (&t, 0) != 0)
//     {
//         SteerTest::errorExit ("Problem reading system clock.\n");
//         return (0);  // won't be reached, but prevents compiler warning
//     }
//     else
//     {
//         // ensure the base time is recorded once after launch
//         if (baseRealTimeSec == 0)
//         {
//             baseRealTimeSec = t.tv_sec;
//             baseRealTimeUsec = t.tv_usec;
//         }

//         // real "wall clock" time since launch
//         return (( t.tv_sec  - baseRealTimeSec) +
//                 ((t.tv_usec - baseRealTimeUsec) / 1000000.0f));
//     }
// }

void clockErrorExit (void)
{
	/// @todo - deal with error here
}

TimeVal Clock::RealTimeSinceFirstClockUpdate ()
#ifdef _WIN32
{
    LONGLONG time, freq;
    if (QueryPerformanceCounter((LARGE_INTEGER *)&time))
    {
        if (QueryPerformanceFrequency((LARGE_INTEGER *)&freq))
        {
            // This is complicated by trying to stick with the original
            // method of storing time as two integers instead of a float.
			totalRealTime = (double)time / (double)freq;
/*            int sec = (int)dtime;
            int usec = (int) ((dtime - sec) * 1000000);

            if (baseRealTimeSec == 0)
            {
                baseRealTimeSec = sec;
                baseRealTimeUsec = usec;
            }
            // real "wall clock" time since launch
            return (( sec  - baseRealTimeSec) +
                    ((usec - baseRealTimeUsec) / 1000000.0f));*/
			return totalRealTime;
        }
        clockErrorExit ();
        return 0.0f;
    }
    clockErrorExit ();
    return 0.0f;
}
#else
{
    timeval t;
    if (gettimeofday (&t, 0) != 0)
    {
        clockErrorExit ();
        return (0);  // won't be reached, but avoids compiler warning
    }
    else
    {
        // ensure the base time is recorded once after launch
        if (baseRealTimeSec == 0)
        {
            baseRealTimeSec = t.tv_sec;
            baseRealTimeUsec = t.tv_usec;
        }

        // real "wall clock" time since launch
        return (( t.tv_sec  - baseRealTimeSec) +
                ((t.tv_usec - baseRealTimeUsec) / 1000000.0f));
    }
}
#endif

// ----------------------------------------------------------------------------
<commit_msg>added<commit_after>// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// discrete time simulation clock for SteerTest
//
// Keeps track of real clock time and simulation time.  Encapsulates OS's
// time API.  Can be put in either "as fast as possible" variable time step
// mode (where simulation time steps are based on real time elapsed between
// updates), or in fixed "target FPS" mode where the simulation steps are
// constrained to start on 1/FPS boundaries (e.g. on a 60 hertz video game
// console).  Also handles the notion of "pausing" simulation time.
//
// Usage: allocate a clock, set its "paused" or "targetFPS" parameters,
// then call updateGlobalSimulationClock before each simulation step.
//
// 10-04-03 dp:  made members private; added accessors, removed frameRateSync
// 09-24-02 cwr: major overhaul
// 06-26-02 cwr: created
//
//
// ----------------------------------------------------------------------------

#include "Clock.h"

// ----------------------------------------------------------------------------
// XXX This is a bit ad hoc.  Need to revisit conditionalization on operating
// XXX system.  As of 5-5-03, this module knows about Win32 (code thanks to
// XXX Leaf Garland and Bruce Mitchener) and Linux/Unix (Craig's original
// XXX version).  It tests for Win32 and assumes Linux/Unix otherwise.

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

// ----------------------------------------------------------------------------
// Constructor

Clock::Clock (void)
{
    // is simulation running or paused?
    paused = false;

    // real "wall clock" time since launch
    totalRealTime = 0;

    // time simulation has run
    totalSimulationTime = 0;

    // time spent paused
    totalPausedTime = 0;

    // sum of (non-realtime driven) advances to simulation time
    totalAdvanceTime = 0;

    // interval since last simulation time
    elapsedSimulationTime = 0;

    // interval since last clock update time
    elapsedRealTime = 0;

    // interval since last clock update,
    // exclusive of time spent waiting for frame boundary when targetFPS>0
    elapsedNonWaitRealTime = 0;

    // "manually" advance clock by this amount on next update
    newAdvanceTime = 0;

    // "Calendar time" in seconds and microseconds (obtained from
    // the OS by gettimeofday) when this clock was first updated
    baseRealTimeSec = 0;
    baseRealTimeUsec = 0;
}

// ----------------------------------------------------------------------------
// update this clock, called once per simulation step ("frame")

void Clock::Update (void)
{
	// save previous real time to measure elapsed time
    const TimeVal previousRealTime = totalRealTime;

    // real "wall clock" time since this application was launched
    totalRealTime = RealTimeSinceFirstClockUpdate ();

    // time since last clock update
    elapsedRealTime = totalRealTime - previousRealTime;

    // accumulate paused time
	if (paused) {
		totalPausedTime += elapsedRealTime;
	}

    // save previous simulation time to measure elapsed time
    const TimeVal previousSimulationTime = totalSimulationTime;

    // update total "manual advance" time
    totalAdvanceTime += newAdvanceTime;

    // new simulation time is total run time minus time spent paused
    totalSimulationTime = (totalRealTime
                           + totalAdvanceTime
                           - totalPausedTime);

    // how much time has elapsed since the last simulation step?
    elapsedSimulationTime = (paused ?
                             newAdvanceTime :
                             (totalSimulationTime - previousSimulationTime));

    // reset advance amount
    newAdvanceTime = 0;
}

// ----------------------------------------------------------------------------
// ("manually") force simulation time ahead, unrelated to the passage of
// real time, currently used only for SteerTest's "single step forward"

void Clock::AdvanceSimulationTime (const TimeVal seconds)
{
	if (seconds > 0) {
		newAdvanceTime += seconds;
	}
}

// ----------------------------------------------------------------------------
// Returns the number of seconds of real time (represented as a float) since
// the clock was first updated.
//
// XXX Need to revisit conditionalization on operating system.
//
// XXX as of 5-5-03: two versions, one for Linux/Unix (by Craig Reynolds) and
// XXX one for Windows (by Leaf Garland).  As Leaf's comment suggests, the
// XXX original version of this function mirrored the Linux/Unix clock model.
// XXX This should be redesigned to be more agnostic to operating system.

// original version:
//
// float Clock::realTimeSinceFirstClockUpdate (void)
// {
//     timeval t;
//     if (gettimeofday (&t, 0) != 0)
//     {
//         SteerTest::errorExit ("Problem reading system clock.\n");
//         return (0);  // won't be reached, but prevents compiler warning
//     }
//     else
//     {
//         // ensure the base time is recorded once after launch
//         if (baseRealTimeSec == 0)
//         {
//             baseRealTimeSec = t.tv_sec;
//             baseRealTimeUsec = t.tv_usec;
//         }

//         // real "wall clock" time since launch
//         return (( t.tv_sec  - baseRealTimeSec) +
//                 ((t.tv_usec - baseRealTimeUsec) / 1000000.0f));
//     }
// }

void clockErrorExit (void)
{
	/// @todo - deal with error here
}

TimeVal Clock::RealTimeSinceFirstClockUpdate ()
#ifdef _WIN32
{
    LONGLONG time, freq;
    if (QueryPerformanceCounter((LARGE_INTEGER *)&time))
    {
        if (QueryPerformanceFrequency((LARGE_INTEGER *)&freq))
        {
			totalRealTime = (double)time / (double)freq;
			return totalRealTime;

			/*
            // This is complicated by trying to stick with the original
            // method of storing time as two integers instead of a float.
            int sec = (int)dtime;
            int usec = (int) ((dtime - sec) * 1000000);

            if (baseRealTimeSec == 0)
            {
                baseRealTimeSec = sec;
                baseRealTimeUsec = usec;
            }
            // real "wall clock" time since launch
            return (( sec  - baseRealTimeSec) +
                    ((usec - baseRealTimeUsec) / 1000000.0f));*/
        }
        clockErrorExit ();
        return 0.0f;
    }
    clockErrorExit ();
    return 0.0f;
}
#else
{
    timeval t;
    if (gettimeofday (&t, 0) != 0)
    {
        clockErrorExit ();
        return (0);  // won't be reached, but avoids compiler warning
    }
    else
    {
        // ensure the base time is recorded once after launch
        if (baseRealTimeSec == 0)
        {
            baseRealTimeSec = t.tv_sec;
            baseRealTimeUsec = t.tv_usec;
        }

        // real "wall clock" time since launch
        return (( t.tv_sec  - baseRealTimeSec) +
                ((t.tv_usec - baseRealTimeUsec) / 1000000.0f));
    }
}
#endif

// ----------------------------------------------------------------------------
<|endoftext|>


<commit_before>#ifndef VANORDER_DSTO_HPP
#define VANORDER_DSTO_HPP

#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

#include "sto_utils.hpp"

namespace vanorder
{

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed
                            , NumType
             >::type
    constexpr
    sto( char const * begin, char const * const end )
    {
        static_assert( std::numeric_limits< NumType >::is_specialized,
                       "Can work only with specialized numbers." );

        static_assert( std::numeric_limits< NumType >::min()
                       == -std::numeric_limits< NumType >::max() - 1,
                       "We relay on ususal integer representation where min = -max - 1"
                       // int8_t -> [-128; 127]
                       // int16_t -> [-32768; 32767]
                       // And so on.
                       );

        typename std::remove_cv<NumType>::type result = 0;

        if( begin == end )
        {
            throw std::length_error( utils::sto_func_name(result) );
        }

        bool const is_neg = (*begin == '-');
        begin += is_neg;

        if( begin == end )
        {
            throw std::invalid_argument( utils::sto_func_name(result) );
        }

        for( ; begin != end ; ++begin )
        {
            signed c = *begin;
            if( std::isdigit( c ) )
            {
                c -= '0';
            }
            else
            {
                throw std::invalid_argument( utils::sto_func_name(result) );
            }

            constexpr NumType cutoff =    std::numeric_limits< NumType >::min() / 10;
            constexpr NumType cutlim = -( std::numeric_limits< NumType >::min() % 10 );

            if( result < cutoff or ( result == cutoff and c > cutlim ) )
            {
                if( is_neg )
                {
                    throw std::underflow_error( utils::sto_func_name(result) );
                }
                else
                {
                    throw std::overflow_error( utils::sto_func_name(result) );
                }
            }
            result *= 10;
            result -= c;
        }

        if( not is_neg )
        {
            if( result == std::numeric_limits<NumType>::min() )
            {
                throw std::overflow_error( utils::sto_func_name(result) );
            }
            result = -result;
        }

        return result;
    }

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return sto< NumType >( &str[0], &str[ str.size() ] );
    }

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed == false
                            , NumType
             >::type
    constexpr
    sto( char const * begin, char const * const end )
    {
        static_assert( std::numeric_limits< NumType >::is_specialized,
                       "Can work only with specialized numbers." );

        typename std::remove_cv<NumType>::type result = 0;

        if( begin == end )
        {
            throw std::length_error( utils::sto_func_name(result) );
        }
        else if( *begin == '-' )
        {
            throw std::domain_error( utils::sto_func_name(result) );
        }

        for( ; begin != end; ++begin )
        {
            signed c = *begin;
            if( std::isdigit( c ) )
            {
                c -= '0';
            }
            else
            {
                throw std::invalid_argument( utils::sto_func_name(result) );
            }

            constexpr NumType cutoff = std::numeric_limits< NumType >::max() / 10;
            constexpr NumType cutlim = std::numeric_limits< NumType >::max() % 10;

            if( result > cutoff or ( result == cutoff and c > cutlim ) )
            {
                throw std::overflow_error( utils::sto_func_name(result) );
            }
            result *= 10;
            result += c;
        }

        return result;
    }

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed == false
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return sto< NumType >( &str[0], &str[ str.size() ] );
    }

    template< class NumType >
    typename std::enable_if<
                            std::is_same<
                                         float
                                         , typename std::remove_cv< NumType >::type
                            >::value
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return std::stof( str );
    }

    template< class NumType >
    typename std::enable_if<
                            std::is_same<
                                         double
                                         , typename std::remove_cv< NumType >::type
                            >::value
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return std::stod( str );
    }

    template< class NumType >
    typename std::enable_if<
                            std::is_same<
                                         long double
                                         , typename std::remove_cv< NumType >::type
                            >::value
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return std::stold( str );
    }

} // namespace vanorder

#endif // VANORDER_DSTO_HPP
<commit_msg>Speedup parsing of int32_t by 29% and int64_t by 51%.<commit_after>#ifndef VANORDER_DSTO_HPP
#define VANORDER_DSTO_HPP

#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

#include "sto_utils.hpp"

namespace vanorder
{

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed
                            , NumType
             >::type
    constexpr
    sto( char const * begin, char const * const end )
    {
        static_assert( std::numeric_limits< NumType >::is_specialized,
                       "Can work only with specialized numbers." );

        static_assert( std::numeric_limits< NumType >::min()
                       == -std::numeric_limits< NumType >::max() - 1,
                       "We relay on ususal integer representation where min = -max - 1"
                       // int8_t -> [-128; 127]
                       // int16_t -> [-32768; 32767]
                       // And so on.
                       );

        typename std::remove_cv<NumType>::type result = 0;

        if( begin == end )
        {
            throw std::length_error( utils::sto_func_name(result) );
        }

        bool const is_neg = (*begin == '-');
        begin += is_neg;

        if( begin == end )
        {
            throw std::invalid_argument( utils::sto_func_name(result) );
        }

        for( ; begin != end ; ++begin )
        {
            signed c = *begin;
            if( std::isdigit( c ) )
            {
                c -= '0';
            }
            else
            {
                throw std::invalid_argument( utils::sto_func_name(result) );
            }

            constexpr NumType cutoff =    std::numeric_limits< NumType >::min() / 10;
            constexpr NumType cutlim = -( std::numeric_limits< NumType >::min() % 10 );

            if( result < cutoff or ( result == cutoff and c > ( cutlim - !is_neg ) ) )
            {
                if( is_neg )
                {
                    throw std::underflow_error( utils::sto_func_name(result) );
                }
                else
                {
                    throw std::overflow_error( utils::sto_func_name(result) );
                }
            }
            result *= 10;
            result -= c;
        }

        if( not is_neg )
        {
            result = -result;
        }

        return result;
    }

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return sto< NumType >( &str[0], &str[ str.size() ] );
    }

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed == false
                            , NumType
             >::type
    constexpr
    sto( char const * begin, char const * const end )
    {
        static_assert( std::numeric_limits< NumType >::is_specialized,
                       "Can work only with specialized numbers." );

        typename std::remove_cv<NumType>::type result = 0;

        if( begin == end )
        {
            throw std::length_error( utils::sto_func_name(result) );
        }
        else if( *begin == '-' )
        {
            throw std::domain_error( utils::sto_func_name(result) );
        }

        for( ; begin != end; ++begin )
        {
            signed c = *begin;
            if( std::isdigit( c ) )
            {
                c -= '0';
            }
            else
            {
                throw std::invalid_argument( utils::sto_func_name(result) );
            }

            constexpr NumType cutoff = std::numeric_limits< NumType >::max() / 10;
            constexpr NumType cutlim = std::numeric_limits< NumType >::max() % 10;

            if( result > cutoff or ( result == cutoff and c > cutlim ) )
            {
                throw std::overflow_error( utils::sto_func_name(result) );
            }
            result *= 10;
            result += c;
        }

        return result;
    }

    template< class NumType >
    typename std::enable_if<
                            std::numeric_limits< NumType >::is_integer
                            and std::numeric_limits< NumType >::is_signed == false
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return sto< NumType >( &str[0], &str[ str.size() ] );
    }

    template< class NumType >
    typename std::enable_if<
                            std::is_same<
                                         float
                                         , typename std::remove_cv< NumType >::type
                            >::value
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return std::stof( str );
    }

    template< class NumType >
    typename std::enable_if<
                            std::is_same<
                                         double
                                         , typename std::remove_cv< NumType >::type
                            >::value
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return std::stod( str );
    }

    template< class NumType >
    typename std::enable_if<
                            std::is_same<
                                         long double
                                         , typename std::remove_cv< NumType >::type
                            >::value
                            , NumType
             >::type
    sto( const std::string & str )
    {
        return std::stold( str );
    }

} // namespace vanorder

#endif // VANORDER_DSTO_HPP
<|endoftext|>


<commit_before>
#include <fstream>
#include <iostream>

using namespace std;

template <class T>
class Tree
{
private:
	struct Node

	{
		friend class B_tree;

		T value_;
		Node *left;
		Node *right;
		Node() {};
		Node(const T value) : value_(value) { }
		~Node() {}
		void show(ostream &out, const int level = 0) const;
	};

	Node *tree, *null_tr;
	void null_tree(Node *tr_)
	{
		if (!tr_) return;
		if (tr_->left)
		{
			null_tree(tr_->left);
			tr_->left = nullptr;
		}
		if (tr_->right)
		{
			null_tree(tr_->right);
			tr_->right = nullptr;
		}
		delete tr_;
	}
	Node * & find_(const T value)
	{

		Node *tr = tree;
		while ((tr) && (tr->value_ != value))
		{
			if (value < tr->value_)
				tr = tr->left;
			else tr = tr->right;
		}
		if (!tr) return null_tr;
		else return tr;
	}
	void add_node(Node *&add_n, T value)
	{
		add_n = new Node(value);
		add_n->left = nullptr;
		add_n->right = nullptr;

	}
	Node* add_(const T value, Node * tr = 0)
	{
		if (!tree)
		{
			tree = new Node(value);
			tree->left = nullptr;
			tree->right = nullptr;
			return tree;
		}
		if (!tr) tr = tree;
		if ((tr) && (tr->value_ != value))

		{
			if (value < tr->value_)

			{
				if (tr->left)
					add_(value, tr->left);
				else
				{
					add_node(tr->left, value);
					return tr->left;
				}
			}

			else
			{
				if (tr->right)
					add_(value, tr->right);
				else
				{
					add_node(tr->right, value);
					return tr->right;
				}
			}
		}
		return 0;
	}
public:
	Tree()
	{
		tree = NULL;
		null_tr = nullptr;
	};

	void file_tree(char* name);
	bool add(const T value);
	bool find(const T value);
	void print(ostream &out) const;
	~Tree()
	{
		null_tree(tree);
		null_tree(null_tr);
	};
};
<commit_msg>Update tree.hpp<commit_after>
#include <fstream>
#include <iostream>

using namespace std;

template <class T>
class Tree
{
private:
	struct Node

	{
		friend class B_tree;

		T value_;
		Node *left;
		Node *right;
		Node() {};
		Node(const T value) : value_(value) { }
		~Node() {}
		void show(ostream &out, const int level) const;
	};

	Node *tree, *null_tr;
	void null_tree(Node *tr_)
	{
		if (!tr_) return;
		if (tr_->left)
		{
			null_tree(tr_->left);
			tr_->left = nullptr;
		}
		if (tr_->right)
		{
			null_tree(tr_->right);
			tr_->right = nullptr;
		}
		delete tr_;
	}
	Node * & find_(const T value)
	{

		Node *tr = tree;
		while ((tr) && (tr->value_ != value))
		{
			if (value < tr->value_)
				tr = tr->left;
			else tr = tr->right;
		}
		if (!tr) return null_tr;
		else return tr;
	}
	void add_node(Node *&add_n, T value)
	{
		add_n = new Node(value);
		add_n->left = nullptr;
		add_n->right = nullptr;

	}
	Node* add_(const T value, Node * tr = 0)
	{
		if (!tree)
		{
			tree = new Node(value);
			tree->left = nullptr;
			tree->right = nullptr;
			return tree;
		}
		if (!tr) tr = tree;
		if ((tr) && (tr->value_ != value))

		{
			if (value < tr->value_)

			{
				if (tr->left)
					add_(value, tr->left);
				else
				{
					add_node(tr->left, value);
					return tr->left;
				}
			}

			else
			{
				if (tr->right)
					add_(value, tr->right);
				else
				{
					add_node(tr->right, value);
					return tr->right;
				}
			}
		}
		return 0;
	}
public:
	Tree()
	{
		tree = NULL;
		null_tr = nullptr;
	};

	void file_tree(char* name);
	bool add(const T value);
	bool find(const T value);
	void print(ostream &out) const;
	~Tree()
	{
		null_tree(tree);
		null_tree(null_tr);
	};
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TransGradientStyle.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:43:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_TRANSGRADIENTSTYLE_HXX
#define _XMLOFF_TRANSGRADIENTSTYLE_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

class SvXMLImport;
class SvXMLExport;
namespace com { namespace sun { namespace star {
    namespace uno { template<class A> class Reference; }
    namespace xml { namespace sax { class XAttributeList; } }
    namespace uno { class Any; }
} } }
namespace rtl { class OUString; }

class XMLTransGradientStyleImport
{
    SvXMLImport& rImport;

public:
    XMLTransGradientStyleImport( SvXMLImport& rImport );
    ~XMLTransGradientStyleImport();

    sal_Bool importXML(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList >& xAttrList,
        ::com::sun::star::uno::Any& rValue,
        ::rtl::OUString& rStrName );
};

class XMLTransGradientStyleExport
{
    SvXMLExport& rExport;

public:
    XMLTransGradientStyleExport( SvXMLExport& rExport );
    ~XMLTransGradientStyleExport();

    sal_Bool exportXML( const ::rtl::OUString& rStrName, const ::com::sun::star::uno::Any& rValue );
};

#endif // _XMLOFF_TRANSGRADIENTSTYLE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.450); FILE MERGED 2008/04/01 16:09:07 thb 1.4.450.2: #i85898# Stripping all external header guards 2008/03/31 16:27:52 rt 1.4.450.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: TransGradientStyle.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLOFF_TRANSGRADIENTSTYLE_HXX
#define _XMLOFF_TRANSGRADIENTSTYLE_HXX

#include <sal/types.h>

class SvXMLImport;
class SvXMLExport;
namespace com { namespace sun { namespace star {
    namespace uno { template<class A> class Reference; }
    namespace xml { namespace sax { class XAttributeList; } }
    namespace uno { class Any; }
} } }
namespace rtl { class OUString; }

class XMLTransGradientStyleImport
{
    SvXMLImport& rImport;

public:
    XMLTransGradientStyleImport( SvXMLImport& rImport );
    ~XMLTransGradientStyleImport();

    sal_Bool importXML(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList >& xAttrList,
        ::com::sun::star::uno::Any& rValue,
        ::rtl::OUString& rStrName );
};

class XMLTransGradientStyleExport
{
    SvXMLExport& rExport;

public:
    XMLTransGradientStyleExport( SvXMLExport& rExport );
    ~XMLTransGradientStyleExport();

    sal_Bool exportXML( const ::rtl::OUString& rStrName, const ::com::sun::star::uno::Any& rValue );
};

#endif // _XMLOFF_TRANSGRADIENTSTYLE_HXX
<|endoftext|>


<commit_before>#include "JPetHLDReader.h"
#include <iostream>
#include <cassert>

JPetHLDReader::JPetHLDReader():
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(NULL)
{
  /* */
}

JPetHLDReader::JPetHLDReader (const char* filename):
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(NULL)
{
  if (OpenFile(filename) ) ReadData();
}

JPetHLDReader::~JPetHLDReader ()
{
  CloseFile();
}

void JPetHLDReader::CloseFile ()
{
  if (fFile != NULL) {
    if (fFile->IsOpen()) fFile->Close();
    delete fFile;
    fFile = NULL;
  }
  fBranch = 0;
  fEvent = 0;
  fTree = 0;
}

bool JPetHLDReader::OpenFile (const char* filename)
{
  CloseFile();
  fFile = new TFile(filename);

  if ((!fFile->IsOpen()) || fFile->IsZombie()) {
    ERROR("Cannot open file.");
    CloseFile();
    return false;
  }
  return true;
}

void JPetHLDReader::ReadData ()
{
<<<<<<< HEAD
  fTree = static_cast<TTree*>(fFile->Get("T")); /// @todo add some comment
=======
  fTree = static_cast<TTree*>(fFile.Get("T"));
>>>>>>> develop
  assert(fTree);
  fBranch = fTree->GetBranch("event");
  assert(fBranch);
  fBranch->SetAddress(&fEvent);
}
<commit_msg>Finished the merge of JPetHLDReader<commit_after>#include "JPetHLDReader.h"
#include <iostream>
#include <cassert>

JPetHLDReader::JPetHLDReader():
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(NULL)
{
  /* */
}

JPetHLDReader::JPetHLDReader (const char* filename):
  fBranch(0),
  fEvent(0),
  fTree(0),
  fFile(NULL)
{
  if (OpenFile(filename) ) ReadData();
}

JPetHLDReader::~JPetHLDReader ()
{
  CloseFile();
}

void JPetHLDReader::CloseFile ()
{
  if (fFile != NULL) {
    if (fFile->IsOpen()) fFile->Close();
    delete fFile;
    fFile = NULL;
  }
  fBranch = 0;
  fEvent = 0;
  fTree = 0;
}

bool JPetHLDReader::OpenFile (const char* filename)
{
  CloseFile();
  fFile = new TFile(filename);

  if ((!fFile->IsOpen()) || fFile->IsZombie()) {
    ERROR("Cannot open file.");
    CloseFile();
    return false;
  }
  return true;
}

void JPetHLDReader::ReadData ()
{
  fTree = static_cast<TTree*>(fFile->Get("T")); /// @todo add some comment
  assert(fTree);
  fBranch = fTree->GetBranch("event");
  assert(fBranch);
  fBranch->SetAddress(&fEvent);
}
<|endoftext|>