unsigned int PosBlockArray::initBitStringIterator(unsigned int pos) {
  assert(posSorted);
  assert(pos >= getStartPos());
  assert(pos <= getEndPos());
  startPoses = new unsigned int[size];
  adjStartPoses = new unsigned int[size];
  endPoses = new unsigned int[size];
  int index;
  for (int i = 0; i < size; i++) {
    startPoses[i] = posBlockArray[i]->getStartPos();
    adjStartPoses[i] = startPoses[i];
    if (adjStartPoses[i] % 32)
      adjStartPoses[i] -= ((adjStartPoses[i] % 32) - 1);
    else {
      adjStartPoses[i] -= 31;
    }

    endPoses[i] = posBlockArray[i]->getEndPos();
    if (startPoses[i] > pos)
      index = i-1;
  }
  currBSPos = posBlockArray[index]->initBitStringIterator(pos);
  currBSIndex = index;
  //for (int i = index+1; i < size; i++)
  //  posBlockArray[i]->initBitStringIterator(startPoses[i]);
  return currBSPos;
}
Example #2
0
AdcCommand Download::getCommand(bool zlib) {
    AdcCommand cmd(AdcCommand::CMD_GET);

    cmd.addParam(Transfer::names[getType()]);

    if(getType() == TYPE_PARTIAL_LIST) {
        cmd.addParam(Util::toAdcFile(getPath()));
    } else if(getType() == TYPE_FULL_LIST) {
        if(isSet(Download::FLAG_XML_BZ_LIST)) {
            cmd.addParam(USER_LIST_NAME_BZ);
        } else {
            cmd.addParam(USER_LIST_NAME);
        }
    } else {
        cmd.addParam("TTH/" + getTTH().toBase32());
    }

    cmd.addParam(Util::toString(getStartPos()));
    cmd.addParam(Util::toString(getSize()));

    if(zlib && BOOLSETTING(COMPRESS_TRANSFERS)) {
        cmd.addParam("ZL1");
    }

    return cmd;
}
bool AllCountryReplyPacket::getCountryData( uint32 index,
                                            uint32& mapID, 
										              uint32& version,
                                            MC2BoundingBox& boundingBox,
											           Vector& stringIndex )
{
   if( index < getNbrCountries() ) {
      // Empty the vector.
      stringIndex.reset();
      int pos = getStartPos( index );
      mapID   = incReadLong( pos );
      version = incReadLong( pos );
      boundingBox.setMinLat( incReadLong( pos ) );
      boundingBox.setMinLon( incReadLong( pos ) );
      boundingBox.setMaxLat( incReadLong( pos ) );
      boundingBox.setMaxLon( incReadLong( pos ) );
      int nbrStrings = incReadLong( pos );
      for( int i=0; i < nbrStrings; i++ ) {
         int string = incReadLong( pos );      
         stringIndex.addLast( string );
      }
      return true;
   }
   return false;
}
Example #4
0
 bool roseNode::hasSourcePos() const
 {
   source_position pos = getStartPos();
   //0 line number means no source position information for ROSE AST
   if (pos.line==0)
     return false;
   else
     return true;
 }
Example #5
0
void newPiece(Game *theGame)
{
    theGame->mPiece = theGame->nextP;
    theGame->mRot  = theGame->nextRot;
    int pX, pY;
    getStartPos(theGame->mPiece, theGame->mRot, &pX, &pY);
    theGame->mXloc = (BOARD_WIDTH / 2) + pX;
    theGame->mYloc = pY;
    theGame->nextP = getRand(0, 6);
    theGame->nextRot = getRand(0,3);
}
Example #6
0
        f32 findServeUpAngle(int throwFlight)
        {
            int flight1, flight2;
            
            f32 upTableAngle = 30;
            f32 downTableAngle = -60;
            
            f32 tableAngle = (upTableAngle + downTableAngle)/2;

            int maxTry = 5;

            setParam(m_hitParam);

            getClissionSystem()->setHorizPlane(0, true, true);
            getClissionSystem()->setDetectObjects(COLLISION_OBJECT_HORIZ_PLANE);

            while (maxTry > 0)
            {
                maxTry--;

                getParam().upAngle = tableAngle;
                
                flight1 = makeFlight(throwFlight);

                flight2 = rebound(flight1);

                _VECTOR3D & left = getSegmengNode(flight2, 0)->pos;
                _VECTOR3D & right = getSegmengNode(flight2, -1)->pos;

                _VECTOR3D center  = (left + right)/2;
                _VECTOR3D distance = (right - left);

                // center accuracy;
                if (fabs(center._X/distance._X) < 0.2f)
                {
                    break;
                }
                else if (getStartPos()._X * center._X > 0)
                {
                    downTableAngle = tableAngle;
                }
                else
                {
                    upTableAngle = tableAngle;
                }

                tableAngle = (upTableAngle + downTableAngle)/2;
            }

            removeAfter(throwFlight);

            return tableAngle;
        }
Example #7
0
void initGame( Game *theGame )
{
    srand(time(NULL));

    theGame->mPiece = getRand(0,6);
    theGame->mRot  = getRand(0, 3);
    int pX, pY;
    getStartPos(theGame->mPiece, theGame->mRot, &pX, &pY);
    theGame->mXloc = (BOARD_WIDTH / 2) + pX;
    theGame->mYloc = pY;

    theGame->nextP = getRand(0, 6);
    theGame->nextRot = getRand(0,3);
    theGame->nextX =  BOARD_WIDTH + 5;
    theGame->nextY = 5;
}
Example #8
0
AdcCommand Download::getCommand(bool zlib, const string& mySID) const {
	AdcCommand cmd(AdcCommand::CMD_GET);
	
	cmd.addParam(Transfer::names[getType()]);

	if(getType() == TYPE_PARTIAL_LIST) {
		if (isSet(Download::FLAG_TTHLIST_BUNDLE)) {
			//these must be converted to adc file when adding (if needed, no slash for bundle requests)
			cmd.addParam(getTempTarget());
		} else {
			cmd.addParam(Util::toAdcFile(getTempTarget()));
		}
	} else if(getType() == TYPE_FULL_LIST) {
		if(isSet(Download::FLAG_XML_BZ_LIST)) {
			cmd.addParam(USER_LIST_NAME_BZ);
		} else {
			cmd.addParam(USER_LIST_NAME);
		}
	} else {
		cmd.addParam("TTH/" + getTTH().toBase32());
	}

	cmd.addParam(Util::toString(getStartPos()));
	cmd.addParam(Util::toString(getSegmentSize()));
	if(!mySID.empty()) //add requester's SID (mySID) to the filelist request, so he can find the hub we are calling from.
		cmd.addParam("ID", mySID); 

	if(zlib && SETTING(COMPRESS_TRANSFERS)) {
		cmd.addParam("ZL1");
	}

	if(isSet(Download::FLAG_RECURSIVE) && getType() == TYPE_PARTIAL_LIST) {
		cmd.addParam("RE1");
	}
	
	if(isSet(Download::FLAG_QUEUE) && getType() == TYPE_PARTIAL_LIST) {	 
		cmd.addParam("TL1");	 
	}

	return cmd;
}
Example #9
0
AdcCommand Download::getCommand(bool zlib, const string& mySID) const noexcept {
	AdcCommand cmd(AdcCommand::CMD_GET);
	
	cmd.addParam(Transfer::names[getType()]);

	if(getType() == TYPE_PARTIAL_LIST) {
		cmd.addParam(getListDirectoryPath());
	} else if(getType() == TYPE_FULL_LIST) {
		if(isSet(Download::FLAG_XML_BZ_LIST)) {
			cmd.addParam(USER_LIST_NAME_BZ);
		} else {
			cmd.addParam(USER_LIST_NAME);
		}
	} else {
		cmd.addParam("TTH/" + getTTH().toBase32());
	}

	cmd.addParam(Util::toString(getStartPos()));
	cmd.addParam(Util::toString(getSegmentSize()));
	if(!mySID.empty()) //add requester's SID (mySID) to the filelist request, so he can find the hub we are calling from.
		cmd.addParam("ID", mySID); 

	if(zlib && SETTING(COMPRESS_TRANSFERS)) {
		cmd.addParam("ZL1");
	}

	if(isSet(Download::FLAG_RECURSIVE) && getType() == TYPE_PARTIAL_LIST) {
		cmd.addParam("RE1");
	}
	
	if(isSet(Download::FLAG_QUEUE) && getType() == TYPE_PARTIAL_LIST) {	 
		cmd.addParam("TL1");	 
	}

	return cmd;
}
Example #10
0
int main(int argc, char *argv[])
{
struct dyString *dy = NULL;
int startPos = 1;
char *chrom = "chr1";
int chromSize = 0;
int windowSize = 100000;
struct machine *machinePos;
time_t now;
char testTime[100];
char testDate[100];
long elapsedTime = 0;

optionInit(&argc, argv, optionSpecs);

expireSeconds = 300;	/* 5 minutes */
(void) signal(SIGALRM, selfApoptosis);
(void) alarm(expireSeconds);	/* CGI timeout */

quiet = optionExists("quiet");
now = time(NULL);
strftime(testTime, 100, "%H:%M", localtime(&now));
strftime(testDate, 100, "%B %d, %Y", localtime(&now));
if (!quiet)
    printf("%s %s\n", testDate, testTime);

if (argc != 2)
    usage();

srand( (unsigned) time(NULL) );

database = hDefaultDbForGenome(NULL); // default human db

chromHash = loadAllChromInfo();
chromSize = getChromSize(chrom);
startPos = getStartPos(chromSize, windowSize);
if (! quiet)
    printf("%s %s:%d-%d\n\n", database, chrom, startPos, startPos + windowSize);

getMachines(argv[1]);

for (machinePos = machineList; machinePos != NULL; machinePos = machinePos->next)
    {
    dy = newDyString(256);
    dyStringPrintf(dy, "%s/cgi-bin/hgTracks?db=%s&position=%s:%d-%d", machinePos->name, 
                   database, chrom, startPos, startPos + windowSize);
    elapsedTime = hgTracksRandom(dy->string);
    if (quiet)
	{
	printf("%ld\n", elapsedTime);
	}
    else
	{
	if (elapsedTime > 5000)
	    printf("%s %ld <---\n", machinePos->name, elapsedTime);
	else
	    printf("%s %ld\n", machinePos->name, elapsedTime);
	}
    }
if (! quiet)
    printf("----------------------------------\n");

/* free machine list */
return 0;
}
Example #11
0
void ib::Completer::completeOption(std::vector<ib::CompletionValue*> &candidates, const std::string &command) { // {{{
  if(!hasCompletionFunc(command)) return;
  auto maininput = ib::Singleton<ib::MainWindow>::getInstance()->getInput();
  const auto &input = maininput->getCursorValue();
  const auto &tokens = maininput->getTokens();
  const auto token = maininput->getCursorToken();
  const unsigned int position = maininput->position();
  method_option_->beforeMatch(candidates, input);
  
  const auto start = lua_gettop(IB_LUA);
  lua_getglobal(IB_LUA, "system");
  lua_getfield(IB_LUA, -1, "completer");
  lua_getfield(IB_LUA, -1, "option_func");
  lua_getfield(IB_LUA, -1, command.c_str());
  lua_newtable(IB_LUA);
  const auto top = lua_gettop(IB_LUA);
  int i = 1;
  int current_index = 1;
  unsigned int token_index = 1; // 0 is command name
  for(; token_index < tokens.size(); token_index++){
    const auto token = tokens.at(token_index);
    const auto is_current = token->getStartPos() < position && token->getEndPos() >= position;
    const auto is_last = (tokens.size() - 1 == token_index);

    if(token->isValueToken()) {
      lua_pushinteger(IB_LUA, i);
      lua_pushstring(IB_LUA, token->getValue().c_str());
      lua_settable(IB_LUA, top);
      if(is_current) current_index = i;
      i++;
    } else if(is_current){
      current_index = i;
      if(is_last){
        lua_pushinteger(IB_LUA, i);
        lua_pushstring(IB_LUA, "");
        lua_settable(IB_LUA, top);
        i++;
      }
    }
  }

  lua_pushinteger(IB_LUA, current_index);
  if(lua_pcall(IB_LUA, 2, 1, 0) != 0){
    ib::utils::message_box("%s", lua_tostring(IB_LUA, lua_gettop(IB_LUA)));
    return;
  }

  if(!lua_istable(IB_LUA, -1)) {
    ib::utils::message_box("Completion function must return a table, but got a(n) %s", lua_typename(IB_LUA, lua_type(IB_LUA, -1)));
    return;
  }

  for(i = 1;;i++){
    lua_pushinteger(IB_LUA, i); 
    lua_gettable(IB_LUA, -2); 
    if(lua_isnil(IB_LUA, -1)){
      lua_pop(IB_LUA, 1);
      break;
    }
    switch(lua_type(IB_LUA, -1)) {
      case LUA_TSTRING: {
          const auto value = luaL_checkstring(IB_LUA, -1);
          if(!token->isValueToken() || method_option_->match(value, input) > -1){
            candidates.push_back(new ib::CompletionString(value));
          }
        }
        break;

      case LUA_TTABLE: {
          lua_getfield(IB_LUA, -1, "value");
          const auto value = luaL_checkstring(IB_LUA, -1);
          lua_pop(IB_LUA, 1);
          lua_getfield(IB_LUA, -1, "always_match");
          const auto is_always_match = lua_toboolean(IB_LUA, -1);
          lua_pop(IB_LUA, 1);

          if(is_always_match || !token->isValueToken() || method_option_->match(value, input) > -1){
            ib::CompletionString *compstr = new ib::CompletionString(value);

            lua_getfield(IB_LUA, -1, "description");
            if(!lua_isnil(IB_LUA, -1)){
              compstr->setDescription(luaL_checkstring(IB_LUA, -1));
            }
            lua_pop(IB_LUA, 1);

            lua_getfield(IB_LUA, -1, "icon");
            if(!lua_isnil(IB_LUA, -1)){
              compstr->setIconFile(luaL_checkstring(IB_LUA, -1));
            }
            lua_pop(IB_LUA, 1);
            if(is_always_match) {
              if(token->isValueToken()) {
                compstr->setCompvalue(input.c_str());
              }else {
                compstr->setCompvalue(value);
              }
            }
            candidates.push_back(compstr);
          }
        }
        break;

      default:
        ;
    }
    lua_pop(IB_LUA, 1);
  }
 
  lua_pop(IB_LUA, lua_gettop(IB_LUA) - start);
  method_option_->afterMatch(candidates, input);
} // }}}
Example #12
0
/*
	We begin at whatever our start position is -- From there (in order) we will 
	check the north, west, east, and south "cells".  Additionally each time we are checking
	these surrounding cells we are building paths from the starting cell that includes
	these cells.  So assuming that ALL four cells where open, and NONE of these cells
	were the destination, we'd have four distinct paths that lead out from our start cell.

	So we've starting building four distinct paths from our start cell... What now?  Well
	for each path we start to build we'll add it to a local variable "master_list".  This 
	is a queue of stacks.  If you are unfamiliar with what a queue or stack is, this is where
	you stop reading this tutorial and brush up on those concepts, otherwise chances are good
	that you will become hopelessly lost.

	The "master_list", as aforementioned, is a queue of stacks -- We're using STL so we 
	don't have to worry about the implementation of the queue or the stack, all we have to do
	is use it.  Each stack in our queue will be a stack of "cells" that lead away from our
	start cell.  The first time through the loop (assuming all the north, west, east and south
	cells are open) we'd have FOUR distinct stacks of cells leading out of the start cell.  It
	would look something like this:
						
	QUEUE[0] = { STACK["North Cell"] ["Start Cell"] }		// Top of queue
	QUEUE[1] = { STACK["West Cell"] ["Start Cell"] }
	QUEUE[2] = { STACK["East Cell"] ["Start Cell"] }
	QUEUE[3] = { STACK["South Cell"] ["Start Cell"] }		// Bottom of queue

	The next time through the loop we'll pop off the TOP stack of our queue (the stack
	containing the start cell and the "north adjacent cell") -- Then we'd check to 
	see if we can move to ANY of the adjacent cells to the "north adjacent cell"
	Lets assume we can move to the north, west, and east cell (we obviously can't move
	to the south cell because that's the start cell and we've all ready visited it)
	Then what we'd have is 3 NEW paths that are added to the master list.  It would then
	look something like this:

	// N == the cell NORTH of the starting cell

	QUEUE[0] = { STACK["West Cell"] ["Start Cell"] }			// Top of queue
	QUEUE[1] = { STACK["East Cell"] ["Start Cell"] }
	QUEUE[2] = { STACK["South Cell"] ["Start Cell"] }
	QUEUE[3] = { STACK["North of N"] [N] ["Start Cell"] }
	QUEUE[4] = { STACK["West of N"] [N] ["Start Cell"] }
	QUEUE[5] = { STACK["East of N"] [N] ["Start Cell"] }		// Bottom of queue

	Basically the pattern continues in this fashion until the destination is reached
	or the "master_list" becomes empty signifying there is NO path from the start cell
	to the destination cell.
	
	This is all really wordy and high level.  So if your eyes glazed over when you were
	reading it, don't worry so did mine :) -- Hopefully it will make some more sense
	when you read the implementation
*/
bool CGrid::pathFind()
{
	/* 
	   So what's up with the COORD?  Our grid is made up of a double array of CCell's.
	   We'll use the COORD (which contains an x and y) for storing the row/column 
	   indices into our double array so we know what cell we are on.  There is an explanation
	   of row/column vs (x,y) at the bottom of grid.h in case you find yourself asking the 
	   question "What is he doing???"
	*/


	queue< stack<COORD> > master_list; // Our master list of stacks of cells that 
									  // are all valid different paths from the start cell

	stack<COORD> single_path; // This will hold ONE valid path from the start cell

	int startX, startY;

	getStartPos(startX,startY); // Get our starting position 
	grid_array[startY][startX].setVisited(true); // Set the starting position to visited

	COORD cell = {startX,startY}; // Create a COORD representing our starting postion

	single_path.push(cell); // Our first path obviously begins with the starting position
	master_list.push(single_path); // This will also be the first stack of potential 
								  // paths on our master list

	// We loop while the "master_list" is not empty -- If it becomes empty then NO 
	// path exists from the start cell to the destination cell
	while(master_list.empty() == false)
	{
		single_path = master_list.front(); // Get the TOP stack of path cells
		master_list.pop(); // ALWAYS remove the TOP of queue -- Any potential paths
						   // will be re-added at the back of the queue once we've
						   // went through checking for open adjacent cells

		cell = single_path.top(); // Get the current cell we're checking 
								 // for our current stack of path cells

		// Loop through all possible adjacent CCell's
		for(int dest_y = cell.Y - 1; dest_y <= cell.Y + 1; dest_y++)
		{
			for(int dest_x = cell.X - 1; dest_x <= cell.X + 1; dest_x++)
			{
				// We are only concerned with north, west, east, and south adjacent cells,
				// so skip all cells we don't care about
				if(!isAdjacent(cell.X,cell.Y,dest_x,dest_y))
					continue; 
				
				// If the CCell is open (ie it hasn't been visited and it's not a wall)
				if(isOpen(dest_x,dest_y))
				{
					COORD temp_cell = {dest_x, dest_y};

					// If the cell is the destination cell -- We're done!!!!!!!!!
					if(grid_array[dest_y][dest_x].getCellVal() == DEST)
					{	
						dest_found = true; // We've found the destination
						
						// Add the destination to the stack of "path_nodes"
						path_nodes.push(temp_cell);

						// Then, while the "single_path" (which is the SHORTEST PATH)
						// isn't empty, add all the CCell's (the COORD holding the row/column
						// indexes into our double array of CCell's) in "single_path" to the 
						// "path_nodes" -- This works out slick, so are path_nodes will
						// be in the correct order (ie start pos at top, end pos at bottom)
						while(single_path.empty() == false)
						{
							path_nodes.push(single_path.top());
							single_path.pop();
						}
							
						return true; // We have found the promised land!
					}

					// If we get here, then the current "open" cell is not the
					// destination cell

					// So... First set the now open cell to visited 
					grid_array[dest_y][dest_x].setVisited(true);

					// Then add it to our current path
					single_path.push(temp_cell);

					// Then add the new current path to the master list
					master_list.push(single_path);

					// Last but not least, remove the "cell" we just added to our current
					// path.  Remember we want to create all the new potential paths
					// leading away from our current "end cell" in our "current path"
					// So we pop off the cell we just added so next time through the loop
					// we'll check our previous state again
					single_path.pop();

				} // end of if(isOpen(dest_x,dest_y))
			
			} // end of for(int dest_x = cell.X - 1; dest_x <= cell.X + 1; dest_x++)

		} // end of for(int dest_y = cell.Y - 1; dest_y <= cell.Y + 1; dest_y++)

	} // end of while(master_list.empty() == false)

	return false; // No path existed

} // end of void CGrid::pathFind()
Example #13
0
Download::Download(UserConnection& conn, QueueItem& qi) noexcept : Transfer(conn, qi.getTarget(), qi.getTTH()),
	tempTarget(qi.getTempTarget())
{
	conn.setDownload(this);
	
	QueueItem::SourceConstIter source = qi.getSource(getUser());

	if(qi.isSet(QueueItem::FLAG_PARTIAL_LIST)) {
		setType(TYPE_PARTIAL_LIST);
	} else if(qi.isSet(QueueItem::FLAG_USER_LIST)) {
		setType(TYPE_FULL_LIST);
	}

	if(source->isSet(QueueItem::Source::FLAG_PARTIAL))
		setFlag(FLAG_PARTIAL);
	if(qi.isSet(QueueItem::FLAG_CLIENT_VIEW))
		setFlag(FLAG_VIEW);
	if(qi.isSet(QueueItem::FLAG_MATCH_QUEUE))
		setFlag(FLAG_QUEUE);
	if(qi.isSet(QueueItem::FLAG_VIEW_NFO))
		setFlag(FLAG_NFO);
	if(qi.isSet(QueueItem::FLAG_RECURSIVE_LIST))
		setFlag(FLAG_RECURSIVE);
	if(qi.isSet(QueueItem::FLAG_TTHLIST_BUNDLE))
		setFlag(FLAG_TTHLIST_BUNDLE);
	if (qi.getPriority() == QueueItemBase::HIGHEST)
		setFlag(FLAG_HIGHEST_PRIO);

	if (qi.getBundle()) {
		dcassert(!qi.isSet(QueueItem::FLAG_USER_LIST));
		dcassert(!qi.isSet(QueueItem::FLAG_TEXT));
		setBundle(qi.getBundle());
	}
	
	if(getType() == TYPE_FILE && qi.getSize() != -1) {
		if(HashManager::getInstance()->getTree(getTTH(), getTigerTree())) {
			setTreeValid(true);
			setSegment(qi.getNextSegment(getTigerTree().getBlockSize(), conn.getChunkSize(), conn.getSpeed(), source->getPartialSource(), true));
			qi.setBlockSize(getTigerTree().getBlockSize());
		} else if(conn.isSet(UserConnection::FLAG_SUPPORTS_TTHL) && !source->isSet(QueueItem::Source::FLAG_NO_TREE) && qi.getSize() > HashManager::MIN_BLOCK_SIZE) {
			// Get the tree unless the file is small (for small files, we'd probably only get the root anyway)
			setType(TYPE_TREE);
			getTigerTree().setFileSize(qi.getSize());
			setSegment(Segment(0, -1));
		} else {
			// Use the root as tree to get some sort of validation at least...
			getTigerTree() = TigerTree(qi.getSize(), qi.getSize(), getTTH());
			setTreeValid(true);
			setSegment(qi.getNextSegment(getTigerTree().getBlockSize(), 0, 0, source->getPartialSource(), true));
		}
		
		if ((getStartPos() + getSegmentSize()) != qi.getSize() || (conn.getDownload() && conn.getDownload()->isSet(FLAG_CHUNKED))) {
			setFlag(FLAG_CHUNKED);
		}

		if(getSegment().getOverlapped()) {
			setFlag(FLAG_OVERLAP);

			// set overlapped flag to original segment
			for(auto d: qi.getDownloads()) {
				if(d->getSegment().contains(getSegment())) {
					d->setOverlapped(true);
					break;
				}
			}
		}
	}
}
Example #14
0
void Download::open(int64_t bytes, bool z, bool hasDownloadedBytes) {
	if(getType() == Transfer::TYPE_FILE) {
		auto target = getDownloadTarget();
		auto fullSize = tt.getFileSize();

		if(getOverlapped() && bundle) {
			setOverlapped(false);
 	 
			bool found = false;
			// ok, we got a fast slot, so it's possible to disconnect original user now
			for(auto d: bundle->getDownloads()) {
				if(d != this && compare(d->getPath(), getPath()) == 0 && d->getSegment().contains(getSegment())) {
 	 
					// overlapping has no sense if segment is going to finish
					if(d->getSecondsLeft() < 10)
						break;
 	 
					found = true;
 	 
					// disconnect slow chunk
					d->getUserConnection().disconnect();
					break;
				}
			}

			if(!found) {
				// slow chunk already finished ???
				throw Exception(STRING(DOWNLOAD_FINISHED_IDLE));
			}
		}

		if(hasDownloadedBytes) {
			if(File::getSize(target) != fullSize) {
				// When trying the download the next time, the resume pos will be reset
				throw Exception(CSTRING(TARGET_FILE_MISSING));
			}
		} else {
			File::ensureDirectory(target);
		}

		int flags = File::OPEN | File::CREATE | File::SHARED_WRITE;
		if (getSegment().getEnd() != fullSize) {
			//segmented download, let Windows decide the buffering
			flags |= File::BUFFER_AUTO;
		}

		unique_ptr<SharedFileStream> f(new SharedFileStream(target, File::WRITE, flags));

		if(f->getSize() != fullSize) {
			f->setSize(fullSize);
		}

		f->setPos(getSegment().getStart());
		output = move(f);
		tempTarget = target;
	} else if(getType() == Transfer::TYPE_FULL_LIST) {
		auto target = getPath();
		File::ensureDirectory(target);

		if(isSet(Download::FLAG_XML_BZ_LIST)) {
			target += ".xml.bz2";
		} else {
			target += ".xml";
		}

		output.reset(new File(target, File::WRITE, File::OPEN | File::TRUNCATE | File::CREATE));
		tempTarget = target;
	} else if(getType() == Transfer::TYPE_PARTIAL_LIST) {
		output.reset(new StringOutputStream(pfs));
	} else if(getType() == Transfer::TYPE_TREE) {
		output.reset(new MerkleTreeOutputStream<TigerTree>(tt));
	}

	if((getType() == Transfer::TYPE_FILE || getType() == Transfer::TYPE_FULL_LIST) && SETTING(BUFFER_SIZE) > 0 ) {
		output.reset(new BufferedOutputStream<true>(output.release()));
	}

	if(getType() == Transfer::TYPE_FILE && !SettingsManager::lanMode) {
		typedef MerkleCheckOutputStream<TigerTree, true> MerkleStream;

		output.reset(new MerkleStream(tt, output.release(), getStartPos()));
		setFlag(Download::FLAG_TTH_CHECK);
	}

	// Check that we don't get too many bytes
	output.reset(new LimitedOutputStream<true>(output.release(), bytes));

	if(z) {
		setFlag(Download::FLAG_ZDOWNLOAD);
		output.reset(new FilteredOutputStream<UnZFilter, true>(output.release()));
	}
}