int TradeShopHandler::helper_trade_shop_sell(SimulatorThread *sim,
		CharacterServerData *pld, SimulatorQuery *query,
		CreatureInstance *creatureInstance,
		const char *itemHex) {
	//Return the query response when selling stuff to an NPC shop.
	unsigned int CCSID = strtol(itemHex, NULL, 16);
	InventorySlot *item = pld->charPtr->inventory.GetItemPtrByCCSID(CCSID);
	if (item == NULL)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID,
				"Item not found in inventory.");

	ItemDef *itemPtr = item->ResolveItemPtr();
	if (itemPtr == NULL)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID,
				"Item does not exist in server database.");

	int wpos = 0;
	wpos += PrepExt_QueryResponseString(&sim->SendBuf[wpos], query->ID, "OK");

	int cost = itemPtr->mValue;
	cost *= item->GetStackCount();
	wpos += pld->charPtr->inventory.AddBuyBack(item, &sim->SendBuf[wpos]);
	wpos += RemoveItemUpdate(&sim->SendBuf[wpos], sim->Aux3, item);
	pld->charPtr->inventory.RemItem(CCSID);
	pld->charPtr->pendingChanges++;
	creatureInstance->AdjustCopper(cost);

	return wpos;
}
int TradeShopHandler::helper_trade_shop_buyback(SimulatorThread *sim,
		CharacterServerData *pld, SimulatorQuery *query,
		CreatureInstance *creatureInstance,unsigned int CCSID) {
	InventorySlot *buybackItem = pld->charPtr->inventory.GetItemPtrByCCSID(
			CCSID);
	if (buybackItem == NULL)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID,
				"Item not found in buyback list.");

	int freeslot = pld->charPtr->inventory.GetFreeSlot(INV_CONTAINER);
	if (freeslot == -1)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID,
				"No free inventory space.");

	ItemDef *itemPtr = buybackItem->ResolveItemPtr();
	if (itemPtr == NULL)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID,
				"Item does not exist in database.");

	int cost = itemPtr->mValue * buybackItem->GetStackCount();
	if (creatureInstance->css.copper < cost)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID, "Not enough coin.");

	InventorySlot newItem;
	newItem.CopyFrom(*buybackItem, false);
	newItem.CCSID = pld->charPtr->inventory.GetCCSID(INV_CONTAINER, freeslot);

	int r = pld->charPtr->inventory.AddItem(INV_CONTAINER, newItem);
	if (r == -1)
		return PrepExt_QueryResponseError(sim->SendBuf, query->ID,
				"Failed to create item.");
	pld->charPtr->pendingChanges++;

	int wpos = 0;
	wpos = RemoveItemUpdate(sim->SendBuf, sim->Aux3, buybackItem);
	wpos += AddItemUpdate(&sim->SendBuf[wpos], sim->Aux3, &newItem);
	wpos += PrepExt_QueryResponseString(&sim->SendBuf[wpos], query->ID, "OK");
	pld->charPtr->inventory.RemItem(buybackItem->CCSID);
	pld->charPtr->pendingChanges++;
	creatureInstance->AdjustCopper(-cost);
	return wpos;
}