text:
using namespace json_spirit;
using namespace std;

int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;

static std::string HelpRequiringPassphrase()
{
    return pwalletMain->IsCrypted()
        ? "\nrequires wallet passphrase to be set with walletpassphrase first"
        : "";
}

static inline void EnsureWalletIsUnlocked()
{
    if (pwalletMain->IsLocked())
        throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}

void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
    int confirms = wtx.GetDepthInMainChain();
    entry.push_back(Pair("confirmations", confirms));
    if (confirms)
    {
        entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
        entry.push_back(Pair("blockindex", wtx.nIndex));
    }
    entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
    entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
    BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
        entry.push_back(Pair(item.first, item.second));
}

string AccountFromValue(const Value& value)
{
    string strAccount = value.get_str();
    if (strAccount == "*")
        throw JSONRPCError(-11, "Invalid account name");
    return strAccount;
}

Value getinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getinfo\n"
            "Returns an object containing various state info.");

    CService addrProxy;
    GetProxy(NET_IPV4, addrProxy);

    Object obj;
    obj.push_back(Pair("version",       FormatFullVersion()));
    obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
    obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
    obj.push_back(Pair("balance",       ValueFromAmount(pwalletMain->GetBalance())));
    obj.push_back(Pair("newmint",       ValueFromAmount(pwalletMain->GetNewMint())));
    obj.push_back(Pair("stake",         ValueFromAmount(pwalletMain->GetStake())));
    obj.push_back(Pair("blocks",        (int)nBestHeight));
    obj.push_back(Pair("moneysupply",   ValueFromAmount(pindexBest->nMoneySupply)));
    obj.push_back(Pair("connections",   (int)vNodes.size()));
    obj.push_back(Pair("proxy",         (addrProxy.IsValid() ? addrProxy.ToStringIPPort() : string())));
    obj.push_back(Pair("ip",            addrSeenByPeer.ToStringIP()));
    obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
    obj.push_back(Pair("testnet",       fTestNet));
    obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
    obj.push_back(Pair("keypoolsize",   pwalletMain->GetKeyPoolSize()));
    obj.push_back(Pair("paytxfee",      ValueFromAmount(nTransactionFee)));
    if (pwalletMain->IsCrypted())
        obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
    obj.push_back(Pair("errors",        GetWarnings("statusbar")));
    return obj;
}

Value getnewaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "getnewaddress [account]\n"
            "Returns a new Paycoin address for receiving payments.  "
            "If [account] is specified (recommended), it is added to the address book "
            "so payments received with the address will be credited to [account].");

    // Parse the account first so we don't generate a key if there's an error
    string strAccount;
    if (params.size() > 0)
        strAccount = AccountFromValue(params[0]);

    if (!pwalletMain->IsLocked())
        pwalletMain->TopUpKeyPool();

    // Generate a new key that is added to wallet
    CPubKey newKey;
    if (!pwalletMain->GetKeyFromPool(newKey, false))
        throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
    CKeyID keyID = newKey.GetID();

    pwalletMain->SetAddressBookName(keyID, strAccount);

    return CBitcoinAddress(keyID).ToString();
}

CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
    CWalletDB walletdb(pwalletMain->strWalletFile);

    CAccount account;
    walletdb.ReadAccount(strAccount, account);

    bool bKeyUsed = false;

    // Check if the current key has been used
    if (account.vchPubKey.IsValid())
    {
        CScript scriptPubKey;
        scriptPubKey.SetDestination(account.vchPubKey.GetID());
        for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
             it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
             ++it)
        {
            const CWalletTx& wtx = (*it).second;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                if (txout.scriptPubKey == scriptPubKey)
                    bKeyUsed = true;
        }
    }

    // Generate a new key
    if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
    {
        if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
            throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");

        pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
        walletdb.WriteAccount(strAccount, account);
    }

    return CBitcoinAddress(account.vchPubKey.GetID());
}

Value getaccountaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getaccountaddress <account>\n"
            "Returns the current Paycoin address for receiving payments to this account.");

    // Parse the account first so we don't generate a key if there's an error
    string strAccount = AccountFromValue(params[0]);

    Value ret;

    ret = GetAccountAddress(strAccount).ToString();

    return ret;
}

Value setaccount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "setaccount <paycoinaddress> <account>\n"
            "Sets the account associated with the given address.");

    CBitcoinAddress address(params[0].get_str());
    if (!address.IsValid())
        throw JSONRPCError(-5, "Invalid Paycoin address");

    string strAccount;
    if (params.size() > 1)
        strAccount = AccountFromValue(params[1]);

    // Detect when changing the account of an address that is the 'unused current key' of another account:
    if (pwalletMain->mapAddressBook.count(address.Get()))
    {
        string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
        if (address == GetAccountAddress(strOldAccount))
            GetAccountAddress(strOldAccount, true);
    }

    pwalletMain->SetAddressBookName(address.Get(), strAccount);

    return Value::null;
}

Value getaccount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getaccount <paycoinaddress>\n"
            "Returns the account associated with the given address.");

    CBitcoinAddress address(params[0].get_str());
    if (!address.IsValid())
        throw JSONRPCError(-5, "Invalid Paycoin address");

    string strAccount;
    map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
    if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
        strAccount = (*mi).second;
    return strAccount;
}

Value getaddressesbyaccount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getaddressesbyaccount <account>\n"
            "Returns the list of addresses for the given account.");

    string strAccount = AccountFromValue(params[0]);

    // Find all addresses that have the given account
    Array ret;
    BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
    {
        const CBitcoinAddress& address = item.first;
        const string& strName = item.second;
        if (strName == strAccount)
            ret.push_back(address.ToString());
    }
    return ret;
}

Value sendtoaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 2 || params.size() > 4)
        throw runtime_error(
            "sendtoaddress <paycoinaddress> <amount> [comment] [comment-to]\n"
            "<amount> is a real and is rounded to the nearest 0.00000001"
            + HelpRequiringPassphrase());

    CBitcoinAddress address(params[0].get_str());
    if (!address.IsValid())
        throw JSONRPCError(-5, "Invalid Paycoin address");

    // Amount
    int64 nAmount = AmountFromValue(params[1]);
    if (nAmount < MIN_TXOUT_AMOUNT)
        throw JSONRPCError(-101, "Send amount too small");

    // Wallet comments
    CWalletTx wtx;
    if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
        wtx.mapValue["comment"] = params[2].get_str();
    if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
        wtx.mapValue["to"]      = params[3].get_str();

    if (pwalletMain->IsLocked())
        throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");

    string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
    if (strError != "")
        throw JSONRPCError(-4, strError);

    return wtx.GetHash().GetHex();
}

Value signmessage(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 2)
        throw runtime_error(
            "signmessage <paycoinaddress> <message>\n"
            "Sign a message with the private key of an address");

    EnsureWalletIsUnlocked();

    string strAddress = params[0].get_str();
    string strMessage = params[1].get_str();

    CBitcoinAddress addr(strAddress);
    if (!addr.IsValid())
        throw JSONRPCError(-3, "Invalid address");

    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
        throw JSONRPCError(-3, "Address does not refer to key");

    CKey key;
    if (!pwalletMain->GetKey(keyID, key))
        throw JSONRPCError(-4, "Private key not available");

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << strMessage;

    vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
        throw JSONRPCError(-5, "Sign failed");

    return EncodeBase64(&vchSig[0], vchSig.size());
}

Value verifymessage(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 3)
        throw runtime_error(
            "verifymessage <paycoinaddress> <signature> <message>\n"
            "Verify a signed message");

    string strAddress  = params[0].get_str();
    string strSign     = params[1].get_str();
    string strMessage  = params[2].get_str();

    CBitcoinAddress addr(strAddress);
    if (!addr.IsValid())
        throw JSONRPCError(-3, "Invalid address");

    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
        throw JSONRPCError(-3, "Address does not refer to key");

    bool fInvalid = false;
    vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);

    if (fInvalid)
        throw JSONRPCError(-5, "Malformed base64 encoding");

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << strMessage;

    CKey key;
    if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
        return false;

    return (key.GetPubKey().GetID() == keyID);
}

Value getreceivedbyaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getreceivedbyaddress <paycoinaddress> [minconf=1]\n"
            "Returns the total amount received by <paycoinaddress> in transactions with at least [minconf] confirmations.");

    // Bitcoin address
    CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
    CScript scriptPubKey;
    if (!address.IsValid())
        throw JSONRPCError(-5, "Invalid Paycoin address");
    scriptPubKey.SetDestination(address.Get());
    if (!IsMine(*pwalletMain,scriptPubKey))
        return (double)0.0;

    // Minimum confirmations
    int nMinDepth = 1;
    if (params.size() > 1)
        nMinDepth = params[1].get_int();

    // Tally
    int64 nAmount = 0;
    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {
        const CWalletTx& wtx = (*it).second;
        if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
            continue;

        BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            if (txout.scriptPubKey == scriptPubKey)
                if (wtx.GetDepthInMainChain() >= nMinDepth)
                    nAmount += txout.nValue;
    }

    return  ValueFromAmount(nAmount);
}

void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
    BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
    {
        const CTxDestination& address = item.first;
        const string& strName = item.second;
        if (strName == strAccount)
            setAddress.insert(address);
    }
}

Value listminting(const Array& params, bool fHelp)
{
    if(fHelp || params.size() > 2)
        throw runtime_error(
                "listminting [count=-1] [from=0]\n"
                "Return all mintable outputs and provide details for each of them.");

    int count = -1;

    if(params.size() > 0)
        count = params[0].get_int();

    int from = 0;
    if(params.size() > 1)
        from = params[1].get_int();

    Array ret;

    const CBlockIndex *p = GetLastBlockIndex(pindexBest, true);
    double difficulty = p->GetBlockDifficulty();

    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {

        std::vector<KernelRecord> txList = KernelRecord::decomposeOutput(pwalletMain, it->second);
        int minAge = nStakeMinAge / 60 / 60 / 24;
        BOOST_FOREACH(KernelRecord& kr, txList) {
            if(!kr.spent) {

                if((count > 0 && ret.size() >= count) || from > 0) {
                    from--;
                    break;
                }

                string strTime = boost::lexical_cast<std::string>(kr.nTime);
                string strAmount = boost::lexical_cast<std::string>(kr.nValue);
                string strAge = boost::lexical_cast<std::string>(kr.getAge());
                string strCoinAge = boost::lexical_cast<std::string>(kr.coinAge);

                Array params;
                params.push_back(kr.address);
                string account = AccountFromValue(getaccount(params, false));

                string status = "immature";
                int searchInterval = 0;
                int attemps = 0;
                if(kr.getAge() >=  minAge)
                {
                    status = "mature";
                    searchInterval = (int)nLastCoinStakeSearchInterval;
                    attemps = GetAdjustedTime() - kr.nTime - nStakeMinAge;
                }

                Object obj;
                obj.push_back(Pair("account",                   account));
                obj.push_back(Pair("address",                   kr.address));
                obj.push_back(Pair("input-txid",                kr.hash.ToString()));
                obj.push_back(Pair("time",                      strTime));
                obj.push_back(Pair("amount",                    strAmount));
                obj.push_back(Pair("status",                    status));
                obj.push_back(Pair("age-in-day",                strAge));
                obj.push_back(Pair("coin-day-weight",           strCoinAge));
                obj.push_back(Pair("proof-of-stake-difficulty", difficulty));
                obj.push_back(Pair("minting-probability-10min", kr.getProbToMintWithinNMinutes(difficulty, 10)));
                obj.push_back(Pair("minting-probability-24h",   kr.getProbToMintWithinNMinutes(difficulty, 60*24)));
                obj.push_back(Pair("minting-probability-30d",   kr.getProbToMintWithinNMinutes(difficulty, 60*24*30)));
                obj.push_back(Pair("minting-probability-90d",   kr.getProbToMintWithinNMinutes(difficulty, 60*24*90)));
                obj.push_back(Pair("search-interval-in-sec",    searchInterval));
                obj.push_back(Pair("attempts",                  attemps));
                ret.push_back(obj);
            }
        }
    }

    return ret;
}

Value getreceivedbyaccount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getreceivedbyaccount <account> [minconf=1]\n"
            "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");

    // Minimum confirmations
    int nMinDepth = 1;
    if (params.size() > 1)
        nMinDepth = params[1].get_int();

    // Get the set of pub keys assigned to account
    string strAccount = AccountFromValue(params[0]);
    set<CTxDestination> setAddress;
    GetAccountAddresses(strAccount, setAddress);

    // Tally
    int64 nAmount = 0;
    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {
        const CWalletTx& wtx = (*it).second;
        if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
            continue;

        BOOST_FOREACH(const CTxOut& txout, wtx.vout)
        {
            CTxDestination address;
            if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
                if (wtx.GetDepthInMainChain() >= nMinDepth)
                    nAmount += txout.nValue;
        }
    }

    return (double)nAmount / (double)COIN;
}

int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
    int64 nBalance = 0;

    // Tally wallet transactions
    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {
        const CWalletTx& wtx = (*it).second;
        if (!wtx.IsFinal())
            continue;

        int64 nGenerated, nReceived, nSent, nFee;
        wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);

        if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
            nBalance += nReceived;
        nBalance += nGenerated - nSent - nFee;
    }

    // Tally internal accounting entries
    nBalance += walletdb.GetAccountCreditDebit(strAccount);

    return nBalance;
}

int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
    CWalletDB walletdb(pwalletMain->strWalletFile);
    return GetAccountBalance(walletdb, strAccount, nMinDepth);
}

Value getbalance(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getbalance [account] [minconf=1]\n"
            "If [account] is not specified, returns the server's total available balance.\n"
            "If [account] is specified, returns the balance in the account.");

    if (params.size() == 0)
        return  ValueFromAmount(pwalletMain->GetBalance());

    int nMinDepth = 1;
    if (params.size() > 1)
        nMinDepth = params[1].get_int();

    if (params[0].get_str() == "*") {
        // Calculate total balance a different way from GetBalance()
        // (GetBalance() sums up all unspent TxOuts)
        // getbalance and getbalance '*' should always return the same number.
        int64 nBalance = 0;
        for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
        {
            const CWalletTx& wtx = (*it).second;
            if (!wtx.IsFinal())
                continue;

            int64 allGeneratedImmature, allGeneratedMature, allFee;
            allGeneratedImmature = allGeneratedMature = allFee = 0;
            string strSentAccount;
            list<pair<CTxDestination, int64> > listReceived;
            list<pair<CTxDestination, int64> > listSent;
            wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
            if (wtx.GetDepthInMainChain() >= nMinDepth)
            {
                BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
                    nBalance += r.second;
            }
            BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
                nBalance -= r.second;
            nBalance -= allFee;
            nBalance += allGeneratedMature;
        }
        return  ValueFromAmount(nBalance);
    }

    string strAccount = AccountFromValue(params[0]);

    int64 nBalance = GetAccountBalance(strAccount, nMinDepth);

    return ValueFromAmount(nBalance);
}

Value movecmd(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 3 || params.size() > 5)
        throw runtime_error(
            "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
            "Move from one account in your wallet to another.");

    string strFrom = AccountFromValue(params[0]);
    string strTo = AccountFromValue(params[1]);
    int64 nAmount = AmountFromValue(params[2]);
    if (params.size() > 3)
        // unused parameter, used to be nMinDepth, keep type-checking it though
        (void)params[3].get_int();
    string strComment;
    if (params.size() > 4)
        strComment = params[4].get_str();

    CWalletDB walletdb(pwalletMain->strWalletFile);
    if (!walletdb.TxnBegin())
        throw JSONRPCError(-20, "database error");

    int64 nNow = GetAdjustedTime();

    // Debit
    CAccountingEntry debit;
    debit.strAccount = strFrom;
    debit.nCreditDebit = -nAmount;
    debit.nTime = nNow;
    debit.strOtherAccount = strTo;
    debit.strComment = strComment;
    walletdb.WriteAccountingEntry(debit);

    // Credit
    CAccountingEntry credit;
    credit.strAccount = strTo;
    credit.nCreditDebit = nAmount;
    credit.nTime = nNow;
    credit.strOtherAccount = strFrom;
    credit.strComment = strComment;
    walletdb.WriteAccountingEntry(credit);

    if (!walletdb.TxnCommit())
        throw JSONRPCError(-20, "database error");

    return true;
}

Value sendfrom(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 3 || params.size() > 6)
        throw runtime_error(
            "sendfrom <fromaccount> <topaycoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
            "<amount> is a real and is rounded to the nearest 0.00000001"
            + HelpRequiringPassphrase());

    string strAccount = AccountFromValue(params[0]);
    CBitcoinAddress address(params[1].get_str());
    if (!address.IsValid())
        throw JSONRPCError(-5, "Invalid Paycoin address");
    int64 nAmount = AmountFromValue(params[2]);
    if (nAmount < MIN_TXOUT_AMOUNT)
        throw JSONRPCError(-101, "Send amount too small");
    int nMinDepth = 1;
    if (params.size() > 3)
        nMinDepth = params[3].get_int();

    CWalletTx wtx;
    wtx.strFromAccount = strAccount;
    if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
        wtx.mapValue["comment"] = params[4].get_str();
    if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
        wtx.mapValue["to"]      = params[5].get_str();

    EnsureWalletIsUnlocked();

    // Check funds
    int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
    if (nAmount > nBalance)
        throw JSONRPCError(-6, "Account has insufficient funds");

    // Send
    string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
    if (strError != "")
        throw JSONRPCError(-4, strError);

    return wtx.GetHash().GetHex();
}

Value sendmany(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 2 || params.size() > 4)
        throw runtime_error(
            "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
            "amounts are double-precision floating point numbers"
            + HelpRequiringPassphrase());

    string strAccount = params[0].get_str();

    bool fFromAllAccounts = false;
    if (strAccount == "*")
    {
        fFromAllAccounts = true;
        strAccount = "";
    }

    Object sendTo = params[1].get_obj();
    int nMinDepth = 1;
    if (params.size() > 2)
        nMinDepth = params[2].get_int();

    CWalletTx wtx;
    wtx.strFromAccount = strAccount;
    if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
        wtx.mapValue["comment"] = params[3].get_str();

    set<CBitcoinAddress> setAddress;
    vector<pair<CScript, int64> > vecSend;

    int64 totalAmount = 0;
    BOOST_FOREACH(const Pair& s, sendTo)
    {
        CBitcoinAddress address(s.name_);
        if (!address.IsValid())
            throw JSONRPCError(-5, string("Invalid Paycoin address:")+s.name_);

        if (setAddress.count(address))
            throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_);
        setAddress.insert(address);

        CScript scriptPubKey;
        scriptPubKey.SetDestination(address.Get());
        int64 nAmount = AmountFromValue(s.value_);
        if (nAmount < MIN_TXOUT_AMOUNT)
            throw JSONRPCError(-101, "Send amount too small");
        totalAmount += nAmount;

        vecSend.push_back(make_pair(scriptPubKey, nAmount));
    }

    EnsureWalletIsUnlocked();

    if (fWalletUnlockMintOnly)
        throw JSONRPCError(-13, "Error: Wallet unlocked for block minting only.");

    // Check funds
    if (fFromAllAccounts)
    {
        int64 nBalance = pwalletMain->GetBalance();
        if (totalAmount > nBalance)
            throw JSONRPCError(-6, "Wallet has insufficient funds");
    }
    else
    {
        int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
        if (totalAmount > nBalance)
            throw JSONRPCError(-6, "Account has insufficient funds");
    }

    // Send
    CReserveKey keyChange(pwalletMain);
    int64 nFeeRequired = 0;
    bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
    if (!fCreated)
    {
        if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
            throw JSONRPCError(-6, "Insufficient funds");
        throw JSONRPCError(-4, "Transaction creation failed");
    }
    if (!pwalletMain->CommitTransaction(wtx, keyChange))
        throw JSONRPCError(-4, "Transaction commit failed");

    return wtx.GetHash().GetHex();
}

//
// Used by addmultisigaddress / createmultisig:
//
CScript _createmultisig(const Array& params)
{
    int nRequired = params[0].get_int();
    const Array& keys = params[1].get_array();

    // Gather public keys
    if (nRequired < 1)
        throw runtime_error("a multisignature address must require at least one key to redeem");
    if ((int)keys.size() < nRequired)
        throw runtime_error(strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
    std::vector<CPubKey> pubkeys;
    pubkeys.resize(keys.size());
    for (unsigned int i = 0; i < keys.size(); i++)
    {
        const std::string& ks = keys[i].get_str();

        // Case 1: Paycoin address and we have full public key:
        CBitcoinAddress address(ks);
        if (pwalletMain && address.IsValid())
        {
            CKeyID keyID;
            if (!address.GetKeyID(keyID))
                throw runtime_error(strprintf("%s does not refer to a key",ks.c_str()));
            CPubKey vchPubKey;
            if (!pwalletMain->GetPubKey(keyID, vchPubKey))
                throw runtime_error(strprintf("no full public key for address %s",ks.c_str()));
            if (!vchPubKey.IsFullyValid())
                throw runtime_error(" Invalid public key: "+ks);
            pubkeys[i] = vchPubKey;
        }

        // Case 2: hex public key
        else if (IsHex(ks))
        {
            CPubKey vchPubKey(ParseHex(ks));
            if (!vchPubKey.IsFullyValid())
                throw runtime_error(" Invalid public key: "+ks);
            pubkeys[i] = vchPubKey;
        }
        else
        {
            throw runtime_error(" Invalid public key: "+ks);
        }
    }
    CScript result;
    result.SetMultisig(nRequired, pubkeys);
    return result;
}

Value addmultisigaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 2 || params.size() > 3)
    {
        string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
            "Add a nrequired-to-sign multisignature address to the wallet\n"
            "each key is a Paycoin address or hex-encoded public key\n"
            "If [account] is specified, assign address to [account].";
        throw runtime_error(msg);
    }

    string strAccount;
    if (params.size() > 2)
        strAccount = AccountFromValue(params[2]);

    // Construct using pay-to-script-hash:
    CScript inner = _createmultisig(params);
    CScriptID innerID = inner.GetID();
    pwalletMain->AddCScript(inner);

    pwalletMain->SetAddressBookName(innerID, strAccount);
    return CBitcoinAddress(innerID).ToString();
}

Value createmultisig(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 2 || params.size() > 2)
    {
        string msg = "createmultisig nrequired [\"key\",...]\n"
            "\nCreates a multi-signature address with n signature of m keys required.\n"
            "It returns a json object with the address and redeemScript.\n"

            "\nArguments:\n"
            "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
            "2. \"keys\" (string, required) A json array of keys which are paycoin addresses or hex-encoded public keys\n"
            " [\n"
            " \"key\" (string) paycoin address or hex-encoded public key\n"
            " ,...\n"
            " ]\n"

            "\nResult:\n"
            "{\n"
            " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
            " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
            "}\n"

            "\nExamples:\n"
            "\nCreate a multisig address from 2 addresses\n"
            "paycoind createmultisig 2 \"[\\\"PCHAhUGKiFKDHKW8Pgw3qrp2vMfhwWjuCo\\\",\\\"PJrhyo8CUvFZQT8j67Expre2PYLhavnHXb\\\"]\""
            "\nAs a json rpc call\n"
            "curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", \"method\": \"icreatemultisig\", \"params\": [2, \"[\\\"PCHAhUGKiFKDHKW8Pgw3qrp2vMfhwWjuCo\\\",\\\"PJrhyo8CUvFZQT8j67Expre2PYLhavnHXb\\\"]\"]} -H 'content-type: text/plain;' http://127.0.0.1:9902"
        ;
        throw runtime_error(msg);
    }

    // Construct using pay-to-script-hash:
    CScript inner = _createmultisig(params);
    CScriptID innerID = inner.GetID();
    CBitcoinAddress address(innerID);

    Object result;
    result.push_back(Pair("address", address.ToString()));
    result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));

    return result;
}

struct tallyitem
{
    int64 nAmount;
    int nConf;
    tallyitem()
    {
        nAmount = 0;
        nConf = std::numeric_limits<int>::max();
    }
};

Value ListReceived(const Array& params, bool fByAccounts)
{
    // Minimum confirmations
    int nMinDepth = 1;
    if (params.size() > 0)
        nMinDepth = params[0].get_int();

    // Whether to include empty accounts
    bool fIncludeEmpty = false;
    if (params.size() > 1)
        fIncludeEmpty = params[1].get_bool();

    // Tally
    map<CBitcoinAddress, tallyitem> mapTally;
    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {
        const CWalletTx& wtx = (*it).second;

        if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
            continue;

        int nDepth = wtx.GetDepthInMainChain();
        if (nDepth < nMinDepth)
            continue;

        BOOST_FOREACH(const CTxOut& txout, wtx.vout)
        {
            CTxDestination address;
            if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
                continue;

            tallyitem& item = mapTally[address];
            item.nAmount += txout.nValue;
            item.nConf = min(item.nConf, nDepth);
        }
    }

    // Reply
    Array ret;
    map<string, tallyitem> mapAccountTally;
    BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
    {
        const CBitcoinAddress& address = item.first;
        const string& strAccount = item.second;
        map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
        if (it == mapTally.end() && !fIncludeEmpty)
            continue;

        int64 nAmount = 0;
        int nConf = std::numeric_limits<int>::max();
        if (it != mapTally.end())
        {
            nAmount = (*it).second.nAmount;
            nConf = (*it).second.nConf;
        }

        if (fByAccounts)
        {
            tallyitem& item = mapAccountTally[strAccount];
            item.nAmount += nAmount;
            item.nConf = min(item.nConf, nConf);
        }
        else
        {
            Object obj;
            obj.push_back(Pair("address",       address.ToString()));
            obj.push_back(Pair("account",       strAccount));
            obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
            obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
            ret.push_back(obj);
        }
    }

    if (fByAccounts)
    {
        for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
        {
            int64 nAmount = (*it).second.nAmount;
            int nConf = (*it).second.nConf;
            Object obj;
            obj.push_back(Pair("account",       (*it).first));
            obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));
            obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
            ret.push_back(obj);
        }
    }

    return ret;
}

Value listreceivedbyaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "listreceivedbyaddress [minconf=1] [includeempty=false]\n"
            "[minconf] is the minimum number of confirmations before payments are included.\n"
            "[includeempty] whether to include addresses that haven't received any payments.\n"
            "Returns an array of objects containing:\n"
            "  \"address\" : receiving address\n"
            "  \"account\" : the account of the receiving address\n"
            "  \"amount\" : total amount received by the address\n"
            "  \"confirmations\" : number of confirmations of the most recent transaction included");

    return ListReceived(params, false);
}

Value listreceivedbyaccount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "listreceivedbyaccount [minconf=1] [includeempty=false]\n"
            "[minconf] is the minimum number of confirmations before payments are included.\n"
            "[includeempty] whether to include accounts that haven't received any payments.\n"
            "Returns an array of objects containing:\n"
            "  \"account\" : the account of the receiving addresses\n"
            "  \"amount\" : total amount received by addresses with this account\n"
            "  \"confirmations\" : number of confirmations of the most recent transaction included");

    return ListReceived(params, true);
}

void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
    int64 nGeneratedImmature, nGeneratedMature, nFee;
    string strSentAccount;
    list<pair<CTxDestination, int64> > listReceived;
    list<pair<CTxDestination, int64> > listSent;

    wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);

    bool fAllAccounts = (strAccount == string("*"));

    // Generated blocks assigned to account ""
    if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
    {
        Object entry;
        entry.push_back(Pair("account", string("")));
        if (nGeneratedImmature)
        {
            entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
            entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
        }
        else if (wtx.IsCoinStake())
        {
            entry.push_back(Pair("category", "stake"));
            entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
        }
        else
        {
            entry.push_back(Pair("category", "generate"));
            entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
        }
        if (fLong)
            WalletTxToJSON(wtx, entry);
        ret.push_back(entry);
    }

    // Sent
    if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
    {
        BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
        {
            Object entry;
            entry.push_back(Pair("account", strSentAccount));
            entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
            entry.push_back(Pair("category", "send"));
            entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
            entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
            if (fLong)
                WalletTxToJSON(wtx, entry);
            ret.push_back(entry);
        }
    }

    // Received
    if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
    {
        BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
        {
            string account;
            if (pwalletMain->mapAddressBook.count(r.first))
                account = pwalletMain->mapAddressBook[r.first];
            if (fAllAccounts || (account == strAccount))
            {
                Object entry;
                entry.push_back(Pair("account", account));
                entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
                entry.push_back(Pair("category", "receive"));
                entry.push_back(Pair("amount", ValueFromAmount(r.second)));
                if (fLong)
                    WalletTxToJSON(wtx, entry);
                ret.push_back(entry);
            }
        }
    }
}

void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
    bool fAllAccounts = (strAccount == string("*"));

    if (fAllAccounts || acentry.strAccount == strAccount)
    {
        Object entry;
        entry.push_back(Pair("account", acentry.strAccount));
        entry.push_back(Pair("category", "move"));
        entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
        entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
        entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
        entry.push_back(Pair("comment", acentry.strComment));
        ret.push_back(entry);
    }
}

Value listtransactions(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 3)
        throw runtime_error(
            "listtransactions [account] [count=10] [from=0]\n"
            "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");

    string strAccount = "*";
    if (params.size() > 0)
        strAccount = params[0].get_str();
    int nCount = 10;
    if (params.size() > 1)
        nCount = params[1].get_int();
    int nFrom = 0;
    if (params.size() > 2)
        nFrom = params[2].get_int();

    if (nCount < 0)
        throw JSONRPCError(-8, "Negative count");
    if (nFrom < 0)
        throw JSONRPCError(-8, "Negative from");

    Array ret;
    CWalletDB walletdb(pwalletMain->strWalletFile);

    // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
    typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
    typedef multimap<int64, TxPair > TxItems;
    TxItems txByTime;

    // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
    // would make this much faster for applications that do this a lot.
    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {
        CWalletTx* wtx = &((*it).second);
        txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
    }
    list<CAccountingEntry> acentries;
    walletdb.ListAccountCreditDebit(strAccount, acentries);
    BOOST_FOREACH(CAccountingEntry& entry, acentries)
    {
        txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
    }

    // iterate backwards until we have nCount items to return:
    for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it)
    {
        CWalletTx *const pwtx = (*it).second.first;
        if (pwtx != 0)
            ListTransactions(*pwtx, strAccount, 0, true, ret);
        CAccountingEntry *const pacentry = (*it).second.second;
        if (pacentry != 0)
            AcentryToJSON(*pacentry, strAccount, ret);

        if ((int)ret.size() >= (nCount+nFrom)) break;
    }
    // ret is newest to oldest

    if (nFrom > (int)ret.size())
        nFrom = ret.size();
    if ((nFrom + nCount) > (int)ret.size())
        nCount = ret.size() - nFrom;
    Array::iterator first = ret.begin();
    std::advance(first, nFrom);
    Array::iterator last = ret.begin();
    std::advance(last, nFrom+nCount);

    if (last != ret.end()) ret.erase(last, ret.end());
    if (first != ret.begin()) ret.erase(ret.begin(), first);

    std::reverse(ret.begin(), ret.end()); // Return oldest to newest

    return ret;
}

Value listaddressbook(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "listaddressbook [all=false]\n"
            "Returns the address book. "
            "By default, only returns the wallet addresses.\n"
            "Set all=true to return entire address book."
        );
    Array ret;
    bool all = false;
    if (params.size() == 1) {
        all = params[0].get_bool();
    }
    BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& item, pwalletMain->mapAddressBook)
    {
        const CBitcoinAddress& address = item.first;
        const std::string& strName = item.second;
        bool fMine = IsMine(*pwalletMain, address.Get());
        if (!fMine && !all) continue;
        Object obj;
        obj.push_back(Pair("account", strName));
        obj.push_back(Pair("address", address.ToString()));
        ret.push_back(obj);
    }

    return ret;
}

Value listaddressgroupings(const Array& params, bool fHelp)
{
    if (fHelp)
        throw runtime_error(
            "listaddressgroupings\n"
            "Lists groups of addresses which have had their common ownership\n"
            "made public by common use as inputs or as the resulting change\n"
            "in past transactions");

    Array jsonGroupings;
    map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
    BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
    {
        Array jsonGrouping;
        BOOST_FOREACH(CTxDestination address, grouping)
        {
            Array addressInfo;
            addressInfo.push_back(CBitcoinAddress(address).ToString());
            addressInfo.push_back(ValueFromAmount(balances[address]));
            {
                LOCK(pwalletMain->cs_wallet);
                if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
                    addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
            }
            jsonGrouping.push_back(addressInfo);
        }
        jsonGroupings.push_back(jsonGrouping);
    }
    return jsonGroupings;
}

Value listaccounts(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "listaccounts [minconf=1]\n"
            "Returns Object that has account names as keys, account balances as values.");

    int nMinDepth = 1;
    if (params.size() > 0)
        nMinDepth = params[0].get_int();

    map<string, int64> mapAccountBalances;
    BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
        if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
            mapAccountBalances[entry.second] = 0;
    }

    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
    {
        const CWalletTx& wtx = (*it).second;
        int64 nGeneratedImmature, nGeneratedMature, nFee;
        string strSentAccount;
        list<pair<CTxDestination, int64> > listReceived;
        list<pair<CTxDestination, int64> > listSent;
        wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
        mapAccountBalances[strSentAccount] -= nFee;
        BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
            mapAccountBalances[strSentAccount] -= s.second;
        if (wtx.GetDepthInMainChain() >= nMinDepth)
        {
            mapAccountBalances[""] += nGeneratedMature;
            BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
                if (pwalletMain->mapAddressBook.count(r.first))
                    mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
                else
                    mapAccountBalances[""] += r.second;
        }
    }

    list<CAccountingEntry> acentries;
    CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
    BOOST_FOREACH(const CAccountingEntry& entry, acentries)
        mapAccountBalances[entry.strAccount] += entry.nCreditDebit;

    Object ret;
    BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
        ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
    }
    return ret;
}

Value listsinceblock(const Array& params, bool fHelp)
{
    if (fHelp)
        throw runtime_error(
            "listsinceblock [blockhash] [target-confirmations]\n"
            "Get all transactions in blocks since block [blockhash], or all transactions if omitted");

    CBlockIndex *pindex = NULL;
    int target_confirms = 1;

    if (params.size() > 0)
    {
        uint256 blockId = 0;

        blockId.SetHex(params[0].get_str());
        pindex = CBlockLocator(blockId).GetBlockIndex();
    }

    if (params.size() > 1)
    {
        target_confirms = params[1].get_int();

        if (target_confirms < 1)
            throw JSONRPCError(-8, "Invalid parameter");
    }

    int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;

    Array transactions;

    for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
    {
        CWalletTx tx = (*it).second;

        if (depth == -1 || tx.GetDepthInMainChain() < depth)
            ListTransactions(tx, "*", 0, true, transactions);
    }

    uint256 lastblock;

    if (target_confirms == 1)
    {
        lastblock = hashBestChain;
    }
    else
    {
        int target_height = pindexBest->nHeight + 1 - target_confirms;

        CBlockIndex *block;
        for (block = pindexBest;
             block && block->nHeight > target_height;
             block = block->pprev)  { }

        lastblock = block ? block->GetBlockHash() : 0;
    }

    Object ret;
    ret.push_back(Pair("transactions", transactions));
    ret.push_back(Pair("lastblock", lastblock.GetHex()));

    return ret;
}

Value gettransaction(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "gettransaction <txid>\n"
            "Get detailed information about <txid>");

    uint256 hash;
    hash.SetHex(params[0].get_str());

    Object entry;

    if (!pwalletMain->mapWallet.count(hash))
        throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
    const CWalletTx& wtx = pwalletMain->mapWallet[hash];

    int64 nCredit = wtx.GetCredit();
    int64 nDebit = wtx.GetDebit();
    int64 nNet = nCredit - nDebit;
    int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);

    entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
    if (wtx.IsFromMe())
        entry.push_back(Pair("fee", ValueFromAmount(nFee)));

    WalletTxToJSON(pwalletMain->mapWallet[hash], entry);

    Array details;
    ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
    entry.push_back(Pair("details", details));

    return entry;
}

Value backupwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "backupwallet <destination>\n"
            "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");

    string strDest = params[0].get_str();
    BackupWallet(*pwalletMain, strDest);

    return Value::null;
}

Value keypoolrefill(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 0)
        throw runtime_error(
            "keypoolrefill\n"
            "Fills the keypool."
            + HelpRequiringPassphrase());

    EnsureWalletIsUnlocked();

    pwalletMain->TopUpKeyPool();

    if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
        throw JSONRPCError(-4, "Error refreshing keypool.");

    return Value::null;
}

void ThreadTopUpKeyPool(void* parg)
{
    pwalletMain->TopUpKeyPool();
}

void ThreadCleanWalletPassphrase(void* parg)
{
    int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;

    ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);

    if (nWalletUnlockTime == 0)
    {
        nWalletUnlockTime = nMyWakeTime;

        do
        {
            if (nWalletUnlockTime==0)
                break;
            int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
            if (nToSleep <= 0)
                break;

            LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
            Sleep(nToSleep);
            ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);

        } while(1);

        if (nWalletUnlockTime)
        {
            nWalletUnlockTime = 0;
            pwalletMain->Lock();
        }
    }
    else
    {
        if (nWalletUnlockTime < nMyWakeTime)
            nWalletUnlockTime = nMyWakeTime;
    }

    LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);

    delete (int64*)parg;
}

Value walletpassphrase(const Array& params, bool fHelp)
{
    if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
        throw runtime_error(
            "walletpassphrase <passphrase> <timeout> [mintonly]\n"
            "Stores the wallet decryption key in memory for <timeout> seconds.\n"
            "mintonly is optional true/false allowing only block minting.");
    if (fHelp)
        return true;
    if (!pwalletMain->IsCrypted())
        throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.");

    if (!pwalletMain->IsLocked())
        throw JSONRPCError(-17, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");

    // Note that the walletpassphrase is stored in params[0] which is not mlock()ed
    SecureString strWalletPass;
    strWalletPass.reserve(100);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make params[0] mlock()'d to begin with.
    strWalletPass = params[0].get_str().c_str();

    if (strWalletPass.length() > 0)
    {
        if (!pwalletMain->Unlock(strWalletPass))
            throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
    }
    else
        throw runtime_error(
            "walletpassphrase <passphrase> <timeout>\n"
            "Stores the wallet decryption key in memory for <timeout> seconds.");

    NewThread(ThreadTopUpKeyPool, NULL);
    int64* pnSleepTime = new int64(params[1].get_int64());
    NewThread(ThreadCleanWalletPassphrase, pnSleepTime);

    // paycoin: if user OS account compromised prevent trivial sendmoney commands
    if (params.size() > 2)
        fWalletUnlockMintOnly = params[2].get_bool();
    else
        fWalletUnlockMintOnly = false;

    return Value::null;
}

Value walletpassphrasechange(const Array& params, bool fHelp)
{
    if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
        throw runtime_error(
            "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
            "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
    if (fHelp)
        return true;
    if (!pwalletMain->IsCrypted())
        throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");

    // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make params[0] mlock()'d to begin with.
    SecureString strOldWalletPass;
    strOldWalletPass.reserve(100);
    strOldWalletPass = params[0].get_str().c_str();

    SecureString strNewWalletPass;
    strNewWalletPass.reserve(100);
    strNewWalletPass = params[1].get_str().c_str();

    if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
        throw runtime_error(
            "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
            "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");

    if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
        throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");

    return Value::null;
}

Value walletlock(const Array& params, bool fHelp)
{
    if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
        throw runtime_error(
            "walletlock\n"
            "Removes the wallet encryption key from memory, locking the wallet.\n"
            "After calling this method, you will need to call walletpassphrase again\n"
            "before being able to call any methods which require the wallet to be unlocked.");
    if (fHelp)
        return true;
    if (!pwalletMain->IsCrypted())
        throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletlock was called.");

    {
        LOCK(cs_nWalletUnlockTime);
        pwalletMain->Lock();
        nWalletUnlockTime = 0;
    }

    return Value::null;
}

Value encryptwallet(const Array& params, bool fHelp)
{
    if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
        throw runtime_error(
            "encryptwallet <passphrase>\n"
            "Encrypts the wallet with <passphrase>.");
    if (fHelp)
        return true;
    if (pwalletMain->IsCrypted())
        throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called.");

    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make params[0] mlock()'d to begin with.
    SecureString strWalletPass;
    strWalletPass.reserve(100);
    strWalletPass = params[0].get_str().c_str();

    if (strWalletPass.length() < 1)
        throw runtime_error(
            "encryptwallet <passphrase>\n"
            "Encrypts the wallet with <passphrase>.");

    if (!pwalletMain->EncryptWallet(strWalletPass))
        throw JSONRPCError(-16, "Error: Failed to encrypt the wallet.");

    // BDB seems to have a bad habit of writing old data into
    // slack space in .dat files; that is bad if the old data is
    // unencrypted private keys.  So:
    StartShutdown();
    return "wallet encrypted; Paycoin server stopping, restart to run with encrypted wallet";
}

class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
    Object operator()(const CNoDestination &dest) const { return Object(); }

    Object operator()(const CKeyID &keyID) const {
        Object obj;
        CPubKey vchPubKey;
        pwalletMain->GetPubKey(keyID, vchPubKey);
        obj.push_back(Pair("isscript", false));
        obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
        obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
        return obj;
    }

    Object operator()(const CScriptID &scriptID) const {
        Object obj;
        obj.push_back(Pair("isscript", true));
        CScript subscript;
        pwalletMain->GetCScript(scriptID, subscript);
        std::vector<CTxDestination> addresses;
        txnouttype whichType;
        int nRequired;
        ExtractDestinations(subscript, whichType, addresses, nRequired);
        obj.push_back(Pair("script", GetTxnOutputType(whichType)));
        Array a;
        BOOST_FOREACH(const CTxDestination& addr, addresses)
            a.push_back(CBitcoinAddress(addr).ToString());
        obj.push_back(Pair("addresses", a));
        if (whichType == TX_MULTISIG)
            obj.push_back(Pair("sigsrequired", nRequired));
        return obj;
    }
};

Value validateaddress(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "validateaddress <paycoinaddress>\n"
            "Return information about <paycoinaddress>.");

    CBitcoinAddress address(params[0].get_str());
    bool isValid = address.IsValid();

    Object ret;
    ret.push_back(Pair("isvalid", isValid));
    if (isValid)
    {
        CTxDestination dest = address.Get();
        string currentAddress = address.ToString();
        ret.push_back(Pair("address", currentAddress));
        bool fMine = IsMine(*pwalletMain, dest);
        ret.push_back(Pair("ismine", fMine));
        if (fMine) {
            Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
            ret.insert(ret.end(), detail.begin(), detail.end());
        }
        if (pwalletMain->mapAddressBook.count(dest))
            ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
    }
    return ret;
}

// paycoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "reservebalance [<reserve> [amount]]\n"
            "<reserve> is true or false to turn balance reserve on or off.\n"
            "<amount> is a real and rounded to cent.\n"
            "Set reserve amount not participating in network protection.\n"
            "If no parameters provided current setting is printed.\n");

    if (params.size() > 0)
    {
        bool fReserve = params[0].get_bool();
        if (fReserve)
        {
            if (params.size() == 1)
                throw runtime_error("must provide amount to reserve balance.\n");
            int64 nAmount = AmountFromValue(params[1]);
            nAmount = (nAmount / CENT) * CENT;  // round to cent
            if (nAmount < 0)
                throw runtime_error("amount cannot be negative.\n");
            mapArgs["-reservebalance"] = FormatMoney(nAmount).c_str();
        }
        else
        {
            if (params.size() > 1)
                throw runtime_error("cannot specify amount to turn off reserve.\n");
            mapArgs["-reservebalance"] = "0";
        }
    }

    Object result;
    int64 nReserveBalance = 0;
    if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
        throw runtime_error("invalid reserve balance amount\n");
    result.push_back(Pair("reserve", (nReserveBalance > 0)));
    result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
    return result;
}

// paycoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 0)
        throw runtime_error(
            "checkwallet\n"
            "Check wallet for integrity.\n");

    int nMismatchSpent;
    int64 nBalanceInQuestion;
    pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
    Object result;
    if (nMismatchSpent == 0)
        result.push_back(Pair("wallet check passed", true));
    else
    {
        result.push_back(Pair("mismatched spent coins", nMismatchSpent));
        result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
    }
    return result;
}

// paycoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 0)
        throw runtime_error(
            "repairwallet\n"
            "Repair wallet if checkwallet reports any problem.\n");

    int nMismatchSpent;
    int64 nBalanceInQuestion;
    pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
    Object result;
    if (nMismatchSpent == 0)
        result.push_back(Pair("wallet check passed", true));
    else
    {
        result.push_back(Pair("mismatched spent coins", nMismatchSpent));
        result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
    }
    return result;
}

// paycoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "makekeypair [prefix]\n"
            "Make a public/private key pair.\n"
            "[prefix] is optional preferred prefix for the public key.\n");

    string strPrefix = "";
    if (params.size() > 0)
        strPrefix = params[0].get_str();

    CKey key;
    int nCount = 0;
    do
    {
        key.MakeNewKey(false);
        nCount++;
    } while (nCount < 10000 && strPrefix != HexStr(key.GetPubKey().Raw()).substr(0, strPrefix.size()));

    if (strPrefix != HexStr(key.GetPubKey().Raw()).substr(0, strPrefix.size()))
        return Value::null;

    CPrivKey vchPrivKey = key.GetPrivKey();
    Object result;
    result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
    result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
    return result;
}

Value clearorphans(const Array& params, bool fHelp)
{
    if (fHelp || params.size() !=0)
        throw runtime_error(
            "clearorphans\n"
            "Clears orphaned transactions from the wallet file.");

    pwalletMain->ClearOrphans();

    return true;
}

Value listmicroprimedata(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "listmicroprimedata <address>\n"
            "List the data regarding a given microprime address (only lists\n"
            "valid addresses found in wallet).");

    string strAddress = params[0].get_str();
    CBitcoinAddress address(strAddress);

    if (!IsMine(*pwalletMain, address.Get()))
        throw runtime_error("Address must be in wallet.");

    if (!primeNodeDB->CheckMicroPrime(strAddress))
        throw runtime_error("Address is not a valid microprime address.");

    int primeNodeRate;
    int64 group;
    CScript scriptMPAddress;
    scriptMPAddress.SetDestination(address.Get());
    if (!primeNodeDB->IsMicroPrime(scriptMPAddress, primeNodeRate, group, GetTime()))
        throw runtime_error("Address is not a valid microprime address.");

    Object obj;
    obj.push_back(Pair("Address", strAddress));
    obj.push_back(Pair("Current stake rate", primeNodeRate));
    obj.push_back(Pair("Max balance", (int)group));

    return obj;
}


text:
$(document).ready(function(){
    $('.profile-popup').hover(function(){
        $('body').append('

');
        var img_link = $(this).data('pic');
        var content = $(this).data('info');
        var popup_img = '

';
        var popup_info = '

'+content+'

';
        $('.profile-box').html(popup_img + popup_info);
        var total_left = $(this).offset().left + $(this).width() + 20;
        if (total_left < $(window).width() + 270)
        {        //showing on left

            var left = total_left + 10;
        }
        else{
            var left = $(this).offset().left - 260;
        }
        var top = $(this).offset().top;
        $('.profile-box').css({
            'top': top + 'px',
            'left': left + 'px'
        }).fadeIn('fast').addClass('on');
    }, function(){
        $('.profile-box').remove();
    })

})

redpajama_set_name: RedPajamaGithub


text:
url: /addons
title: Add-ons
description: Learn about add-ons and how they are related to Auth0-registered Applications.
topics:
  - applications
  - add-ons
contentType:
  - concept
  - index
useCase:
  - build-an-app
  - integrate-third-party-apps
---

# Add-ons

<%= include('../_includes/_uses-delegation') %>

Add-ons are plugins associated with an application registered with Auth0. Usually, they are third-party APIs used by application(s) for which Auth0 generates Access Tokens (e.g., Salesforce, Azure Service Bus, Windows Azure Mobile Services, SAP).

Some typical scenarios for using add-ons include:

* **Accessing External APIs**: Using the Delegation endpoint, you can exchange your application's Access Token for a third-party service's (e.g., Salesforce, Amazon) Access Token.

* **Integrating with Applications using SAML2/WS-Federation**: Since Add-ons allow you to configure every aspect of the SAML2/WS-Federation integration, they allow you to integrate with any custom or <dfn data-key="single-sign-on">Single Sign-on (SSO)</dfn> integration that does not currently enjoy built-in Auth0 support.

![Addons Example Diagram](/media/articles/applications/applications-addon-types.png)

## Available Add-ons

- Amazon Web Services
- Firebase
- Layer
- Salesforce
- Salesforce (Sandbox)
- SAP
- Azure Mobile Services
- Azure Service Bus
- Azure Blob Storage
- SAML2
- WS-Fed

## Keep reading

- [View Add-ons](/dashboard/guides/applications/view-addons)
- [Set Up Add-Ons](/dashboard/guides/applications/set-up-addons)


text:
package learning.sfa;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.sat4j.specs.TimeoutException;

import automata.sfa.SFA;
import theory.intervals.IntPred;

public class IOOracle extends Oracle<IntPred, Integer> {

	private Scanner sc;

	public IOOracle() {
		sc = new Scanner(System.in);
	}

	@Override
	public List<Integer> checkEquivalenceImpl(SFA<IntPred, Integer> compareTo) throws TimeoutException {
		List<Integer> ret = new ArrayList<Integer>();
		System.out.println(compareTo);
		System.out.println("Is that your automaton? (y/n):");
		char in = sc.nextLine().charAt(0);
		if (in == 'y')
			return null;
		System.out.println("Enter counterexample string a1,a2,a3... :");
		String cex = sc.nextLine();
		for (String s : cex.split(","))
			ret.add(Integer.parseInt(s));
		return ret;
	}

	@Override
	public boolean checkMembershipImpl(List<Integer> w) {
		System.out.println("Does your automaton accept " + w + " ? (y/n):");
		char in = sc.nextLine().charAt(0);
		return in == 'y';
	}

}


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, Emory University,
*  the University of Minnesota Supercomputing Institute
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-grid-incubation/LICENSE.txt for details.
*============================================================================
**/
/**
*============================================================================
*============================================================================
**/
package org.cagrid.introduce.service1.common;

import java.rmi.RemoteException;

/**
 * This class is autogenerated, DO NOT EDIT.
 *
 * This interface represents the API which is accessable on the grid service from the client.
 *
 * @created by Introduce Toolkit version 1.1
 *
 */
public interface Service1I {

  public org.cagrid.worklfow.service1.types.StringAndItsLenght generateData(java.lang.String info) throws RemoteException ;

  public org.cagrid.worklfow.service1.types.StringAndItsLenght secureGenerateData(java.lang.String info) throws RemoteException ;

}


text:
<?php

interface Calling {

    public function callToOtherPhones(string $number);
}

interface Browsing {

    public function browsingInWWW(string $URL);
}

class Smartphone implements Calling, Browsing {

    public function browsingInWWW(string $URL) {
        if (preg_match('/[0-9]/', $URL) != 0) {
            throw new Exception("Invalid URL!" . PHP_EOL);
        }
        echo 'Browsing: ' . $URL . '!' . PHP_EOL;
    }

    public function callToOtherPhones(string $number) {
        if (!ctype_digit($number)) {
            throw new Exception("Invalid number!" . PHP_EOL);
        }
        echo 'Calling... ' . $number . PHP_EOL;
    }

}

$numbers = fgets(STDIN);
$arrayNumbers = explode(' ', $numbers);
$urls = fgets(STDIN);
$arrayURLs = explode(' ', $urls);
$smartphone = new Smartphone();
foreach ($arrayNumbers as $number) {
    try {
        $smartphone->callToOtherPhones(trim($number));
    } catch (Exception $exc) {
        echo $exc->getMessage();
    }
}

foreach ($arrayURLs as $URL) {
    try {
        $smartphone->browsingInWWW(trim($URL));
    } catch (Exception $exc) {
        echo $exc->getMessage();
    }
}


text:
<?php

namespace Pingpong\Trusty;

use Illuminate\Support\ServiceProvider;

class TrustyServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Boot the package.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/src/migrations/' => base_path('/database/migrations'),
            __DIR__.'/src/config/config.php' => config_path('trusty.php'),
        ]);
        $this->mergeConfigFrom(__DIR__.'/src/config/config.php', 'trusty');
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->app['trusty'] = $this->app->share(function ($app) {
            $auth = $app['auth']->driver();

            return new Trusty($auth, $app['router']);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('trusty');
    }
}


text:
"use strict";

var info = require("./cli-info");

/**
 * $ browser-sync init
 *
 * This command will generate a configuration
 * file in the current directory
 *
 * @param opts
 */
module.exports = function(opts) {
    info.makeConfig(process.cwd(), opts.cb);
};


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>DllNames | win32-api</title>
	<meta name="description" content="Documentation for win32-api">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					win32-api

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited

					Menu

					Globals

					"model"

					DllNames

Enumeration DllNames

Index

Enumeration members

comctl32

kernel32

ntdll

user32

Enumeration members

comctl32

comctl32:  = "comctl32"

Defined in model.ts:3

kernel32

kernel32:  = "kernel32"

Defined in model.ts:4

ntdll

ntdll:  = "ntdll"

Defined in model.ts:5

user32

user32:  = "user32"

Defined in model.ts:6

						Globals

						"model"

						Dll<wbr>Names

								comctl32

								kernel32

								ntdll

								user32

Legend

Enumeration

Generated using TypeDoc


text:
namespace AjScript.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using AjScript.Commands;
    using AjScript.Expressions;
    using AjScript.Interpreter;
    using AjScript.Language;
    using AjScript.Primitives;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class EvaluationTests
    {
        private Machine machine;

        [TestInitialize]
        public void Setup()
        {
            this.machine = new Machine();
        }

        [TestMethod]
        public void GetInteger()
        {
            Assert.AreEqual(3, this.EvaluateExpression("3"));
        }

        [TestMethod]
        public void GetNegativeInteger()
        {
            Assert.AreEqual(-3, this.EvaluateExpression("-3"));
        }

        [TestMethod]
        public void GetReal()
        {
            Assert.AreEqual(3.14, this.EvaluateExpression("3.14"));
        }

        [TestMethod]
        public void GetNegativeReal()
        {
            Assert.AreEqual(-3.14, this.EvaluateExpression("-3.14"));
        }

        [TestMethod]
        public void AddSimpleExpression()
        {
            Assert.AreEqual(3, this.EvaluateExpression("1+2"));
        }

        [TestMethod]
        public void AddRealsSimpleExpression()
        {
            Assert.AreEqual(1.2 + 3.4, this.EvaluateExpression("1.2+3.4"));
        }

        [TestMethod]
        public void ArithmeticSimpleExpressionWithPrecedence()
        {
            Assert.AreEqual(7, this.EvaluateExpression("1+2*3"));
        }

        [TestMethod]
        public void ArithmeticSimpleExpressionWithParenthesis()
        {
            Assert.AreEqual(9, this.EvaluateExpression("(1+2)*3"));
        }

        [TestMethod]
        public void DivideIntegers()
        {
            Assert.AreEqual(3, this.EvaluateExpression("9/3"));
            Assert.AreEqual(1.0 / 2.0, this.EvaluateExpression("1/2"));
        }

        [TestMethod]
        public void GetNull()
        {
            Assert.IsNull(this.EvaluateExpression("null"));
        }

        [TestMethod]
        public void ConcatenateNull()
        {
            Assert.AreEqual("foonull", this.EvaluateExpression("'foo' + null"));
            Assert.AreEqual("nullfoo", this.EvaluateExpression("null + 'foo'"));
        }

        [TestMethod]
        public void AddNull()
        {
            Assert.AreEqual(10, this.EvaluateExpression("10 + null"));
            Assert.AreEqual(10, this.EvaluateExpression("null + 10"));
        }

        [TestMethod]
        public void GetUndefined()
        {
            Assert.AreSame(Undefined.Instance, this.EvaluateExpression("undefined"));
        }

        [TestMethod]
        public void EvaluateStringToUpperCase()
        {
            Assert.AreEqual("FOO", this.EvaluateExpression("'foo'.toUpperCase()"));
        }

        [TestMethod]
        public void EvaluateStringToLowerCase()
        {
            Assert.AreEqual("foo", this.EvaluateExpression("'Foo'.toLowerCase()"));
        }

        [TestMethod]
        public void EvaluateStringSubstring()
        {
            Assert.AreEqual("oo", this.EvaluateExpression("'foobar'.substring(1, 3)"));
            Assert.AreEqual("obar", this.EvaluateExpression("'foobar'.substring(2)"));
            Assert.AreEqual("foobar", this.EvaluateExpression("'foobar'.substring()"));
            Assert.AreEqual("foobar", this.EvaluateExpression("'foobar'.substring(-10, 100)"));
        }

        [TestMethod]
        public void EvaluateStringSubstr()
        {
            Assert.AreEqual("oobar", this.EvaluateExpression("'foobar'.substr(1)"));
            Assert.AreEqual("foobar", this.EvaluateExpression("'foobar'.substr(0)"));
            Assert.AreEqual(string.Empty, this.EvaluateExpression("'foobar'.substr(10)"));
            Assert.AreEqual("bar", this.EvaluateExpression("'foobar'.substr(-3)"));
            Assert.AreEqual("ba", this.EvaluateExpression("'foobar'.substr(-3, 2)"));
            Assert.AreEqual("foobar", this.EvaluateExpression("'foobar'.substr(-10)"));
            Assert.AreEqual("oob", this.EvaluateExpression("'foobar'.substr(1, 3)"));
            Assert.AreEqual(string.Empty, this.EvaluateExpression("'foobar'.substr(1, 0)"));
            Assert.AreEqual(string.Empty, this.EvaluateExpression("'foobar'.substr(1, -2)"));
        }

        [TestMethod]
        public void EvaluateStringIndexOf()
        {
            Assert.AreEqual(3, this.EvaluateExpression("'foobar'.indexOf('bar')"));
            Assert.AreEqual(-1, this.EvaluateExpression("'foobar'.indexOf('boo')"));
            Assert.AreEqual(1, this.EvaluateExpression("'foobar'.indexOf('o')"));
            Assert.AreEqual(2, this.EvaluateExpression("'foobar'.indexOf('o', 2)"));
        }

        [TestMethod]
        public void EvaluateStringLastIndexOf()
        {
            Assert.AreEqual(3, this.EvaluateExpression("'foobar'.lastIndexOf('bar')"));
            Assert.AreEqual(-1, this.EvaluateExpression("'foobar'.lastIndexOf('boo')"));
            Assert.AreEqual(2, this.EvaluateExpression("'foobar'.lastIndexOf('o')"));
            Assert.AreEqual(1, this.EvaluateExpression("'foobar'.lastIndexOf('o', 1)"));
            Assert.AreEqual(-1, this.EvaluateExpression("'foobar'.lastIndexOf('o', 0)"));
        }

        [TestMethod]
        public void EvaluateStringSlice()
        {
            Assert.AreEqual("oobar", this.EvaluateExpression("'foobar'.slice(1)"));
            Assert.AreEqual("oob", this.EvaluateExpression("'foobar'.slice(1, 4)"));
            Assert.AreEqual("bar", this.EvaluateExpression("'foobar'.slice(-3)"));
            Assert.AreEqual("ooba", this.EvaluateExpression("'foobar'.slice(1, -1)"));
        }

        [TestMethod]
        public void EvaluateStringLength()
        {
            Assert.AreEqual(6, this.EvaluateExpression("'foobar'.length"));
            Assert.AreEqual(0, this.EvaluateExpression("''.length"));
            Assert.AreEqual(3, this.EvaluateExpression("'foo'.length"));
        }

        [TestMethod]
        public void EvaluateStringCharAt()
        {
            Assert.AreEqual("f", this.EvaluateExpression("'foobar'.charAt(0)"));
            Assert.AreEqual("b", this.EvaluateExpression("'foobar'.charAt(3)"));
            Assert.AreEqual(string.Empty, this.EvaluateExpression("'foobar'.charAt(-2)"));
            Assert.AreEqual(string.Empty, this.EvaluateExpression("'foobar'.charAt(100)"));
        }

        [TestMethod]
        public void EvaluateStringConcat()
        {
            Assert.AreEqual("foobar", this.EvaluateExpression("'foo'.concat('bar')"));
            Assert.AreEqual("foo", this.EvaluateExpression("'foo'.concat()"));
            Assert.AreEqual("foo42", this.EvaluateExpression("'foo'.concat(42)"));
            Assert.AreEqual("hello, world", this.EvaluateExpression("'hello'.concat(', ', 'world')"));
            Assert.AreEqual("foonull", this.EvaluateExpression("'foo'.concat(null)"));
        }

        [TestMethod]
        public void EvaluateVar()
        {
            this.EvaluateCommands("var x;");
            Assert.AreEqual(Undefined.Instance, this.machine.Context.GetValue("x"));
        }

        [TestMethod]
        public void DefineVar()
        {
            this.EvaluateCommands("var x=1;");
            Assert.AreEqual(1, this.machine.Context.GetValue("x"));
        }

        [TestMethod]
        public void DefineVarWithInitialValue()
        {
            this.EvaluateCommands("var x=1+2;");
            Assert.AreEqual(3, this.machine.Context.GetValue("x"));
        }

        [TestMethod]
        public void DefineVarWithInitialExpressionValue()
        {
            this.EvaluateCommands("var x=1+2;");
            Assert.AreEqual(3, this.machine.Context.GetValue("x"));
        }

        [TestMethod]
        public void SetUndefinedVar()
        {
            this.EvaluateCommands("x = 1+2;");
            Assert.AreEqual(3, this.machine.Context.GetValue("x"));
        }

        [TestMethod]
        public void PreIncrementVar()
        {
            this.EvaluateCommands("var x = 0; y = ++x;");
            Assert.AreEqual(1, this.machine.Context.GetValue("x"));
            Assert.AreEqual(1, this.machine.Context.GetValue("y"));
        }

        [TestMethod]
        public void PostIncrementVar()
        {
            this.EvaluateCommands("var x = 0; y = x++;");
            Assert.AreEqual(1, this.machine.Context.GetValue("x"));
            Assert.AreEqual(0, this.machine.Context.GetValue("y"));
        }

        [TestMethod]
        public void EmptyObject()
        {
            object result = this.EvaluateExpression("{}");

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(IObject));
        }

        [TestMethod]
        public void Typeof()
        {
            Assert.AreEqual("object", this.EvaluateExpression("typeof {}"));
            Assert.AreEqual("object", this.EvaluateExpression("typeof []"));
            Assert.AreEqual("number", this.EvaluateExpression("typeof 42"));
            Assert.AreEqual("number", this.EvaluateExpression("typeof 3.14159"));
            Assert.AreEqual("null", this.EvaluateExpression("typeof null"));
            Assert.AreEqual("undefined", this.EvaluateExpression("typeof undefined"));
        }

        [TestMethod]
        public void IsArray()
        {
            Assert.AreEqual(true, this.EvaluateExpression("Array.isArray([])"));
            Assert.AreEqual(true, this.EvaluateExpression("Array.isArray([1, 2, 3])"));

            Assert.AreEqual(false, this.EvaluateExpression("Array.isArray({})"));
            Assert.AreEqual(false, this.EvaluateExpression("Array.isArray(42)"));
            Assert.AreEqual(false, this.EvaluateExpression("Array.isArray('foo')"));
            Assert.AreEqual(false, this.EvaluateExpression("Array.isArray(null)"));
            Assert.AreEqual(false, this.EvaluateExpression("Array.isArray(undefined)"));
        }

        [TestMethod]
        public void PreDecrementVar()
        {
            this.EvaluateCommands("var x = 0; y = --x;");
            Assert.AreEqual(-1, this.machine.Context.GetValue("x"));
            Assert.AreEqual(-1, this.machine.Context.GetValue("y"));
        }

        [TestMethod]
        public void PostDecrementVar()
        {
            this.EvaluateCommands("var x = 0; y = x--;");
            Assert.AreEqual(-1, this.machine.Context.GetValue("x"));
            Assert.AreEqual(0, this.machine.Context.GetValue("y"));
        }

        [TestMethod]
        public void SimpleFor()
        {
            this.EvaluateCommands("var y = 1; for (var x=1; x<4; x++) y = y*x;");
            Assert.AreEqual(4, this.machine.Context.GetValue("x"));
            Assert.AreEqual(6, this.machine.Context.GetValue("y"));
        }

        [TestMethod]
        public void SimpleForWithBlock()
        {
            this.EvaluateCommands("var y = 1; for (var x=1; x<4; x++) { y = y*x; y = y*2; }");
            Assert.AreEqual(4, this.machine.Context.GetValue("x"));
            Assert.AreEqual(48, this.machine.Context.GetValue("y"));
        }

        [TestMethod]
        public void IntegerToString()
        {
            Assert.AreEqual("42", this.EvaluateExpression("42.toString()"));
        }

        [TestMethod]
        public void StringToString()
        {
            Assert.AreEqual("foo", this.EvaluateExpression("'foo'.toString()"));
        }

        [TestMethod]
        public void EmptyToString()
        {
            Assert.AreEqual("[object Object]", this.EvaluateExpression("{}.toString()"));
        }

        [TestMethod]
        public void AddFunction()
        {
            Assert.AreEqual(3, this.EvaluateExpression("function (x) { return x+1;} (2)"));
        }

        [TestMethod]
        public void DefineAndEvaluateAddFunction()
        {
            this.EvaluateCommands("var add1 = function (x) { return x+1;}; result = add1(2);");
            Assert.AreEqual(3, this.machine.Context.GetValue("result"));
        }

        [TestMethod]
        public void DefineAndEvaluateFunctionWithClosure()
        {
            this.EvaluateCommands("var addx = function (x) { return function(y) { return x+y;}; }; result = addx(2)(3);");
            Assert.AreEqual(5, this.machine.Context.GetValue("result"));
        }

        [TestMethod]
        public void NewObject()
        {
            object result = this.EvaluateExpression("new Object()");
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(IObject));
        }

        [TestMethod]
        public void NewObjectUsingPrototype()
        {
            this.EvaluateCommands("var x = new Object(); Object.prototype.y = 10; result = x.y;");
            Assert.AreEqual(10, this.machine.Context.GetValue("result"));
        }

        [TestMethod]
        public void NewEmptyObjectUsingPrototype()
        {
            this.EvaluateCommands("var x = {}; Object.prototype.y = 10; result = x.y;");
            Assert.AreEqual(10, this.machine.Context.GetValue("result"));
        }

        [TestMethod]
        public void SetValueUsingArrayNotation()
        {
            this.EvaluateCommands("var x = new Object(); x['y'] = 10; result = x.y;");
            Assert.AreEqual(10, this.machine.Context.GetValue("result"));
        }

        [TestMethod]
        public void NewDirectoryInfo()
        {
            var expr = this.EvaluateExpression("new System.IO.DirectoryInfo('.')");
            Assert.IsNotNull(expr);
            Assert.IsInstanceOfType(expr, typeof(System.IO.DirectoryInfo));
        }

        [TestMethod]
        public void EvaluateSimpleBooleans()
        {
            Assert.AreEqual(true, this.EvaluateExpression("true && true"));
            Assert.AreEqual(true, this.EvaluateExpression("false || true"));
            Assert.AreEqual(false, this.EvaluateExpression("true && false"));
            Assert.AreEqual(false, this.EvaluateExpression("false || false"));
        }

        [TestMethod]
        public void EvaluateFunctionWithGlobalThis()
        {
            this.EvaluateCommands("function Person() { this.name = 'Adam'; this.age = 800; }");
            this.EvaluateExpression("Person()");
            Assert.AreEqual("Adam", this.machine.Context.GetValue("name"));
            Assert.AreEqual(800, this.machine.Context.GetValue("age"));
        }

        [TestMethod]
        public void EvaluateFunctionUsingCallWithOneParameterAsThis()
        {
            this.EvaluateCommands("function Person() { this.name = 'Adam'; this.age = 800; }");
            this.EvaluateCommands("var adam = {};");
            this.EvaluateExpression("Person.call(adam)");
            Assert.AreEqual("Adam", this.EvaluateExpression("adam.name"));
            Assert.AreEqual(800, this.EvaluateExpression("adam.age"));
        }

        [TestMethod]
        public void EvaluateFunctionUsingCallWithParameters()
        {
            this.EvaluateCommands("function MakePerson(name, age) { this.name = name; this.age = age; }");
            this.EvaluateCommands("var adam = {};");
            this.EvaluateExpression("MakePerson.call(adam, ['Adam', 800])");
            Assert.AreEqual("Adam", this.EvaluateExpression("adam.name"));
            Assert.AreEqual(800, this.EvaluateExpression("adam.age"));
        }

        [TestMethod]
        public void EvaluateFunctionUsingApplyWithOneParameterAsThis()
        {
            this.EvaluateCommands("function Person() { this.name = 'Adam'; this.age = 800; }");
            this.EvaluateCommands("var adam = {};");
            this.EvaluateExpression("Person.apply(adam)");
            Assert.AreEqual("Adam", this.EvaluateExpression("adam.name"));
            Assert.AreEqual(800, this.EvaluateExpression("adam.age"));
        }

        [TestMethod]
        public void EvaluateFunctionUsingApplyWithParameters()
        {
            this.EvaluateCommands("function MakePerson(name, age) { this.name = name; this.age = age; }");
            this.EvaluateCommands("var adam = {};");
            this.EvaluateExpression("MakePerson.apply(adam, 'Adam', 800)");
            Assert.AreEqual("Adam", this.EvaluateExpression("adam.name"));
            Assert.AreEqual(800, this.EvaluateExpression("adam.age"));
        }

        [TestMethod]
        public void EvaluateNewWithFunction()
        {
            this.EvaluateCommands("function foo() { this.name = 'Adam'; this.age = 800; }");
            object result = this.EvaluateExpression("new foo()");
            Assert.IsInstanceOfType(result, typeof(IObject));
            IObject obj = (IObject)result;

            Assert.AreEqual("Adam", obj.GetValue("name"));
            Assert.AreEqual(800, obj.GetValue("age"));
        }

        [TestMethod]
        public void EvaluateNewWithObjectFunction()
        {
            this.EvaluateCommands("var obj = new Object(); obj.foo = function() { this.name = 'Adam'; this.age = 800; };");
            object result = this.EvaluateExpression("new obj.foo()");
            Assert.IsInstanceOfType(result, typeof(IObject));
            IObject obj = (IObject)result;

            Assert.AreEqual("Adam", obj.GetValue("name"));
            Assert.AreEqual(800, obj.GetValue("age"));
        }

        [TestMethod]
        public void NewObjectWithPrototype()
        {
            this.EvaluateCommands("function Person() { this.name = 'Adam'; }");
            this.EvaluateCommands("Person.prototype.age = 800; var adam = new Person();");
            Assert.AreEqual(800, this.EvaluateExpression("adam.age"));
        }

        [TestMethod]
        public void NewObjectWithArgument()
        {
            this.EvaluateCommands("function Person(name) { this.name = name; }");
            this.EvaluateCommands("var adam = new Person('Adam');");
            Assert.AreEqual("Adam", this.EvaluateExpression("adam.name"));
        }

        [TestMethod]
        public void NewObjectOverridingPrototypeValue()
        {
            this.EvaluateCommands("function Person() { this.name = 'Adam'; }");
            this.EvaluateCommands("Person.prototype.age = 800; var adam = new Person();");
            this.EvaluateCommands("adam.age = 600;");
            Assert.AreEqual(600, this.EvaluateExpression("adam.age"));
            Assert.AreEqual(800, this.EvaluateExpression("Person.prototype.age"));
        }

        [TestMethod]
        public void AddElementToArray()
        {
            this.EvaluateCommands("var arr = []; arr.push(1); arr.push(2);");
            Assert.AreEqual(2, this.EvaluateExpression("arr.length"));
            Assert.AreEqual(1, this.EvaluateExpression("arr[0]"));
            Assert.AreEqual(2, this.EvaluateExpression("arr[1]"));
        }

        [TestMethod]
        public void ChangeElementInArray()
        {
            this.EvaluateCommands("var arr = [1, 2, 3]; arr[1] = 5;");
            Assert.AreEqual(3, this.EvaluateExpression("arr.length"));
            Assert.AreEqual(1, this.EvaluateExpression("arr[0]"));
            Assert.AreEqual(5, this.EvaluateExpression("arr[1]"));
            Assert.AreEqual(3, this.EvaluateExpression("arr[2]"));
        }

        [TestMethod]
        public void SliceCompleteArray()
        {
            this.EvaluateCommands("var arr = [1, 2, 3]; var arr2 = arr.slice();");
            Assert.AreEqual(3, this.EvaluateExpression("arr2.length"));
            Assert.AreEqual(1, this.EvaluateExpression("arr2[0]"));
            Assert.AreEqual(2, this.EvaluateExpression("arr2[1]"));
            Assert.AreEqual(3, this.EvaluateExpression("arr2[2]"));
        }

        [TestMethod]
        public void SliceWithOneArgument()
        {
            this.EvaluateCommands("var arr = [1, 2, 3]; var arr2 = arr.slice(1);");
            Assert.AreEqual(2, this.EvaluateExpression("arr2.length"));
            Assert.AreEqual(2, this.EvaluateExpression("arr2[0]"));
            Assert.AreEqual(3, this.EvaluateExpression("arr2[1]"));
        }

        [TestMethod]
        public void SliceWithTwoArgument()
        {
            this.EvaluateCommands("var arr = [1, 2, 3]; var arr2 = arr.slice(1, 2);");
            Assert.AreEqual(1, this.EvaluateExpression("arr2.length"));
            Assert.AreEqual(2, this.EvaluateExpression("arr2[0]"));
        }

        [TestMethod]
        public void SliceWithNegativeFirstArgument()
        {
            this.EvaluateCommands("var arr = [1, 2, 3, 4]; var arr2 = arr.slice(-2);");
            Assert.AreEqual(2, this.EvaluateExpression("arr2.length"));
            Assert.AreEqual(3, this.EvaluateExpression("arr2[0]"));
            Assert.AreEqual(4, this.EvaluateExpression("arr2[1]"));
        }

        [TestMethod]
        public void SliceWithNegativeSecondArgument()
        {
            this.EvaluateCommands("var arr = [1, 2, 3, 4]; var arr2 = arr.slice(1, -1);");
            Assert.AreEqual(2, this.EvaluateExpression("arr2.length"));
            Assert.AreEqual(2, this.EvaluateExpression("arr2[0]"));
            Assert.AreEqual(3, this.EvaluateExpression("arr2[1]"));
        }

        [TestMethod]
        public void UnshiftAddElementIntoArray()
        {
            this.EvaluateCommands("var arr = [1, 2, 3];");
            Assert.AreEqual(4, this.EvaluateExpression("arr.unshift(4)"));
            Assert.AreEqual(4, this.EvaluateExpression("arr.length"));
            Assert.AreEqual(4, this.EvaluateExpression("arr[0]"));
            Assert.AreEqual(1, this.EvaluateExpression("arr[1]"));
            Assert.AreEqual(2, this.EvaluateExpression("arr[2]"));
            Assert.AreEqual(3, this.EvaluateExpression("arr[3]"));
        }

        [TestMethod]
        public void ShiftRemoveElementFromArray()
        {
            this.EvaluateCommands("var arr = [1, 2, 3];");
            Assert.AreEqual(1, this.EvaluateExpression("arr.shift()"));
            Assert.AreEqual(2, this.EvaluateExpression("arr.length"));
            Assert.AreEqual(2, this.EvaluateExpression("arr[0]"));
            Assert.AreEqual(3, this.EvaluateExpression("arr[1]"));
        }

        [TestMethod]
        public void PopRemoveElementFromArray()
        {
            this.EvaluateCommands("var arr = [1, 2, 3];");
            Assert.AreEqual(3, this.EvaluateExpression("arr.pop()"));
            Assert.AreEqual(2, this.EvaluateExpression("arr.length"));
            Assert.AreEqual(1, this.EvaluateExpression("arr[0]"));
            Assert.AreEqual(2, this.EvaluateExpression("arr[1]"));
        }

        [TestMethod]
        public void InstanceOf()
        {
            Assert.AreEqual(false, this.EvaluateExpression("1 instanceof Object"));
            Assert.AreEqual(true, this.EvaluateExpression("[] instanceof Array"));
            Assert.AreEqual(true, this.EvaluateExpression("[] instanceof Object"));
            Assert.AreEqual(true, this.EvaluateExpression("{} instanceof Object"));
            Assert.AreEqual(false, this.EvaluateExpression("1 instanceof Number"));
            Assert.AreEqual(false, this.EvaluateExpression("'foo' instanceof String"));
        }

        [TestMethod]
        public void NewStringInstanceOf()
        {
            Assert.AreEqual(true, this.EvaluateExpression("new String('foo') instanceof String"));
        }

        [TestMethod]
        public void NewStringTypeOf()
        {
            Assert.AreEqual("object", this.EvaluateExpression("typeof (new String('foo'))"));
        }

        [TestMethod]
        public void NewStringIndexedAccess()
        {
            Assert.AreEqual(3, this.EvaluateExpression("(new String('foo')).length"));
        }

        [TestMethod]
        public void NonStrictEqualNullUndefined()
        {
            Assert.AreEqual(true, this.EvaluateExpression("null == undefined"));
            Assert.AreEqual(true, this.EvaluateExpression("undefined == null"));
            Assert.AreEqual(false, this.EvaluateExpression("undefined == false"));
            Assert.AreEqual(false, this.EvaluateExpression("null == false"));
            Assert.AreEqual(false, this.EvaluateExpression("false == undefined"));
            Assert.AreEqual(false, this.EvaluateExpression("false == null"));
        }

        [TestMethod]
        public void NonStrictNotEqualNullUndefined()
        {
            Assert.AreEqual(false, this.EvaluateExpression("null != undefined"));
            Assert.AreEqual(false, this.EvaluateExpression("undefined != null"));
            Assert.AreEqual(true, this.EvaluateExpression("undefined != false"));
            Assert.AreEqual(true, this.EvaluateExpression("null != false"));
            Assert.AreEqual(true, this.EvaluateExpression("false != undefined"));
            Assert.AreEqual(true, this.EvaluateExpression("false != null"));
        }

        [TestMethod]
        public void JoinArrayUsingDefaultComma()
        {
            this.EvaluateCommands("var arr = [1, 2, 3];");
            Assert.AreEqual("1,2,3", this.EvaluateExpression("arr.join()"));
        }

        [TestMethod]
        public void JoinArrayUsingDefaultSeparator()
        {
            this.EvaluateCommands("var arr = [1, 2, 3];");
            Assert.AreEqual("1 2 3", this.EvaluateExpression("arr.join(' ')"));
        }

        [TestMethod]
        public void DeleteProperty()
        {
            this.EvaluateCommands("adam = {}; adam.name = 'Adam'; adam.age = 800;");

            var adam = (IObject)this.machine.Context.GetValue("adam");

            Assert.AreEqual(800, adam.GetValue("age"));

            this.EvaluateCommands("delete adam.age;");

            Assert.AreSame(Undefined.Instance, adam.GetValue("age"));
        }

        [TestMethod]
        public void DeleteVariable()
        {
            this.EvaluateCommands("adam = {}; adam.name = 'Adam'; adam.age = 800;");

            var adam = (IObject)this.machine.Context.GetValue("adam");

            Assert.IsNotNull(adam);
            Assert.AreNotSame(Undefined.Instance, adam);

            this.EvaluateCommands("delete adam;");

            Assert.AreSame(Undefined.Instance, this.machine.Context.GetValue("adam"));
        }

        [TestMethod]
        public void TypeofPrimitiveFunctions()
        {
            Assert.AreEqual("function", this.EvaluateExpression("typeof Object"));
            Assert.AreEqual("function", this.EvaluateExpression("typeof Array"));
            Assert.AreEqual("function", this.EvaluateExpression("typeof String"));
        }

        private void EvaluateCommands(string text)
        {
            Parser parser = new Parser(text);

            for (ICommand cmd = parser.ParseCommand(); cmd != null; cmd = parser.ParseCommand())
                cmd.Execute(this.machine.Context);
        }

        private object EvaluateExpression(string text)
        {
            Parser parser = new Parser(text);
            IExpression expression = parser.ParseExpression();
            Assert.IsNull(parser.ParseExpression());
            return this.machine.Evaluate(expression);
        }
    }
}