text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Text;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.OData;
using System.Web.Http.OData.Extensions;
using System.Web.Http.OData.Query;
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Query;

namespace NuGet.Lucene.Web.OData
{
    public class NoSelectODataQueryOptions<T> : ODataQueryOptions<T>
    {
        private static readonly MethodInfo limitResultsGenericMethod = typeof(ODataQueryOptions).GetMethod("LimitResults");
        private readonly IAssembliesResolver assembliesResolver;

        public NoSelectODataQueryOptions(ODataQueryContext context, HttpRequestMessage request) : base(context, request)
        {
            if (request.GetConfiguration() != null)
            {
                assembliesResolver = request.GetConfiguration().Services.GetAssembliesResolver();
            }

            // fallback to the default assemblies resolver if none available.
            assembliesResolver = assembliesResolver ?? new DefaultAssembliesResolver();

        }
        public override IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            if (querySettings == null)
            {
                throw new ArgumentNullException(nameof(querySettings));
            }

            var result = query;

            // Construct the actual query and apply them in the following order: filter, orderby, skip, top
            if (Filter != null)
            {
                result = Filter.ApplyTo(result, querySettings, assembliesResolver);
            }

            if (InlineCount != null && Request.ODataProperties().TotalCount == null)
            {
                long? count = InlineCount.GetEntityCount(result);
                if (count.HasValue)
                {
                    Request.ODataProperties().TotalCount = count.Value;
                }
            }

            OrderByQueryOption orderBy = OrderBy;

            // $skip or $top require a stable sort for predictable results.
            // Result limits require a stable sort to be able to generate a next page link.
            // If either is present in the query and we have permission,
            // generate an $orderby that will produce a stable sort.
            if (querySettings.EnsureStableOrdering &&
                (Skip != null || Top != null || querySettings.PageSize.HasValue))
            {
                // If there is no OrderBy present, we manufacture a default.
                // If an OrderBy is already present, we add any missing
                // properties necessary to make a stable sort.
                // Instead of failing early here if we cannot generate the OrderBy,
                // let the IQueryable backend fail (if it has to).
                orderBy = orderBy == null
                            ? GenerateDefaultOrderBy(Context)
                            : EnsureStableSortOrderBy(orderBy, Context);
            }

            if (orderBy != null)
            {
                result = orderBy.ApplyTo(result, querySettings);
            }

            if (Skip != null)
            {
                result = Skip.ApplyTo(result, querySettings);
            }

            if (Top != null)
            {
                result = Top.ApplyTo(result, querySettings);
            }

            if (querySettings.PageSize.HasValue)
            {
                bool resultsLimited;
                result = LimitResults(result, querySettings.PageSize.Value, out resultsLimited);
                if (resultsLimited && Request.RequestUri != null && Request.RequestUri.IsAbsoluteUri && Request.ODataProperties().NextLink == null)
                {
                    Uri nextPageLink = GetNextPageLink(Request, querySettings.PageSize.Value);
                    Request.ODataProperties().NextLink = nextPageLink;
                }
            }

            return result;
        }
        private static OrderByQueryOption EnsureStableSortOrderBy(OrderByQueryOption orderBy, ODataQueryContext context)
        {
            Contract.Assert(orderBy != null);
            Contract.Assert(context != null);

            // Strategy: create a hash of all properties already used in the given OrderBy
            // and remove them from the list of properties we need to add to make the sort stable.
            var usedPropertyNames =
                new HashSet<string>(orderBy.OrderByNodes.OfType<OrderByPropertyNode>().Select(node => node.Property.Name));

            var propertiesToAdd = GetAvailableOrderByProperties(context).Where(prop => !usedPropertyNames.Contains(prop.Name)).ToArray();

            if (propertiesToAdd.Any())
            {
                // The existing query options has too few properties to create a stable sort.
                // Clone the given one and add the remaining properties to end, thereby making
                // the sort stable but preserving the user's original intent for the major
                // sort order.
                orderBy = new OrderByQueryOption(orderBy.RawValue, context);
                foreach (var property in propertiesToAdd)
                {
                    orderBy.OrderByNodes.Add(new OrderByPropertyNode(property, OrderByDirection.Ascending));
                }
            }

            return orderBy;
        }

        private static OrderByQueryOption GenerateDefaultOrderBy(ODataQueryContext context)
        {
            var orderByRaw = string.Join(",",
                                    GetAvailableOrderByProperties(context)
                                        .Select(property => property.Name));
            return string.IsNullOrEmpty(orderByRaw)
                    ? null
                    : new OrderByQueryOption(orderByRaw, context);
        }

        // Returns a sorted list of all properties that may legally appear
        // in an OrderBy.  If the entity type has keys, all are returned.
        // Otherwise, when no keys are present, all primitive properties are returned.
        private static IEnumerable<IEdmStructuralProperty> GetAvailableOrderByProperties(ODataQueryContext context)
        {
            Contract.Assert(context != null);

            var entityType = context.ElementType as IEdmEntityType;

            if (entityType == null) return Enumerable.Empty<IEdmStructuralProperty>();

            var properties =
                entityType.Key().Any()
                    ? entityType.Key()
                    : entityType
                        .StructuralProperties()
                        .Where(property => property.Type.IsPrimitive());

            // Sort properties alphabetically for stable sort
            return properties.OrderBy(property => property.Name);
        }
        internal static IQueryable LimitResults(IQueryable queryable, int limit, out bool resultsLimited)
        {
            var genericMethod = limitResultsGenericMethod.MakeGenericMethod(queryable.ElementType);
            var args = new object[] { queryable, limit, null };
            var results = genericMethod.Invoke(null, args) as IQueryable;
            resultsLimited = (bool)args[2];
            return results;
        }

        internal static Uri GetNextPageLink(HttpRequestMessage request, int pageSize)
        {
            Contract.Assert(request != null);
            Contract.Assert(request.RequestUri != null);
            Contract.Assert(request.RequestUri.IsAbsoluteUri);

            return GetNextPageLink(request.RequestUri, request.GetQueryNameValuePairs(), pageSize);
        }

        internal static Uri GetNextPageLink(Uri requestUri, int pageSize)
        {
            Contract.Assert(requestUri != null);
            Contract.Assert(requestUri.IsAbsoluteUri);

            return GetNextPageLink(requestUri, new FormDataCollection(requestUri), pageSize);
        }

        internal static Uri GetNextPageLink(Uri requestUri, IEnumerable<KeyValuePair<string, string>> queryParameters, int pageSize)
        {
            Contract.Assert(requestUri != null);
            Contract.Assert(queryParameters != null);
            Contract.Assert(requestUri.IsAbsoluteUri);

            var queryBuilder = new StringBuilder();

            var nextPageSkip = pageSize;

            foreach (KeyValuePair<string, string> kvp in queryParameters)
            {
                var key = kvp.Key;
                var value = kvp.Value;
                switch (key)
                {
                    case "$top":
                        int top;
                        if (int.TryParse(value, out top))
                        {
                            // There is no next page if the $top query option's value is less than or equal to the page size.
                            Contract.Assert(top > pageSize);
                            // We decrease top by the pageSize because that's the number of results we're returning in the current page
                            value = (top - pageSize).ToString(CultureInfo.InvariantCulture);
                        }
                        break;
                    case "$skip":
                        int skip;
                        if (int.TryParse(value, out skip))
                        {
                            // We increase skip by the pageSize because that's the number of results we're returning in the current page
                            nextPageSkip += skip;
                        }
                        continue;
                }

                if (key.Length > 0 && key[0] == '$')
                {
                    // $ is a legal first character in query keys
                    key = '$' + Uri.EscapeDataString(key.Substring(1));
                }
                else
                {
                    key = Uri.EscapeDataString(key);
                }
                value = Uri.EscapeDataString(value);

                queryBuilder.Append(key);
                queryBuilder.Append('=');
                queryBuilder.Append(value);
                queryBuilder.Append('&');
            }

            queryBuilder.AppendFormat("$skip={0}", nextPageSkip);

            var uriBuilder = new UriBuilder(requestUri)
            {
                Query = queryBuilder.ToString()
            };
            return uriBuilder.Uri;
        }
    }
}


text:
    width: 60%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
}

#features img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 20%;
}

#features li {
    margin: 5px;
}

#nameForm {
    display: flex;
    flex-flow: column wrap;
    align-items: center;
    margin-top: 20px;
}

#cancelButton {
    position: absolute;
    bottom: 1em;
    right: 1em;
}

redpajama_set_name: RedPajamaGithub


text:
#include "bitpaywalletclient-config.h"

#include "bitpaywalletclient.h"

#include <btc/ecc.h>

#include <assert.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>

static struct option long_options[] =
{
    {"privkey", required_argument, NULL, 'p'},
    {"pubkey", required_argument, NULL, 'k'},
    {"keypath", required_argument, NULL, 'm'},
    {"command", required_argument, NULL, 'c'},
    {"testnet", no_argument, NULL, 't'},
    {"regtest", no_argument, NULL, 'r'},
    {"version", no_argument, NULL, 'v'},
    {NULL, 0, NULL, 0}
};

static void print_version() {
    printf("Version: %s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
}

static void print_usage() {
    print_version();
    printf("Usage: bitpaywalletclient -c <command>\n");
    printf("Available commands: createwallet\n");
    printf("\nExamples: \n");
    printf("Create a new wallet:\n");
    printf("> bitpaywalletclient -c createwallet --testnet\n\n");
}

static bool showError(const char *er)
{
    printf("Error: %s\n", er);
    return 0;
}

int main(int argc, char *argv[])
{
    int long_index =0;
    int opt= 0;
    char *cmd = 0;
    bool testnet = false;

    /* get arguments */
    while ((opt = getopt_long_only(argc, argv,"p:k:m:c:trv", long_options, &long_index )) != -1) {
        switch (opt) {
            // case 'p' :
            //     pkey = optarg;
            //     if (strlen(pkey) < 50)
            //         return showError("Private key must be WIF encoded");
            //     break;
            case 'c' : cmd = optarg;
                break;
            // case 'm' : keypath = optarg;
            //     break;
            // case 'k' : pubkey = optarg;
            //     break;
            case 't' :
                testnet = true;
                break;
            // case 'r' :
            //     chain = &btc_chain_regt;
            //     break;
            case 'v' :
                print_version();
                exit(EXIT_SUCCESS);
                break;
            default: print_usage();
                exit(EXIT_FAILURE);
        }
    }

    /* start ECC context */
    btc_ecc_start();

    if (!cmd)
    {
        /* exit if no command was provided */
        print_usage();
        exit(EXIT_FAILURE);
    }
    else if (strcmp(cmd, "createwallet") == 0)
    {
        BitPayWalletClient *singleWallet = new BitPayWalletClient("/tmp/", testnet);
        singleWallet->setRequestPubKey("xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73");
        singleWallet->setMasterPubKey("xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73");
        singleWallet->CreateWallet("New Wallet");
        std::string response;
        singleWallet->GetWallets(response);
        printf("%s\n", response.c_str());
    }

    btc_ecc_stop();

    return 0;
}


text:
#include "SDL_config.h"

#if SDL_VIDEO_RENDER_D3D

#include "SDL_win32video.h"
#include "../SDL_yuv_sw_c.h"

#ifdef ASSEMBLE_SHADER
///////////////////////////////////////////////////////////////////////////
// ID3DXBuffer:
// ------------
// The buffer object is used by D3DX to return arbitrary size data.
//
// GetBufferPointer -
//    Returns a pointer to the beginning of the buffer.
//
// GetBufferSize -
//    Returns the size of the buffer, in bytes.
///////////////////////////////////////////////////////////////////////////

typedef interface ID3DXBuffer ID3DXBuffer;
typedef interface ID3DXBuffer *LPD3DXBUFFER;

// {8BA5FB08-5195-40e2-AC58-0D989C3A0102}
DEFINE_GUID(IID_ID3DXBuffer,
0x8ba5fb08, 0x5195, 0x40e2, 0xac, 0x58, 0xd, 0x98, 0x9c, 0x3a, 0x1, 0x2);

#undef INTERFACE
#define INTERFACE ID3DXBuffer

typedef interface ID3DXBuffer {
    const struct ID3DXBufferVtbl FAR* lpVtbl;
} ID3DXBuffer;
typedef const struct ID3DXBufferVtbl ID3DXBufferVtbl;
const struct ID3DXBufferVtbl
{
    // IUnknown
    STDMETHOD(QueryInterface)(THIS_ REFIID iid, LPVOID *ppv) PURE;
    STDMETHOD_(ULONG, AddRef)(THIS) PURE;
    STDMETHOD_(ULONG, Release)(THIS) PURE;

    // ID3DXBuffer
    STDMETHOD_(LPVOID, GetBufferPointer)(THIS) PURE;
    STDMETHOD_(DWORD, GetBufferSize)(THIS) PURE;
};

HRESULT WINAPI
    D3DXAssembleShader(
        LPCSTR                          pSrcData,
        UINT                            SrcDataLen,
        CONST LPVOID*                   pDefines,
        LPVOID                          pInclude,
        DWORD                           Flags,
        LPD3DXBUFFER*                   ppShader,
        LPD3DXBUFFER*                   ppErrorMsgs);

#endif /* ASSEMBLE_SHADER */

/* Direct3D renderer implementation */

#if 1                           /* This takes more memory but you won't lose your texture data */
#define D3DPOOL_SDL    D3DPOOL_MANAGED
#define SDL_MEMORY_POOL_MANAGED
#else
#define D3DPOOL_SDL    D3DPOOL_DEFAULT
#define SDL_MEMORY_POOL_DEFAULT
#endif

static SDL_Renderer *D3D_CreateRenderer(SDL_Window * window, Uint32 flags);
static int D3D_DisplayModeChanged(SDL_Renderer * renderer);
static int D3D_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
static int D3D_QueryTexturePixels(SDL_Renderer * renderer,
                                  SDL_Texture * texture, void **pixels,
                                  int *pitch);
static int D3D_SetTexturePalette(SDL_Renderer * renderer,
                                 SDL_Texture * texture,
                                 const SDL_Color * colors, int firstcolor,
                                 int ncolors);
static int D3D_GetTexturePalette(SDL_Renderer * renderer,
                                 SDL_Texture * texture, SDL_Color * colors,
                                 int firstcolor, int ncolors);
static int D3D_SetTextureColorMod(SDL_Renderer * renderer,
                                  SDL_Texture * texture);
static int D3D_SetTextureAlphaMod(SDL_Renderer * renderer,
                                  SDL_Texture * texture);
static int D3D_SetTextureBlendMode(SDL_Renderer * renderer,
                                   SDL_Texture * texture);
static int D3D_SetTextureScaleMode(SDL_Renderer * renderer,
                                   SDL_Texture * texture);
static int D3D_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                             const SDL_Rect * rect, const void *pixels,
                             int pitch);
static int D3D_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                           const SDL_Rect * rect, int markDirty,
                           void **pixels, int *pitch);
static void D3D_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture);
static void D3D_DirtyTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                             int numrects, const SDL_Rect * rects);
static int D3D_RenderDrawPoints(SDL_Renderer * renderer,
                                const SDL_Point * points, int count);
static int D3D_RenderDrawLines(SDL_Renderer * renderer,
                               const SDL_Point * points, int count);
static int D3D_RenderDrawRects(SDL_Renderer * renderer,
                               const SDL_Rect ** rects, int count);
static int D3D_RenderFillRects(SDL_Renderer * renderer,
                               const SDL_Rect ** rects, int count);
static int D3D_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
                          const SDL_Rect * srcrect, const SDL_Rect * dstrect);
static int D3D_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                                Uint32 format, void * pixels, int pitch);
static int D3D_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                                 Uint32 format, const void * pixels, int pitch);
static void D3D_RenderPresent(SDL_Renderer * renderer);
static void D3D_DestroyTexture(SDL_Renderer * renderer,
                               SDL_Texture * texture);
static void D3D_DestroyRenderer(SDL_Renderer * renderer);

SDL_RenderDriver D3D_RenderDriver = {
    D3D_CreateRenderer,
    {
     "d3d",
     (SDL_RENDERER_SINGLEBUFFER | SDL_RENDERER_PRESENTCOPY |
      SDL_RENDERER_PRESENTFLIP2 | SDL_RENDERER_PRESENTFLIP3 |
      SDL_RENDERER_PRESENTDISCARD | SDL_RENDERER_PRESENTVSYNC |
      SDL_RENDERER_ACCELERATED),
     (SDL_TEXTUREMODULATE_NONE | SDL_TEXTUREMODULATE_COLOR |
      SDL_TEXTUREMODULATE_ALPHA),
     (SDL_BLENDMODE_NONE | SDL_BLENDMODE_MASK |
      SDL_BLENDMODE_BLEND | SDL_BLENDMODE_ADD | SDL_BLENDMODE_MOD),
     (SDL_TEXTURESCALEMODE_NONE | SDL_TEXTURESCALEMODE_FAST |
      SDL_TEXTURESCALEMODE_SLOW | SDL_TEXTURESCALEMODE_BEST),
     0,
     {0},
     0,
     0}
};

typedef struct
{
    IDirect3D9 *d3d;
    IDirect3DDevice9 *device;
    UINT adapter;
    D3DPRESENT_PARAMETERS pparams;
    LPDIRECT3DPIXELSHADER9 ps_mask;
    SDL_bool beginScene;
} D3D_RenderData;

typedef struct
{
    SDL_SW_YUVTexture *yuv;
    Uint32 format;
    IDirect3DTexture9 *texture;
} D3D_TextureData;

typedef struct
{
    float x, y, z;
    float rhw;
    DWORD color;
    float u, v;
} Vertex;

static void
D3D_SetError(const char *prefix, HRESULT result)
{
    const char *error;

    switch (result) {
    case D3DERR_WRONGTEXTUREFORMAT:
        error = "WRONGTEXTUREFORMAT";
        break;
    case D3DERR_UNSUPPORTEDCOLOROPERATION:
        error = "UNSUPPORTEDCOLOROPERATION";
        break;
    case D3DERR_UNSUPPORTEDCOLORARG:
        error = "UNSUPPORTEDCOLORARG";
        break;
    case D3DERR_UNSUPPORTEDALPHAOPERATION:
        error = "UNSUPPORTEDALPHAOPERATION";
        break;
    case D3DERR_UNSUPPORTEDALPHAARG:
        error = "UNSUPPORTEDALPHAARG";
        break;
    case D3DERR_TOOMANYOPERATIONS:
        error = "TOOMANYOPERATIONS";
        break;
    case D3DERR_CONFLICTINGTEXTUREFILTER:
        error = "CONFLICTINGTEXTUREFILTER";
        break;
    case D3DERR_UNSUPPORTEDFACTORVALUE:
        error = "UNSUPPORTEDFACTORVALUE";
        break;
    case D3DERR_CONFLICTINGRENDERSTATE:
        error = "CONFLICTINGRENDERSTATE";
        break;
    case D3DERR_UNSUPPORTEDTEXTUREFILTER:
        error = "UNSUPPORTEDTEXTUREFILTER";
        break;
    case D3DERR_CONFLICTINGTEXTUREPALETTE:
        error = "CONFLICTINGTEXTUREPALETTE";
        break;
    case D3DERR_DRIVERINTERNALERROR:
        error = "DRIVERINTERNALERROR";
        break;
    case D3DERR_NOTFOUND:
        error = "NOTFOUND";
        break;
    case D3DERR_MOREDATA:
        error = "MOREDATA";
        break;
    case D3DERR_DEVICELOST:
        error = "DEVICELOST";
        break;
    case D3DERR_DEVICENOTRESET:
        error = "DEVICENOTRESET";
        break;
    case D3DERR_NOTAVAILABLE:
        error = "NOTAVAILABLE";
        break;
    case D3DERR_OUTOFVIDEOMEMORY:
        error = "OUTOFVIDEOMEMORY";
        break;
    case D3DERR_INVALIDDEVICE:
        error = "INVALIDDEVICE";
        break;
    case D3DERR_INVALIDCALL:
        error = "INVALIDCALL";
        break;
    case D3DERR_DRIVERINVALIDCALL:
        error = "DRIVERINVALIDCALL";
        break;
    case D3DERR_WASSTILLDRAWING:
        error = "WASSTILLDRAWING";
        break;
    default:
        error = "UNKNOWN";
        break;
    }
    SDL_SetError("%s: %s", prefix, error);
}

static D3DFORMAT
PixelFormatToD3DFMT(Uint32 format)
{
    switch (format) {
    case SDL_PIXELFORMAT_INDEX8:
        return D3DFMT_P8;
    case SDL_PIXELFORMAT_RGB332:
        return D3DFMT_R3G3B2;
    case SDL_PIXELFORMAT_RGB444:
        return D3DFMT_X4R4G4B4;
    case SDL_PIXELFORMAT_RGB555:
        return D3DFMT_X1R5G5B5;
    case SDL_PIXELFORMAT_ARGB4444:
        return D3DFMT_A4R4G4B4;
    case SDL_PIXELFORMAT_ARGB1555:
        return D3DFMT_A1R5G5B5;
    case SDL_PIXELFORMAT_RGB565:
        return D3DFMT_R5G6B5;
    case SDL_PIXELFORMAT_RGB888:
        return D3DFMT_X8R8G8B8;
    case SDL_PIXELFORMAT_ARGB8888:
        return D3DFMT_A8R8G8B8;
    case SDL_PIXELFORMAT_ARGB2101010:
        return D3DFMT_A2R10G10B10;
    case SDL_PIXELFORMAT_YV12:
        return MAKEFOURCC('Y','V','1','2');
    case SDL_PIXELFORMAT_IYUV:
        return MAKEFOURCC('I','4','2','0');
    case SDL_PIXELFORMAT_UYVY:
        return D3DFMT_UYVY;
    case SDL_PIXELFORMAT_YUY2:
        return D3DFMT_YUY2;
    default:
        return D3DFMT_UNKNOWN;
    }
}

static UINT D3D_FindAdapter(IDirect3D9 * d3d, SDL_VideoDisplay * display)
{
    SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata;
    UINT adapter, count;

    count = IDirect3D9_GetAdapterCount(d3d);
    for (adapter = 0; adapter < count; ++adapter) {
        HRESULT result;
        D3DADAPTER_IDENTIFIER9 info;
        char *name;

        result = IDirect3D9_GetAdapterIdentifier(d3d, adapter, 0, &info);
        if (FAILED(result)) {
            continue;
        }
        name = WIN_StringToUTF8(displaydata->DeviceName);
        if (SDL_strcmp(name, info.DeviceName) == 0) {
            SDL_free(name);
            return adapter;
        }
        SDL_free(name);
    }

    /* This should never happen, but just in case... */
    return D3DADAPTER_DEFAULT;
}

static SDL_bool
D3D_IsTextureFormatAvailable(IDirect3D9 * d3d, UINT adapter,
                             Uint32 display_format,
                             Uint32 texture_format)
{
    HRESULT result;

    result = IDirect3D9_CheckDeviceFormat(d3d, adapter,
                                          D3DDEVTYPE_HAL,
                                          PixelFormatToD3DFMT(display_format),
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          PixelFormatToD3DFMT
                                          (texture_format));
    return FAILED(result) ? SDL_FALSE : SDL_TRUE;
}

static void
UpdateYUVTextureData(SDL_Texture * texture)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;
    SDL_Rect rect;
    RECT d3drect;
    D3DLOCKED_RECT locked;
    HRESULT result;

    d3drect.left = 0;
    d3drect.right = texture->w;
    d3drect.top = 0;
    d3drect.bottom = texture->h;

    result =
        IDirect3DTexture9_LockRect(data->texture, 0, &locked, &d3drect, 0);
    if (FAILED(result)) {
        return;
    }

    rect.x = 0;
    rect.y = 0;
    rect.w = texture->w;
    rect.h = texture->h;
    SDL_SW_CopyYUVToRGB(data->yuv, &rect, data->format, texture->w,
                        texture->h, locked.pBits, locked.Pitch);

    IDirect3DTexture9_UnlockRect(data->texture, 0);
}

void
D3D_AddRenderDriver(_THIS)
{
    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
    SDL_RendererInfo *info = &D3D_RenderDriver.info;

    if (data->d3d) {
        int i, j;
        int formats[] = {
            SDL_PIXELFORMAT_INDEX8,
            SDL_PIXELFORMAT_RGB332,
            SDL_PIXELFORMAT_RGB444,
            SDL_PIXELFORMAT_RGB555,
            SDL_PIXELFORMAT_ARGB4444,
            SDL_PIXELFORMAT_ARGB1555,
            SDL_PIXELFORMAT_RGB565,
            SDL_PIXELFORMAT_RGB888,
            SDL_PIXELFORMAT_ARGB8888,
            SDL_PIXELFORMAT_ARGB2101010,
        };

        for (i = 0; i < _this->num_displays; ++i) {
            SDL_VideoDisplay *display = &_this->displays[i];
            SDL_DisplayMode *mode = &display->desktop_mode;
            UINT adapter = D3D_FindAdapter(data->d3d, display);

            /* Get the matching D3D adapter for this display */
            info->num_texture_formats = 0;
            for (j = 0; j < SDL_arraysize(formats); ++j) {
                if (D3D_IsTextureFormatAvailable
                    (data->d3d, adapter, mode->format, formats[j])) {
                    info->texture_formats[info->num_texture_formats++] =
                        formats[j];
                }
            }
            info->texture_formats[info->num_texture_formats++] =
                SDL_PIXELFORMAT_YV12;
            info->texture_formats[info->num_texture_formats++] =
                SDL_PIXELFORMAT_IYUV;
            info->texture_formats[info->num_texture_formats++] =
                SDL_PIXELFORMAT_YUY2;
            info->texture_formats[info->num_texture_formats++] =
                SDL_PIXELFORMAT_UYVY;
            info->texture_formats[info->num_texture_formats++] =
                SDL_PIXELFORMAT_YVYU;

            SDL_AddRenderDriver(display, &D3D_RenderDriver);
        }
    }
}

SDL_Renderer *
D3D_CreateRenderer(SDL_Window * window, Uint32 flags)
{
    SDL_VideoDisplay *display = window->display;
    SDL_VideoData *videodata = (SDL_VideoData *) display->device->driverdata;
    SDL_WindowData *windowdata = (SDL_WindowData *) window->driverdata;
    SDL_Renderer *renderer;
    D3D_RenderData *data;
    HRESULT result;
    D3DPRESENT_PARAMETERS pparams;
    IDirect3DSwapChain9 *chain;
    D3DCAPS9 caps;

    renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer));
    if (!renderer) {
        SDL_OutOfMemory();
        return NULL;
    }

    data = (D3D_RenderData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        D3D_DestroyRenderer(renderer);
        SDL_OutOfMemory();
        return NULL;
    }
    data->d3d = videodata->d3d;

    renderer->DisplayModeChanged = D3D_DisplayModeChanged;
    renderer->CreateTexture = D3D_CreateTexture;
    renderer->QueryTexturePixels = D3D_QueryTexturePixels;
    renderer->SetTexturePalette = D3D_SetTexturePalette;
    renderer->GetTexturePalette = D3D_GetTexturePalette;
    renderer->SetTextureColorMod = D3D_SetTextureColorMod;
    renderer->SetTextureAlphaMod = D3D_SetTextureAlphaMod;
    renderer->SetTextureBlendMode = D3D_SetTextureBlendMode;
    renderer->SetTextureScaleMode = D3D_SetTextureScaleMode;
    renderer->UpdateTexture = D3D_UpdateTexture;
    renderer->LockTexture = D3D_LockTexture;
    renderer->UnlockTexture = D3D_UnlockTexture;
    renderer->DirtyTexture = D3D_DirtyTexture;
    renderer->RenderDrawPoints = D3D_RenderDrawPoints;
    renderer->RenderDrawLines = D3D_RenderDrawLines;
    renderer->RenderDrawRects = D3D_RenderDrawRects;
    renderer->RenderFillRects = D3D_RenderFillRects;
    renderer->RenderCopy = D3D_RenderCopy;
    renderer->RenderReadPixels = D3D_RenderReadPixels;
    renderer->RenderWritePixels = D3D_RenderWritePixels;
    renderer->RenderPresent = D3D_RenderPresent;
    renderer->DestroyTexture = D3D_DestroyTexture;
    renderer->DestroyRenderer = D3D_DestroyRenderer;
    renderer->info = D3D_RenderDriver.info;
    renderer->window = window;
    renderer->driverdata = data;

    renderer->info.flags = SDL_RENDERER_ACCELERATED;

    SDL_zero(pparams);
    pparams.BackBufferWidth = window->w;
    pparams.BackBufferHeight = window->h;
    if (window->flags & SDL_WINDOW_FULLSCREEN) {
        pparams.BackBufferFormat =
            PixelFormatToD3DFMT(window->fullscreen_mode.format);
    } else {
        pparams.BackBufferFormat = D3DFMT_UNKNOWN;
    }
    if (flags & SDL_RENDERER_PRESENTFLIP2) {
        pparams.BackBufferCount = 2;
        pparams.SwapEffect = D3DSWAPEFFECT_FLIP;
    } else if (flags & SDL_RENDERER_PRESENTFLIP3) {
        pparams.BackBufferCount = 3;
        pparams.SwapEffect = D3DSWAPEFFECT_FLIP;
    } else if (flags & SDL_RENDERER_PRESENTCOPY) {
        pparams.BackBufferCount = 1;
        pparams.SwapEffect = D3DSWAPEFFECT_COPY;
    } else {
        pparams.BackBufferCount = 1;
        pparams.SwapEffect = D3DSWAPEFFECT_DISCARD;
    }
    if (window->flags & SDL_WINDOW_FULLSCREEN) {
        pparams.Windowed = FALSE;
        pparams.FullScreen_RefreshRateInHz =
            window->fullscreen_mode.refresh_rate;
    } else {
        pparams.Windowed = TRUE;
        pparams.FullScreen_RefreshRateInHz = 0;
    }
    if (flags & SDL_RENDERER_PRESENTVSYNC) {
        pparams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
    } else {
        pparams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    }

    data->adapter = D3D_FindAdapter(videodata->d3d, display);
    IDirect3D9_GetDeviceCaps(videodata->d3d, data->adapter,
                             D3DDEVTYPE_HAL, &caps);

    result = IDirect3D9_CreateDevice(videodata->d3d, data->adapter,
                                     D3DDEVTYPE_HAL,
                                     windowdata->hwnd,
                                     (caps.
                                      DevCaps &
                                      D3DDEVCAPS_HWTRANSFORMANDLIGHT) ?
                                     D3DCREATE_HARDWARE_VERTEXPROCESSING :
                                     D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                     &pparams, &data->device);
    if (FAILED(result)) {
        D3D_DestroyRenderer(renderer);
        D3D_SetError("CreateDevice()", result);
        return NULL;
    }
    data->beginScene = SDL_TRUE;

    /* Get presentation parameters to fill info */
    result = IDirect3DDevice9_GetSwapChain(data->device, 0, &chain);
    if (FAILED(result)) {
        D3D_DestroyRenderer(renderer);
        D3D_SetError("GetSwapChain()", result);
        return NULL;
    }
    result = IDirect3DSwapChain9_GetPresentParameters(chain, &pparams);
    if (FAILED(result)) {
        IDirect3DSwapChain9_Release(chain);
        D3D_DestroyRenderer(renderer);
        D3D_SetError("GetPresentParameters()", result);
        return NULL;
    }
    IDirect3DSwapChain9_Release(chain);
    switch (pparams.SwapEffect) {
    case D3DSWAPEFFECT_COPY:
        renderer->info.flags |= SDL_RENDERER_PRESENTCOPY;
        break;
    case D3DSWAPEFFECT_FLIP:
        switch (pparams.BackBufferCount) {
        case 2:
            renderer->info.flags |= SDL_RENDERER_PRESENTFLIP2;
            break;
        case 3:
            renderer->info.flags |= SDL_RENDERER_PRESENTFLIP3;
            break;
        }
        break;
    case D3DSWAPEFFECT_DISCARD:
        renderer->info.flags |= SDL_RENDERER_PRESENTDISCARD;
        break;
    }
    if (pparams.PresentationInterval == D3DPRESENT_INTERVAL_ONE) {
        renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC;
    }
    data->pparams = pparams;

    IDirect3DDevice9_GetDeviceCaps(data->device, &caps);
    renderer->info.max_texture_width = caps.MaxTextureWidth;
    renderer->info.max_texture_height = caps.MaxTextureHeight;

    /* Set up parameters for rendering */
    IDirect3DDevice9_SetVertexShader(data->device, NULL);
    IDirect3DDevice9_SetFVF(data->device,
                            D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
    IDirect3DDevice9_SetRenderState(data->device, D3DRS_ZENABLE, D3DZB_FALSE);
    IDirect3DDevice9_SetRenderState(data->device, D3DRS_CULLMODE,
                                    D3DCULL_NONE);
    IDirect3DDevice9_SetRenderState(data->device, D3DRS_LIGHTING, FALSE);
    /* Enable color modulation by diffuse color */
    IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_COLOROP,
                                          D3DTOP_MODULATE);
    IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_COLORARG1,
                                          D3DTA_TEXTURE);
    IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_COLORARG2,
                                          D3DTA_DIFFUSE);
    /* Enable alpha modulation by diffuse alpha */
    IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_ALPHAOP,
                                          D3DTOP_MODULATE);
    IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_ALPHAARG1,
                                          D3DTA_TEXTURE);
    IDirect3DDevice9_SetTextureStageState(data->device, 0, D3DTSS_ALPHAARG2,
                                          D3DTA_DIFFUSE);
    /* Disable second texture stage, since we're done */
    IDirect3DDevice9_SetTextureStageState(data->device, 1, D3DTSS_COLOROP,
                                          D3DTOP_DISABLE);
    IDirect3DDevice9_SetTextureStageState(data->device, 1, D3DTSS_ALPHAOP,
                                          D3DTOP_DISABLE);

    {
#ifdef ASSEMBLE_SHADER
        const char *shader_text =
"ps_1_1\n"
"def c0, 0, 0, 0, 0.496\n"
"def c1, 0, 0, 0, 1\n"
"def c2, 0, 0, 0, -1\n"
"tex t0\n"
"mul r1, t0, v0\n"
"add r0, r1, c0\n"
"cnd r0, r0.a, c1, c2\n"
"add r0, r0, r1\n";
        LPD3DXBUFFER pCode;         // buffer with the assembled shader code
        LPD3DXBUFFER pErrorMsgs;    // buffer with error messages
        LPDWORD shader_data;
        DWORD   shader_size;
        result = D3DXAssembleShader( shader_text, SDL_strlen(shader_text), NULL, NULL, 0, &pCode, &pErrorMsgs );
        if (FAILED(result)) {
            D3D_SetError("D3DXAssembleShader()", result);
        }
        shader_data = (DWORD*)pCode->lpVtbl->GetBufferPointer(pCode);
        shader_size = pCode->lpVtbl->GetBufferSize(pCode);
#else
        const DWORD shader_data[] = {
            0xffff0101,0x00000051,0xa00f0000,0x00000000,0x00000000,0x00000000,
            0x3efdf3b6,0x00000051,0xa00f0001,0x00000000,0x00000000,0x00000000,
            0x3f800000,0x00000051,0xa00f0002,0x00000000,0x00000000,0x00000000,
            0xbf800000,0x00000042,0xb00f0000,0x00000005,0x800f0001,0xb0e40000,
            0x90e40000,0x00000002,0x800f0000,0x80e40001,0xa0e40000,0x00000050,
            0x800f0000,0x80ff0000,0xa0e40001,0xa0e40002,0x00000002,0x800f0000,
            0x80e40000,0x80e40001,0x0000ffff
        };
#endif
        result = IDirect3DDevice9_CreatePixelShader(data->device, shader_data, &data->ps_mask);
        if (FAILED(result)) {
            D3D_SetError("CreatePixelShader()", result);
        }
    }

    return renderer;
}

static int
D3D_Reset(SDL_Renderer * renderer)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    HRESULT result;

    result = IDirect3DDevice9_Reset(data->device, &data->pparams);
    if (FAILED(result)) {
        if (result == D3DERR_DEVICELOST) {
            /* Don't worry about it, we'll reset later... */
            return 0;
        } else {
            D3D_SetError("Reset()", result);
            return -1;
        }
    }
    IDirect3DDevice9_SetVertexShader(data->device, NULL);
    IDirect3DDevice9_SetFVF(data->device,
                            D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1);
    IDirect3DDevice9_SetRenderState(data->device, D3DRS_CULLMODE,
                                    D3DCULL_NONE);
    IDirect3DDevice9_SetRenderState(data->device, D3DRS_LIGHTING, FALSE);
    return 0;
}

static int
D3D_DisplayModeChanged(SDL_Renderer * renderer)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    SDL_Window *window = renderer->window;
    SDL_VideoDisplay *display = window->display;

    data->pparams.BackBufferWidth = window->w;
    data->pparams.BackBufferHeight = window->h;
    if (window->flags & SDL_WINDOW_FULLSCREEN) {
        data->pparams.BackBufferFormat =
            PixelFormatToD3DFMT(window->fullscreen_mode.format);
    } else {
        data->pparams.BackBufferFormat = D3DFMT_UNKNOWN;
    }
    return D3D_Reset(renderer);
}

static int
D3D_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    D3D_RenderData *renderdata = (D3D_RenderData *) renderer->driverdata;
    SDL_Window *window = renderer->window;
    SDL_VideoDisplay *display = window->display;
    Uint32 display_format = display->current_mode.format;
    D3D_TextureData *data;
    HRESULT result;

    data = (D3D_TextureData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        SDL_OutOfMemory();
        return -1;
    }

    texture->driverdata = data;

    if (SDL_ISPIXELFORMAT_FOURCC(texture->format) &&
        (texture->format != SDL_PIXELFORMAT_YUY2 ||
         !D3D_IsTextureFormatAvailable(renderdata->d3d, renderdata->adapter,
                                       display_format, texture->format))
        && (texture->format != SDL_PIXELFORMAT_YVYU
            || !D3D_IsTextureFormatAvailable(renderdata->d3d, renderdata->adapter,
                                             display_format, texture->format))) {
        data->yuv =
            SDL_SW_CreateYUVTexture(texture->format, texture->w, texture->h);
        if (!data->yuv) {
            return -1;
        }
        data->format = display->current_mode.format;
    } else {
        data->format = texture->format;
    }

    result =
        IDirect3DDevice9_CreateTexture(renderdata->device, texture->w,
                                       texture->h, 1, 0,
                                       PixelFormatToD3DFMT(data->format),
                                       D3DPOOL_SDL, &data->texture, NULL);
    if (FAILED(result)) {
        D3D_SetError("CreateTexture()", result);
        return -1;
    }

    return 0;
}

static int
D3D_QueryTexturePixels(SDL_Renderer * renderer, SDL_Texture * texture,
                       void **pixels, int *pitch)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;

    if (data->yuv) {
        return SDL_SW_QueryYUVTexturePixels(data->yuv, pixels, pitch);
    } else {
        /* D3D textures don't have their pixels hanging out */
        return -1;
    }
}

static int
D3D_SetTexturePalette(SDL_Renderer * renderer, SDL_Texture * texture,
                      const SDL_Color * colors, int firstcolor, int ncolors)
{
    D3D_RenderData *renderdata = (D3D_RenderData *) renderer->driverdata;
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;

    return 0;
}

static int
D3D_GetTexturePalette(SDL_Renderer * renderer, SDL_Texture * texture,
                      SDL_Color * colors, int firstcolor, int ncolors)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;

    return 0;
}

static int
D3D_SetTextureColorMod(SDL_Renderer * renderer, SDL_Texture * texture)
{
    return 0;
}

static int
D3D_SetTextureAlphaMod(SDL_Renderer * renderer, SDL_Texture * texture)
{
    return 0;
}

static int
D3D_SetTextureBlendMode(SDL_Renderer * renderer, SDL_Texture * texture)
{
    switch (texture->blendMode) {
    case SDL_BLENDMODE_NONE:
    case SDL_BLENDMODE_MASK:
    case SDL_BLENDMODE_BLEND:
    case SDL_BLENDMODE_ADD:
    case SDL_BLENDMODE_MOD:
        return 0;
    default:
        SDL_Unsupported();
        texture->blendMode = SDL_BLENDMODE_NONE;
        return -1;
    }
}

static int
D3D_SetTextureScaleMode(SDL_Renderer * renderer, SDL_Texture * texture)
{
    switch (texture->scaleMode) {
    case SDL_TEXTURESCALEMODE_NONE:
    case SDL_TEXTURESCALEMODE_FAST:
    case SDL_TEXTURESCALEMODE_SLOW:
    case SDL_TEXTURESCALEMODE_BEST:
        return 0;
    default:
        SDL_Unsupported();
        texture->scaleMode = SDL_TEXTURESCALEMODE_NONE;
        return -1;
    }
    return 0;
}

static int
D3D_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                  const SDL_Rect * rect, const void *pixels, int pitch)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;
    D3D_RenderData *renderdata = (D3D_RenderData *) renderer->driverdata;

    if (data->yuv) {
        if (SDL_SW_UpdateYUVTexture(data->yuv, rect, pixels, pitch) < 0) {
            return -1;
        }
        UpdateYUVTextureData(texture);
        return 0;
    } else {
#ifdef SDL_MEMORY_POOL_DEFAULT
        IDirect3DTexture9 *temp;
        RECT d3drect;
        D3DLOCKED_RECT locked;
        const Uint8 *src;
        Uint8 *dst;
        int row, length;
        HRESULT result;

        result =
            IDirect3DDevice9_CreateTexture(renderdata->device, texture->w,
                                           texture->h, 1, 0,
                                           PixelFormatToD3DFMT(texture->
                                                               format),
                                           D3DPOOL_SYSTEMMEM, &temp, NULL);
        if (FAILED(result)) {
            D3D_SetError("CreateTexture()", result);
            return -1;
        }

        d3drect.left = rect->x;
        d3drect.right = rect->x + rect->w;
        d3drect.top = rect->y;
        d3drect.bottom = rect->y + rect->h;

        result = IDirect3DTexture9_LockRect(temp, 0, &locked, &d3drect, 0);
        if (FAILED(result)) {
            IDirect3DTexture9_Release(temp);
            D3D_SetError("LockRect()", result);
            return -1;
        }

        src = pixels;
        dst = locked.pBits;
        length = rect->w * SDL_BYTESPERPIXEL(texture->format);
        for (row = 0; row < rect->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += pitch;
            dst += locked.Pitch;
        }
        IDirect3DTexture9_UnlockRect(temp, 0);

        result =
            IDirect3DDevice9_UpdateTexture(renderdata->device,
                                           (IDirect3DBaseTexture9 *) temp,
                                           (IDirect3DBaseTexture9 *)
                                           data->texture);
        IDirect3DTexture9_Release(temp);
        if (FAILED(result)) {
            D3D_SetError("UpdateTexture()", result);
            return -1;
        }
#else
        RECT d3drect;
        D3DLOCKED_RECT locked;
        const Uint8 *src;
        Uint8 *dst;
        int row, length;
        HRESULT result;

        d3drect.left = rect->x;
        d3drect.right = rect->x + rect->w;
        d3drect.top = rect->y;
        d3drect.bottom = rect->y + rect->h;

        result =
            IDirect3DTexture9_LockRect(data->texture, 0, &locked, &d3drect,
                                       0);
        if (FAILED(result)) {
            D3D_SetError("LockRect()", result);
            return -1;
        }

        src = pixels;
        dst = locked.pBits;
        length = rect->w * SDL_BYTESPERPIXEL(texture->format);
        for (row = 0; row < rect->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += pitch;
            dst += locked.Pitch;
        }
        IDirect3DTexture9_UnlockRect(data->texture, 0);
#endif // SDL_MEMORY_POOL_DEFAULT

        return 0;
    }
}

static int
D3D_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                const SDL_Rect * rect, int markDirty, void **pixels,
                int *pitch)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;

    if (data->yuv) {
        return SDL_SW_LockYUVTexture(data->yuv, rect, markDirty, pixels,
                                     pitch);
    } else {
        RECT d3drect;
        D3DLOCKED_RECT locked;
        HRESULT result;

        d3drect.left = rect->x;
        d3drect.right = rect->x + rect->w;
        d3drect.top = rect->y;
        d3drect.bottom = rect->y + rect->h;

        result =
            IDirect3DTexture9_LockRect(data->texture, 0, &locked, &d3drect,
                                       markDirty ? 0 :
                                       D3DLOCK_NO_DIRTY_UPDATE);
        if (FAILED(result)) {
            D3D_SetError("LockRect()", result);
            return -1;
        }
        *pixels = locked.pBits;
        *pitch = locked.Pitch;
        return 0;
    }
}

static void
D3D_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;

    if (data->yuv) {
        SDL_SW_UnlockYUVTexture(data->yuv);
        UpdateYUVTextureData(texture);
    } else {
        IDirect3DTexture9_UnlockRect(data->texture, 0);
    }
}

static void
D3D_DirtyTexture(SDL_Renderer * renderer, SDL_Texture * texture, int numrects,
                 const SDL_Rect * rects)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;
    RECT d3drect;
    int i;

    for (i = 0; i < numrects; ++i) {
        const SDL_Rect *rect = &rects[i];

        d3drect.left = rect->x;
        d3drect.right = rect->x + rect->w;
        d3drect.top = rect->y;
        d3drect.bottom = rect->y + rect->h;

        IDirect3DTexture9_AddDirtyRect(data->texture, &d3drect);
    }
}

static void
D3D_SetBlendMode(D3D_RenderData * data, int blendMode)
{
    switch (blendMode) {
    case SDL_BLENDMODE_NONE:
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
                                        FALSE);
        break;
    case SDL_BLENDMODE_MASK:
    case SDL_BLENDMODE_BLEND:
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
                                        TRUE);
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLEND,
                                        D3DBLEND_SRCALPHA);
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLEND,
                                        D3DBLEND_INVSRCALPHA);
        break;
    case SDL_BLENDMODE_ADD:
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
                                        TRUE);
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLEND,
                                        D3DBLEND_SRCALPHA);
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLEND,
                                        D3DBLEND_ONE);
        break;
    case SDL_BLENDMODE_MOD:
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
                                        TRUE);
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLEND,
                                        D3DBLEND_ZERO);
        IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLEND,
                                        D3DBLEND_SRCCOLOR);
        break;
    }
}

static int
D3D_RenderDrawPoints(SDL_Renderer * renderer, const SDL_Point * points,
                     int count)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    DWORD color;
    Vertex *vertices;
    int i;
    HRESULT result;

    if (data->beginScene) {
        IDirect3DDevice9_BeginScene(data->device);
        data->beginScene = SDL_FALSE;
    }

    D3D_SetBlendMode(data, renderer->blendMode);

    result =
        IDirect3DDevice9_SetTexture(data->device, 0,
                                    (IDirect3DBaseTexture9 *) 0);
    if (FAILED(result)) {
        D3D_SetError("SetTexture()", result);
        return -1;
    }

    color = D3DCOLOR_ARGB(renderer->a, renderer->r, renderer->g, renderer->b);

    vertices = SDL_stack_alloc(Vertex, count);
    for (i = 0; i < count; ++i) {
        vertices[i].x = (float) points[i].x;
        vertices[i].y = (float) points[i].y;
        vertices[i].z = 0.0f;
        vertices[i].rhw = 1.0f;
        vertices[i].color = color;
        vertices[i].u = 0.0f;
        vertices[i].v = 0.0f;
    }
    result =
        IDirect3DDevice9_DrawPrimitiveUP(data->device, D3DPT_POINTLIST, count,
                                         vertices, sizeof(*vertices));
    SDL_stack_free(vertices);
    if (FAILED(result)) {
        D3D_SetError("DrawPrimitiveUP()", result);
        return -1;
    }
    return 0;
}

static int
D3D_RenderDrawLines(SDL_Renderer * renderer, const SDL_Point * points,
                    int count)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    DWORD color;
    Vertex *vertices;
    int i;
    HRESULT result;

    if (data->beginScene) {
        IDirect3DDevice9_BeginScene(data->device);
        data->beginScene = SDL_FALSE;
    }

    D3D_SetBlendMode(data, renderer->blendMode);

    result =
        IDirect3DDevice9_SetTexture(data->device, 0,
                                    (IDirect3DBaseTexture9 *) 0);
    if (FAILED(result)) {
        D3D_SetError("SetTexture()", result);
        return -1;
    }

    color = D3DCOLOR_ARGB(renderer->a, renderer->r, renderer->g, renderer->b);

    vertices = SDL_stack_alloc(Vertex, count);
    for (i = 0; i < count; ++i) {
        vertices[i].x = (float) points[i].x;
        vertices[i].y = (float) points[i].y;
        vertices[i].z = 0.0f;
        vertices[i].rhw = 1.0f;
        vertices[i].color = color;
        vertices[i].u = 0.0f;
        vertices[i].v = 0.0f;
    }
    result =
        IDirect3DDevice9_DrawPrimitiveUP(data->device, D3DPT_LINESTRIP, count-1,
                                         vertices, sizeof(*vertices));

    /* DirectX 9 has the same line rasterization semantics as GDI,
       so we need to close the endpoint of the line */
    if (points[0].x != points[count-1].x || points[0].y != points[count-1].y) {
        vertices[0].x = (float) points[count-1].x;
        vertices[0].y = (float) points[count-1].y;
        result = IDirect3DDevice9_DrawPrimitiveUP(data->device, D3DPT_POINTLIST, 1, vertices, sizeof(*vertices));
    }

    SDL_stack_free(vertices);
    if (FAILED(result)) {
        D3D_SetError("DrawPrimitiveUP()", result);
        return -1;
    }
    return 0;
}

static int
D3D_RenderDrawRects(SDL_Renderer * renderer, const SDL_Rect ** rects,
                    int count)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    DWORD color;
    int i;
    Vertex vertices[5];
    HRESULT result;

    if (data->beginScene) {
        IDirect3DDevice9_BeginScene(data->device);
        data->beginScene = SDL_FALSE;
    }

    D3D_SetBlendMode(data, renderer->blendMode);

    result =
        IDirect3DDevice9_SetTexture(data->device, 0,
                                    (IDirect3DBaseTexture9 *) 0);
    if (FAILED(result)) {
        D3D_SetError("SetTexture()", result);
        return -1;
    }

    color = D3DCOLOR_ARGB(renderer->a, renderer->r, renderer->g, renderer->b);

    for (i = 0; i < SDL_arraysize(vertices); ++i) {
        vertices[i].z = 0.0f;
        vertices[i].rhw = 1.0f;
        vertices[i].color = color;
        vertices[i].u = 0.0f;
        vertices[i].v = 0.0f;
    }

    for (i = 0; i < count; ++i) {
        const SDL_Rect *rect = rects[i];

        vertices[0].x = (float) rect->x;
        vertices[0].y = (float) rect->y;

        vertices[1].x = (float) rect->x+rect->w-1;
        vertices[1].y = (float) rect->y;

        vertices[2].x = (float) rect->x+rect->w-1;
        vertices[2].y = (float) rect->y+rect->h-1;

        vertices[3].x = (float) rect->x;
        vertices[3].y = (float) rect->y+rect->h-1;

        vertices[4].x = (float) rect->x;
        vertices[4].y = (float) rect->y;

        result =
            IDirect3DDevice9_DrawPrimitiveUP(data->device, D3DPT_LINESTRIP, 4,
                                             vertices, sizeof(*vertices));

        if (FAILED(result)) {
            D3D_SetError("DrawPrimitiveUP()", result);
            return -1;
        }
    }
    return 0;
}

static int
D3D_RenderFillRects(SDL_Renderer * renderer, const SDL_Rect ** rects,
                    int count)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    DWORD color;
    int i;
    float minx, miny, maxx, maxy;
    Vertex vertices[4];
    HRESULT result;

    if (data->beginScene) {
        IDirect3DDevice9_BeginScene(data->device);
        data->beginScene = SDL_FALSE;
    }

    D3D_SetBlendMode(data, renderer->blendMode);

    result =
        IDirect3DDevice9_SetTexture(data->device, 0,
                                    (IDirect3DBaseTexture9 *) 0);
    if (FAILED(result)) {
        D3D_SetError("SetTexture()", result);
        return -1;
    }

    color = D3DCOLOR_ARGB(renderer->a, renderer->r, renderer->g, renderer->b);

    for (i = 0; i < count; ++i) {
        const SDL_Rect *rect = rects[i];

        minx = (float) rect->x;
        miny = (float) rect->y;
        maxx = (float) rect->x + rect->w;
        maxy = (float) rect->y + rect->h;

        vertices[0].x = minx;
        vertices[0].y = miny;
        vertices[0].z = 0.0f;
        vertices[0].rhw = 1.0f;
        vertices[0].color = color;
        vertices[0].u = 0.0f;
        vertices[0].v = 0.0f;

        vertices[1].x = maxx;
        vertices[1].y = miny;
        vertices[1].z = 0.0f;
        vertices[1].rhw = 1.0f;
        vertices[1].color = color;
        vertices[1].u = 0.0f;
        vertices[1].v = 0.0f;

        vertices[2].x = maxx;
        vertices[2].y = maxy;
        vertices[2].z = 0.0f;
        vertices[2].rhw = 1.0f;
        vertices[2].color = color;
        vertices[2].u = 0.0f;
        vertices[2].v = 0.0f;

        vertices[3].x = minx;
        vertices[3].y = maxy;
        vertices[3].z = 0.0f;
        vertices[3].rhw = 1.0f;
        vertices[3].color = color;
        vertices[3].u = 0.0f;
        vertices[3].v = 0.0f;

        result =
            IDirect3DDevice9_DrawPrimitiveUP(data->device, D3DPT_TRIANGLEFAN,
                                             2, vertices, sizeof(*vertices));
        if (FAILED(result)) {
            D3D_SetError("DrawPrimitiveUP()", result);
            return -1;
        }
    }
    return 0;
}

static int
D3D_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
               const SDL_Rect * srcrect, const SDL_Rect * dstrect)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    D3D_TextureData *texturedata = (D3D_TextureData *) texture->driverdata;
    LPDIRECT3DPIXELSHADER9 shader = NULL;
    float minx, miny, maxx, maxy;
    float minu, maxu, minv, maxv;
    DWORD color;
    Vertex vertices[4];
    HRESULT result;

    if (data->beginScene) {
        IDirect3DDevice9_BeginScene(data->device);
        data->beginScene = SDL_FALSE;
    }

    minx = (float) dstrect->x - 0.5f;
    miny = (float) dstrect->y - 0.5f;
    maxx = (float) dstrect->x + dstrect->w - 0.5f;
    maxy = (float) dstrect->y + dstrect->h - 0.5f;

    minu = (float) srcrect->x / texture->w;
    maxu = (float) (srcrect->x + srcrect->w) / texture->w;
    minv = (float) srcrect->y / texture->h;
    maxv = (float) (srcrect->y + srcrect->h) / texture->h;

    color = D3DCOLOR_ARGB(texture->a, texture->r, texture->g, texture->b);

    vertices[0].x = minx;
    vertices[0].y = miny;
    vertices[0].z = 0.0f;
    vertices[0].rhw = 1.0f;
    vertices[0].color = color;
    vertices[0].u = minu;
    vertices[0].v = minv;

    vertices[1].x = maxx;
    vertices[1].y = miny;
    vertices[1].z = 0.0f;
    vertices[1].rhw = 1.0f;
    vertices[1].color = color;
    vertices[1].u = maxu;
    vertices[1].v = minv;

    vertices[2].x = maxx;
    vertices[2].y = maxy;
    vertices[2].z = 0.0f;
    vertices[2].rhw = 1.0f;
    vertices[2].color = color;
    vertices[2].u = maxu;
    vertices[2].v = maxv;

    vertices[3].x = minx;
    vertices[3].y = maxy;
    vertices[3].z = 0.0f;
    vertices[3].rhw = 1.0f;
    vertices[3].color = color;
    vertices[3].u = minu;
    vertices[3].v = maxv;

    D3D_SetBlendMode(data, texture->blendMode);

    if (texture->blendMode == SDL_BLENDMODE_MASK) {
        shader = data->ps_mask;
    }

    switch (texture->scaleMode) {
    case SDL_TEXTURESCALEMODE_NONE:
    case SDL_TEXTURESCALEMODE_FAST:
        IDirect3DDevice9_SetSamplerState(data->device, 0, D3DSAMP_MINFILTER,
                                         D3DTEXF_POINT);
        IDirect3DDevice9_SetSamplerState(data->device, 0, D3DSAMP_MAGFILTER,
                                         D3DTEXF_POINT);
        break;
    case SDL_TEXTURESCALEMODE_SLOW:
        IDirect3DDevice9_SetSamplerState(data->device, 0, D3DSAMP_MINFILTER,
                                         D3DTEXF_LINEAR);
        IDirect3DDevice9_SetSamplerState(data->device, 0, D3DSAMP_MAGFILTER,
                                         D3DTEXF_LINEAR);
        break;
    case SDL_TEXTURESCALEMODE_BEST:
        IDirect3DDevice9_SetSamplerState(data->device, 0, D3DSAMP_MINFILTER,
                                         D3DTEXF_GAUSSIANQUAD);
        IDirect3DDevice9_SetSamplerState(data->device, 0, D3DSAMP_MAGFILTER,
                                         D3DTEXF_GAUSSIANQUAD);
        break;
    }

    result =
        IDirect3DDevice9_SetTexture(data->device, 0, (IDirect3DBaseTexture9 *)
                                    texturedata->texture);
    if (FAILED(result)) {
        D3D_SetError("SetTexture()", result);
        return -1;
    }
    if (shader) {
        result = IDirect3DDevice9_SetPixelShader(data->device, shader);
        if (FAILED(result)) {
            D3D_SetError("SetShader()", result);
            return -1;
        }
    }
    result =
        IDirect3DDevice9_DrawPrimitiveUP(data->device, D3DPT_TRIANGLEFAN, 2,
                                         vertices, sizeof(*vertices));
    if (FAILED(result)) {
        D3D_SetError("DrawPrimitiveUP()", result);
        return -1;
    }
    if (shader) {
        result = IDirect3DDevice9_SetPixelShader(data->device, NULL);
        if (FAILED(result)) {
            D3D_SetError("SetShader()", result);
            return -1;
        }
    }
    return 0;
}

static int
D3D_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                     Uint32 format, void * pixels, int pitch)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    SDL_Window *window = renderer->window;
    SDL_VideoDisplay *display = window->display;
    D3DSURFACE_DESC desc;
    LPDIRECT3DSURFACE9 backBuffer;
    LPDIRECT3DSURFACE9 surface;
    RECT d3drect;
    D3DLOCKED_RECT locked;
    HRESULT result;

    result = IDirect3DDevice9_GetBackBuffer(data->device, 0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
    if (FAILED(result)) {
        D3D_SetError("GetBackBuffer()", result);
        return -1;
    }

    result = IDirect3DSurface9_GetDesc(backBuffer, &desc);
    if (FAILED(result)) {
        D3D_SetError("GetDesc()", result);
        IDirect3DSurface9_Release(backBuffer);
        return -1;
    }

    result = IDirect3DDevice9_CreateOffscreenPlainSurface(data->device, desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surface, NULL);
    if (FAILED(result)) {
        D3D_SetError("CreateOffscreenPlainSurface()", result);
        IDirect3DSurface9_Release(backBuffer);
        return -1;
    }

    result = IDirect3DDevice9_GetRenderTargetData(data->device, backBuffer, surface);
    if (FAILED(result)) {
        D3D_SetError("GetRenderTargetData()", result);
        IDirect3DSurface9_Release(surface);
        IDirect3DSurface9_Release(backBuffer);
        return -1;
    }

    d3drect.left = rect->x;
    d3drect.right = rect->x + rect->w;
    d3drect.top = rect->y;
    d3drect.bottom = rect->y + rect->h;

    result = IDirect3DSurface9_LockRect(surface, &locked, &d3drect, D3DLOCK_READONLY);
    if (FAILED(result)) {
        D3D_SetError("LockRect()", result);
        IDirect3DSurface9_Release(surface);
        IDirect3DSurface9_Release(backBuffer);
        return -1;
    }

    SDL_ConvertPixels(rect->w, rect->h,
                      display->current_mode.format, locked.pBits, locked.Pitch,
                      format, pixels, pitch);

    IDirect3DSurface9_UnlockRect(surface);

    IDirect3DSurface9_Release(surface);
    IDirect3DSurface9_Release(backBuffer);

    return 0;
}

static int
D3D_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                      Uint32 format, const void * pixels, int pitch)
{
    /* Work in progress */
    SDL_Unsupported();
    return -1;
}

static void
D3D_RenderPresent(SDL_Renderer * renderer)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
    HRESULT result;

    if (!data->beginScene) {
        IDirect3DDevice9_EndScene(data->device);
        data->beginScene = SDL_TRUE;
    }

    result = IDirect3DDevice9_TestCooperativeLevel(data->device);
    if (result == D3DERR_DEVICELOST) {
        /* We'll reset later */
        return;
    }
    if (result == D3DERR_DEVICENOTRESET) {
        D3D_Reset(renderer);
    }
    result = IDirect3DDevice9_Present(data->device, NULL, NULL, NULL, NULL);
    if (FAILED(result)) {
        D3D_SetError("Present()", result);
    }
}

static void
D3D_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    D3D_TextureData *data = (D3D_TextureData *) texture->driverdata;

    if (!data) {
        return;
    }
    if (data->yuv) {
        SDL_SW_DestroyYUVTexture(data->yuv);
    }
    if (data->texture) {
        IDirect3DTexture9_Release(data->texture);
    }
    SDL_free(data);
    texture->driverdata = NULL;
}

static void
D3D_DestroyRenderer(SDL_Renderer * renderer)
{
    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;

    if (data) {
        if (data->device) {
            IDirect3DDevice9_Release(data->device);
        }
        SDL_free(data);
    }
    SDL_free(renderer);
}

#endif /* SDL_VIDEO_RENDER_D3D */

/* vi: set ts=4 sw=4 expandtab: */


text:
@implementation NotePreviewController
-(void) dealloc {
    [allPages release];
    [chapter release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self _setupPreviewPageView];

    self.navigationItem.rightBarButtonItem = \
    [[[UIBarButtonItem alloc] initWithTitle:
      PF_L10N(@"buy") style:UIBarButtonItemStyleBordered target:self action:@selector(onBuy)] autorelease];
}

- (void)releaseViewElements {
    [super releaseViewElements];
    PF_Release_IBOutlet(previewPageView)
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.title = [productInfo valueForKey:NOTE_PRODUCT_TITLE];
    DECLARE_PFNOTE_MODEL
    chapter = [[model.note getChapter] copyWithZone:nil];
    [self _updatePreviewPage];
}

-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    DECLARE_PFUTILS
    [utils hideProgressHUD];
}

-(void) _setupPreviewPageView {
    previewPageView.pageConfig = [[PFNoteConfig alloc] init];
    DECLARE_PFNOTE_PAINTER_FACTORY
    previewPageView.pagePainter = [painterFactory factoryPagePainter];
    previewPageView.page = nil;
    previewPageView.delegate = self;
    previewPageView.backgroundColor = [UIColor clearColor];
    previewPageView.handlePinch = YES;
    [previewPageView initGestures];
}

-(void) _updatePreviewPage {
    DECLARE_PFNOTE_MODEL
    [previewPageView.pageConfig updateTo:model.config];
    previewPageView.pageConfig.showingControlCharactors = NO;

    if ([productInfo valueForKey:NOTE_PRODUCT_TYPE] == PFNoteProductTypeTheme) {
        NSString *themeType = [productInfo valueForKey:NOTE_PRODUCT_NAME];
        PFNoteConfig *noteConfig = (PFNoteConfig *)previewPageView.pageConfig;
        noteConfig.themeType = themeType;
        DECLARE_PFNOTE_PAINTER_FACTORY
        PFNoteTheme *theme = [painterFactory getThemeByType:themeType];
        DECLARE_PFNOTE_MODEL
        self.view.backgroundColor = [theme getPaperColor:[model iPadLandScape]];
    }

    [previewPageView.pagePainter refreshConfig];

    [self _onRepaintPreviewPage];
}

-(void) _onRepaintPreviewPage {
    DECLARE_PFNOTE_MODEL
    CGSize viewSize = previewPageView.frame.size;
    if (allPages) {
        [allPages release];
    }
    allPages = [[model.pager getPages:chapter withConfig:previewPageView.pageConfig forSize:viewSize] retain];
    previewPageView.page = [allPages objectAtIndex:0];
    [previewPageView setNeedsDisplay];
    DECLARE_PFUTILS
    [utils hideProgressHUD];
}

-(void) onPinch:(PFPageView *)pageView
         sender:(UIPinchGestureRecognizer *)sender {
    if (UIGestureRecognizerStateBegan == [sender state]) {
    } else if (UIGestureRecognizerStateChanged == [sender state]) {
    } else if (UIGestureRecognizerStateEnded == [sender state]) {
        previewPageView.pageConfig.factor = [PFNotePoint getFactor:previewPageView.pageConfig.factor scale:sender.scale];
    } else if (UIGestureRecognizerStateCancelled == [sender state]) {
    } else if (sender == nil) {
        [self _onRepaintPreviewPage];
    }
}

-(void) onProductPurchased:(NSNotification *)notification {
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

@end


text:
conf_external_interface = """# The external network interface
auto {{ public_interface }}
iface {{ public_interface }} inet manual
up ip link set dev $IFACE up
down ip link set dev $IFACE down"""


text:
//*********************** plan.js **************************//
//create namespace for field layout
plenty_admin.UI.plan = {
	DOM: 	$("#plan-container"),
	init: 	function(drilldownData){
		console.log("plan - init", drilldownData);
		plenty_admin.UI.currentScreen.fadeOut("normal");

		plenty_admin.UI.currentScreen = plenty_admin.UI.plan.DOM;

		plenty_admin.UI.currentScreen
		.addClass("fill-area-content flexbox-item-grow");

		plenty_admin.UI.plan.populate(drilldownData);
		plenty_admin.UI.plan.renderActivities(drilldownData);
		plenty_admin.UI.currentScreen.fadeIn("normal", function(){
			plenty_admin.UI.plan.renderActivityFinancesGraph(drilldownData);
		});
	},
	populate: function(drilldownData){
		console.log("plan - populate", drilldownData);
		if(Array.isArray(drilldownData)){
			var profit = 0;
			var expense = 0;
			var revenue = 0;
			var bushelsPerAcreTotal = 0;
			var cropPriceTotal = 0;
			var subsidyTotal = 0;
			var profitPerAcreTotal = 0;

			//loop active plans and total up values
			for(var a=0; a< drilldownData.length; a++){
				var plan = drilldownData[a];
				profit += plan.profitProjection.profit;
				expense += plan.profitProjection.expense;
				revenue += plan.profitProjection.revenue;
				bushelsPerAcreTotal += plan.profitProjection.avgBushlesPerAcre;
				cropPriceTotal += plan.profitProjection.cropPrice;
				subsidyTotal += plan.profitProjection.subsidy;
				profitPerAcreTotal += plan.profitProjection.profitPerAcre;
			}

			var bushelsPerAcreAvg = bushelsPerAcreTotal / drilldownData.length;
			var cropPriceAvg = cropPriceTotal / drilldownData.length;
			profitPerAcreAvg = profitPerAcreTotal / drilldownData.length;

			//populate fields with totalled data
			plenty_admin.UI.plan.DOM
			.find(".profit")
			.text(numeral(profit).format('$0,0.00'))
			.end()
			.find(".expense")
			.text(numeral(expense).format('$0,0.00'))
			.end()
			.find(".revenue")
			.text(numeral(revenue).format('$0,0.00'))
			.end()
			.find(".plan_field_acres")
			.text(drilldownData[0].field.acres)
			.end()
			.find(".plan_field_bushels_per_acre")
			.text(bushelsPerAcreAvg)
			.end()
			.find(".plan_field_price_per_bushel")
			.text(numeral(cropPriceAvg).format('$0,0.00'))
			.end()
			.find(".text-right.plan_field_subsidy_total")
			.text(numeral(subsidyTotal).format('$0,0.00'))
			.end()
			.find(".plan_field_profit_per_acre")
			.text(numeral(profitPerAcreAvg).format('$0,0.00'));

		}else{
			plenty_admin.UI.plan.DOM
			.find(".profit")
			.text(numeral(drilldownData.profitProjection.profit).format('$0,0.00'))
			.end()
			.find(".expense")
			.text(numeral(drilldownData.profitProjection.expense).format('$0,0.00'))
			.end()
			.find(".revenue")
			.text(numeral(drilldownData.profitProjection.revenue).format('$0,0.00'))
			.end()
			.find(".plan_field_acres")
			.text(drilldownData.field.acres)
			.end()
			.find(".plan_field_bushels_per_acre")
			.text(drilldownData.profitProjection.avgBushlesPerAcre)
			.end()
			.find(".plan_field_price_per_bushel")
			.text(numeral(drilldownData.profitProjection.cropPrice).format('$0,0.00'))
			.end()
			.find(".text-right.plan_field_subsidy_total")
			.text(numeral(drilldownData.profitProjection.subsidy).format('$0,0.00'))
			.end()
			.find(".plan_field_profit_per_acre")
			.text(numeral(drilldownData.profitProjection.profitPerAcre).format('$0,0.00'));

		}
	},
	clear: function(){
		console.log("plan - clear");
		if(plenty_admin.UI.plan.financesGraph){
			plenty_admin.UI.plan.financesGraph.destroy();
		}
	},
	renderActivityFinancesGraph: function(drilldownData){
		//console.log("renderActivityFinancesGraph", drilldownData, Array.isArray(drilldownData));
		if(Array.isArray(drilldownData)){
			var finances = [];
			for(var a=0; a< drilldownData.length; a++){
				for(var f=0; f<drilldownData[a].activities.activityFinances.length; f++){
					var finance = drilldownData[a].activities.activityFinances[f];
					finances.push(finance);
				}
			}
			//console.log("all finances: ", finances);
		}else{
			var finances = drilldownData.activities.activityFinances;
		}

		//holder for graph data set
		var financesData = [];

		//colour palette for graph segments
		var palette = new Rainbow();
		palette.setSpectrum("#0076b2", "#93b222", "#788912");
		palette.setNumberRange(0, (finances.length > 0 ? finances.length : 1));

		//for(index in finances){
		for(var a=0; a<finances.length; a++){
			var finance = finances[a];
			//console.log("finance", finance, plenty_admin.DATA.activityTypes[finance.activityTypeId]);
			finance.colour = "#"+palette.colourAt(a);

			var segment = {
				value:		finance.cost,
				color:		finance.colour,
				highlight:	plenty_admin.HELPER.colorLuminance(finance.colour, .4),
				label: 		plenty_admin.DATA.activityTypes[finance.activityTypeId].name,
			};

			financesData.push(segment);
		}

		var financeChartOptions = {
			legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend mrs\"><% for (var i=0; i<segments.length; i++){%><li data-segmentid=\"<%=i%>\" data-hovercolour=\"<%=segments[i].fillColor%>\" data-name=\"<%=segments[i].label.replace(/ /g, \"\").toLowerCase()%>\"><span class=\"swatch\" style=\"background-color:<%=segments[i].fillColor%>\"><i class=\"pif pif-<%=segments[i].label.toLowerCase().replace(/ /g, \"-\")%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%> <%= numeral(segments[i].value).format('$0,0.00') %>
<%}%>
",
			tooltipTemplate: "<%=label%>: <%= numeral(value).format('$0,0.00') %> | <%= numeral(circumference / 6.283).format('00.00%') %>",
			animateRotate: true
		};

		var helpers = Chart.helpers;

		//console.log("helpers", helpers);

		plenty_admin.UI.plan.financesGraph = new Chart(plenty_admin.UI.plan.financesGraphEl.get(0).getContext("2d")).Doughnut(financesData,financeChartOptions);

		//console.log("render finances graph: ", plenty_admin.UI.plan.financesGraph, financesData);

		//add a legend for this graph
		var $legendHTML = $(plenty_admin.UI.plan.financesGraph.generateLegend());

		var legendHolder =
		plenty_admin.UI.plan.financesGraphEl
		.parent()
		.parent()
		.parent()
		.find(".legend");

		legendHolder
		.html("")
		.append($legendHTML);

		var resetLegentStyle = function(legendHolder){
			$(legendHolder)
			.find("li")
			.css({"background-color": "transparent"})
			.removeClass("active")
			.find("span.swatch")
			.each(function(){
				$(this)
				.css({"background-color": $(this).closest("li").data("hovercolour")});
			})
			.end()
			.find("span.pct")
			.text("");
		}

		// Include a html legend template after the module doughnut itself
		helpers.each(legendHolder.get(0).firstChild.childNodes, function (legendNode, index) {
			helpers.addEvent(legendNode, 'mouseover', function () {
				var activeSegment = plenty_admin.UI.plan.financesGraph.segments[index];

				var pct = numeral(activeSegment.circumference / 6.283).format('00.00%');

				activeSegment.save();
				activeSegment.fillColor = activeSegment.highlightColor;
				activeSegment.innerRadius = 60;
				plenty_admin.UI.plan.financesGraph.showTooltip([activeSegment]);
				activeSegment.restore();

				$(legendNode)
				.css({"background-color": $(this).data("hovercolour")})
				.addClass("active")
				.find("span.swatch")
				.css({"background-color": activeSegment.highlightColor})
				.end()
				.find("span.pct")
				.text(pct);
			});
		});

		helpers.addEvent(legendHolder.get(0).firstChild, 'mouseout', function () {
			plenty_admin.UI.plan.financesGraph.draw();
			resetLegentStyle(legendHolder);
		});

		//highlight key element when hovering segment
		plenty_admin.UI.plan.financesGraphEl.on("mousemove", function(evt){
			var activePoints = plenty_admin.UI.plan.financesGraph.getSegmentsAtEvent(evt);
			if(activePoints.length > 0){
				//console.log("activePoints", activePoints, activePoints[0].label.replace(/ /g, "").toLowerCase());
				legendHolder
				.find("li")
				.removeClass("active");

				var labelId = activePoints[0].label.replace(/ /g, "").toLowerCase();
				var legendItem = legendHolder.find("li[data-name='"+labelId+"']");
				var pct = numeral(activePoints[0].circumference / 6.283).format('00.00%');

				resetLegentStyle(legendHolder);

				legendItem
				.addClass("active")
				.css({"background-color": legendItem.data("hovercolour")})
				.find("span.swatch")
				.css({"background-color": activePoints[0].highlightColor})
				.end()
				.find("span.pct")
				.text(pct);
			}else{
				resetLegentStyle(legendHolder);
			}
			// => activePoints is an array of segments on the canvas that are at the same position as the click event.
		});

		//clear segment highlight onMouseOut
		plenty_admin.UI.plan.financesGraphEl.on("mouseout", function(evt){
			resetLegentStyle(legendHolder);
		});
	},
	renderActivities: function(drilldownData){
		plenty_admin.UI.plan.activityListContainer
		.find("tr")
		.remove();

		function buildActivityFinances(activityFinances){
			//build the activity list item
			for(var a=0; a<activityFinances.length; a++){
				var activity = activityFinances[a].activityDto;
				activity.iconClass = plenty_admin.UI.field.getActivityIconClass(activity.activityTypeId);
				activity.startDate = plenty_admin.HELPER.formatJavaDate(activity.startTime);
				activity.endDate = plenty_admin.HELPER.formatJavaDate(activity.endTime);

				var activityItem = [
						"
",
							"",
								"",
							"	",
							"",
								activity.state,
							"	",
							"",
								plenty_admin.DATA.activityTypes[activity.activityTypeId].name,
							"	",
							"",
								activity.startDate.date,
							"	",
							"",
								plenty_admin.HELPER.daysFromHours(activity.durationInHours),
							"	",
							"",
								numeral(activity.cost).format('$0,0.00'),
							"	",
						"
"
				].join("");

				var $activityItem = $(activityItem);

				$activityItem
				.data("activity", activity)
				.data("activityFinance", activityFinances[a])
				.click(function(){
					plenty_admin.UI.plan.show_activity_modal($(this).data("activity"), $(this).data("activityFinance").taskFinances, $(this));
				});

				plenty_admin.UI.plan.activityListContainer.append($activityItem);
			}
		}

		if(Array.isArray(drilldownData)){
			for(var a=0; a< drilldownData.length; a++){
				var activityFinances = drilldownData[a].activities.activityFinances;
				buildActivityFinances(activityFinances);
			}
		}else{
			var activityFinances = drilldownData.activities.activityFinances;
			buildActivityFinances(activityFinances);
		}
	},
	show_activity_modal: function(activity, taskFinances, el){
		console.log("show_activity_modal", activity, taskFinances);
		plenty_admin.UI.plan.MODAL_activity
		.find(".modal-title")
		.text(plenty_admin.DATA.activityTypes[activity.activityTypeId].name)
		.end()
		.find("button.delete")
		.off("click")
		.on("click", function(){
				plenty_admin.UI.plan.MODAL_activity
				.find(".modal-content")
				.addClass("blur")
				.end()
				.find(".confirmDelete")
				.show();
		})
		.end()
		.find("button.cancel")
		.off("click")
		.on("click", function(){
				plenty_admin.UI.plan.MODAL_activity
				.find(".modal-content")
				.removeClass("blur")
				.end()
				.find(".confirmDelete")
				.hide();
		})
		.end()
		.find(".confirmDelete button.delete")
		.off("click")
		.on("click", function(){
			plenty_admin.REST.deleteActivity
			.delete(activity.id)
			.then(function(data){
				console.log("Activity Deleted:", data);
				plenty_admin.UI.plan.MODAL_activity
				.modal("hide");

				el
				.remove();
			})
		})
		.end()
		.on("shown.bs.modal", function(){
			plenty_admin.UI.plan.renderTaskFinancesGraph(taskFinances);
			plenty_admin.UI.plan.renderTasks(taskFinances);
		})
		.on("hidden.bs.modal", function(){
			plenty_admin.UI.plan.taskFinancesGraph.destroy();
		})
		.modal("show");
	},
	renderTasks: function(taskFinances){
		var taskRows = "";

		for(var t=0; t<taskFinances.length; t++){
			var task = taskFinances[t];
			var taskStartDate = plenty_admin.HELPER.formatJavaDate(task.taskDto.startTime);
			console.log("taskStartDate - ", taskStartDate, task.taskDto.startTime);
			var taskRow = [
				"
",
					"",
						task.taskDto.name,
					"	",
					"",
						task.taskDto.state,
					"	",
					"",
						plenty_admin.HELPER.formatJavaDate(task.taskDto.startTime).date,
					"	",
					"",
						plenty_admin.HELPER.daysFromHours(task.taskDto.durationInHours),
					"	",
					"",
						task.taskDto.cost,
					"	",
				"
",
			].join("");

			taskRows += taskRow;
		}

		$.fn.editable.defaults.mode = 'inline';

		plenty_admin.UI.plan.MODAL_activity
		.find(".activityTasksList table tbody tr")
		.remove()
		.end()
		.find(".activityTasksList table tbody")
		.append(taskRows)
		.find(".editable")
		.editable(plenty_admin.REST.inline_editing_options);
	},
	renderTaskFinancesGraph: function(taskFinances){
		console.log("renderTaskFinancesGraph", taskFinances);
		//colour palette for graph segments
		var palette = new Rainbow();
		palette.setSpectrum("#0076b2", "#93b222", "#788912");
		palette.setNumberRange(0, 2);

		//holder for graph data set
		var taskFinancesData = [
			//equipment
			{
				value:		0,
				color:		"#"+palette.colourAt(0),
				highlight:	plenty_admin.HELPER.colorLuminance("#"+palette.colourAt(0), .4),
				label: 		"Equipment",
			},
			//skill
			{
				value:		0,
				color:		"#"+palette.colourAt(1),
				highlight:	plenty_admin.HELPER.colorLuminance("#"+palette.colourAt(1), .4),
				label: 		"Labor",
			},
			//skill
			{
				value:		0,
				color:		"#"+palette.colourAt(2),
				highlight:	plenty_admin.HELPER.colorLuminance("#"+palette.colourAt(2), .4),
				label: 		"Products",
			},
		];

		//for(index in finances){
		for(var a=0; a<taskFinances.length; a++){
			//break the costs into equipment / skill / product
			var taskFinance = taskFinances[a];
			console.log("taskFinance", taskFinance);
			taskFinancesData[0].value += taskFinance.equipmentCost.cost;
			taskFinancesData[1].value += taskFinance.laborCost.cost;
			taskFinancesData[2].value += taskFinance.productsCost.cost;
		}

		var taskFinancesChartOptions = {
			legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend mts\"><% for (var i=0; i<segments.length; i++){%><li data-segmentid=\"<%=i%>\" data-hovercolour=\"<%=segments[i].fillColor%>\" data-name=\"<%=segments[i].label.replace(/ /g, \"\").toLowerCase()%>\" class=\"taskHeader\" style=\"border-top:2px solid <%=segments[i].fillColor%>\"><span class=\"swatch\" style=\"background-color:<%=segments[i].fillColor%>\"><i class=\"pif pif-<%=segments[i].label.toLowerCase().replace(/ /g, \"-\")%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%> <%= numeral(segments[i].value).format('$0,0.00') %>
<%}%>
",
			tooltipTemplate: "<%=label%>: <%= numeral(value).format('$0,0.00') %> | <%= numeral(circumference / 6.283).format('00.00%') %>",
			animateRotate: true
		};

		var helpers = Chart.helpers;

		console.log("helpers", helpers);

		plenty_admin.UI.plan.taskFinancesGraph = new Chart(plenty_admin.UI.plan.taskFinancesGraphEl.get(0).getContext("2d")).Doughnut(taskFinancesData,taskFinancesChartOptions);

		console.log("render task finances graph: ", plenty_admin.UI.plan.taskFinancesGraph, taskFinancesData);

		//add a legend for this graph
		var $legendHTML = $(plenty_admin.UI.plan.taskFinancesGraph.generateLegend());

		var legendHolder =
		plenty_admin.UI.plan.taskFinancesGraphEl
		.parent()
		.parent()
		.find(".legend");

		legendHolder
		.html("")
		.append($legendHTML);

		var equipmentItems = "";
		var laborItems = "";
		var productItems = "";

		//INJECT THE DIFFERENT TASK COST ELEMENTS INTO THE LEGEND ONCE BUILT
		//for(index in finances){
		for(var a=0; a<taskFinances.length; a++){
			//break the costs into equipment / skill / product
			var taskFinance = taskFinances[a];
			console.log("taskFinance", taskFinance);

			for(var e=0; e<taskFinance.equipmentCost.taskResourceTypeCosts.length; e++){
				var taskItem = taskFinance.equipmentCost.taskResourceTypeCosts[e];
				var bgColor = plenty_admin.HELPER.hexToRgb("#"+palette.colourAt(0));
				equipmentItems += "
"+taskItem.resourceTypeName+""+numeral(taskItem.cost).format('$0,0.00')+"
";

				//add task resource costs breakdown to task resource type costs (indented)
				for(var tr=0; tr<taskItem.taskResourceCosts.length; tr++){
					var resource = taskItem.taskResourceCosts[tr];
					equipmentItems += "
"+resource.resourceName+""+numeral(resource.cost).format('$0,0.00')+"
";
				}
			}

			for(var l=0; l<taskFinance.laborCost.taskResourceTypeCosts.length; l++){
				var taskItem = taskFinance.laborCost.taskResourceTypeCosts[l];
				var bgColor = plenty_admin.HELPER.hexToRgb("#"+palette.colourAt(1));
				laborItems += "
"+taskItem.resourceTypeName+""+numeral(taskItem.cost).format('$0,0.00')+"
";

				//add task resource costs breakdown to task resource type costs (indented)
				for(var tr=0; tr<taskItem.taskResourceCosts.length; tr++){
					var resource = taskItem.taskResourceCosts[tr];
					laborItems += "
"+resource.resourceName+""+numeral(resource.cost).format('$0,0.00')+"
";
				}
			}

			for(var p=0; p<taskFinance.productsCost.taskResourceTypeCosts.length; p++){
				var taskItem = taskFinance.productsCost.taskResourceTypeCosts[p];
				var bgColor = plenty_admin.HELPER.hexToRgb("#"+palette.colourAt(2));
				productItems += "
"+taskItem.resourceTypeName	+""+numeral(taskItem.cost).format('$0,0.00')+"
";

				//add task resource costs breakdown to task resource type costs (indented)
				for(var tr=0; tr<taskItem.taskResourceCosts.length; tr++){
					var resource = taskItem.taskResourceCosts[tr];
					productItems += "
"+resource.resourceName+""+numeral(resource.cost).format('$0,0.00')+"
";
				}
			}
		}

		console.log("equipmentItems", equipmentItems);
		console.log("laborItems", laborItems);
		console.log("productItems", productItems);

		legendHolder
		.find("li[data-name='equipment']")
		.after(equipmentItems)
		.end()
		.find("li[data-name='labor']")
		.after(laborItems)
		.end()
		.find("li[data-name='products']")
		.after(productItems)
		.end()
		.find(".equipmentTaskResourceItem")
		.last()
		.addClass("last")
		.end()
		.end()
		.find(".laborTaskResourceItem")
		.last()
		.addClass("last")
		.end()
		.end()
		.find(".productTaskResourceItem")
		.last()
		.addClass("last");

		var resetLegentStyle = function(legendHolder){
			$(legendHolder)
			.find("li:not(.taskItem):not(.taskResourceItem)")
			.css({"background-color": "transparent"})
			.removeClass("active")
			.find("span.swatch")
			.each(function(){
				$(this)
				.css({"background-color": $(this).closest("li").data("hovercolour")});
			})
			.end()
			.find("span.pct")
			.text("");
		}

		// Include a html legend template after the module doughnut itself
		helpers.each(legendHolder.get(0).firstChild.childNodes, function (legendNode, index) {
			helpers.addEvent(legendNode, 'mouseover', function () {
				console.log("hover legendNode: ", this, index, $(this).prop("class"));

				if($(this).hasClass("taskItem") || $(this).hasClass("taskResourceItem")){
					if($(this).hasClass("equipmentTaskItem") || $(this).hasClass("equipmentTaskResourceItem")){
						index = 0; //$(legendHolder).find("li[data-name='equipment']").index();
					}else if($(this).hasClass("laborTaskItem") || $(this).hasClass("laborTaskResourceItem")){
						index = 1; //$(legendHolder).find("li[data-name='labor']").index();
					}else if($(this).hasClass("productTaskItem") || $(this).hasClass("productTaskResourceItem")){
						index = 2; //$(legendHolder).find("li[data-name='products']").index();
					}
				}else{
					index = parseInt($(this).data("segmentid"));
				}

				console.log("index: ", index);

				if(!$(this).hasClass("taskItem") && !$(this).hasClass("taskResourceItem")){
					var activeSegment = plenty_admin.UI.plan.taskFinancesGraph.segments[index];

					var pct = numeral(activeSegment.circumference / 6.283).format('00.00%');

					activeSegment.save();
					activeSegment.fillColor = activeSegment.highlightColor;
					activeSegment.innerRadius = 60;
					plenty_admin.UI.plan.taskFinancesGraph.showTooltip([activeSegment]);
					activeSegment.restore();

					$(legendNode)
					.css({"background-color": $(this).data("hovercolour")})
					.addClass("active")
					.find("span.swatch")
					.css({"background-color": activeSegment.highlightColor})
					.end()
					.find("span.pct")
					.text(pct);
				}
			});
		});

		helpers.addEvent(legendHolder.get(0).firstChild, 'mouseout', function () {
			if($(this).hasClass("taskItem")){
				if($(this).hasClass("equipmentTaskItem") || $(this).hasClass("equipmentTaskResourceItem")){
					index = 0; //$(legendHolder).find("li[data-name='equipment']").index();
				}else if($(this).hasClass("laborTaskItem") || $(this).hasClass("laborTaskResourceItem")){
					index = 1; //$(legendHolder).find("li[data-name='labor']").index();
				}else if($(this).hasClass("productTaskItem") || $(this).hasClass("productTaskResourceItem")){
					index = 2; //$(legendHolder).find("li[data-name='products']").index();
				}
				//return; //no hover effect on task items just yet
			}
			plenty_admin.UI.plan.taskFinancesGraph.draw();
			if(!$(this).hasClass("taskItem") && !$(this).hasClass("taskResourceItem")){
				resetLegentStyle(legendHolder);
			}
		});

		//highlight key element when hovering segment
		plenty_admin.UI.plan.taskFinancesGraphEl.on("mousemove", function(evt){
			var activePoints = plenty_admin.UI.plan.taskFinancesGraph.getSegmentsAtEvent(evt);
			if(activePoints.length > 0){
				//console.log("activePoints", activePoints, activePoints[0].label.replace(/ /g, "").toLowerCase());
				legendHolder
				.find("li")
				.removeClass("active");

				var labelId = activePoints[0].label.replace(/ /g, "").toLowerCase();
				var legendItem = legendHolder.find("li[data-name='"+labelId+"']");
				var pct = numeral(activePoints[0].circumference / 6.283).format('00.00%');

				resetLegentStyle(legendHolder);

				legendItem
				.addClass("active")
				.css({"background-color": legendItem.data("hovercolour")})
				.find("span.swatch")
				.css({"background-color": activePoints[0].highlightColor})
				.end()
				.find("span.pct")
				.text(pct);
			}else{
				resetLegentStyle(legendHolder);
			}
			// => activePoints is an array of segments on the canvas that are at the same position as the click event.
		});

		//clear segment highlight onMouseOut
		plenty_admin.UI.plan.taskFinancesGraphEl.on("mouseout", function(evt){
			resetLegentStyle(legendHolder);
		});
	}
};

plenty_admin.UI.plan.activityListContainer = plenty_admin.UI.plan.DOM.find("table.planActivities tbody");
plenty_admin.UI.plan.financesGraphEl = plenty_admin.UI.plan.DOM.find("#plan_graph_wrapper canvas");
plenty_admin.UI.plan.MODAL_activity = $("body").find(".modal#activity");
plenty_admin.UI.plan.taskFinancesGraphEl = plenty_admin.UI.plan.MODAL_activity.find("canvas#taskGraph");


text:
alter session set "_ORACLE_SCRIPT"=true;

--Drop user testiaf_user cascade;

Create user testiaf_user identified by testiaf_user00 default tablespace users;

Grant dba to testiaf_user;
Grant resource to testiaf_user;
Grant connect to testiaf_user;

--DROP ROLE ROLE_WEBSPHERE_XA;
CREATE ROLE ROLE_WEBSPHERE_XA;
GRANT SELECT ON SYS.DBA_PENDING_TRANSACTIONS TO ROLE_WEBSPHERE_XA;
GRANT SELECT ON SYS.DBA_2PC_PENDING TO ROLE_WEBSPHERE_XA;
GRANT EXECUTE ON SYS.DBMS_SYSTEM TO ROLE_WEBSPHERE_XA;
GRANT SELECT ON SYS.PENDING_TRANS$ TO ROLE_WEBSPHERE_XA;

Grant ROLE_WEBSPHERE_XA to testiaf_user;

-- http://docs.codehaus.org/display/BTM/FAQ
grant select on sys.dba_pending_transactions to testiaf_user;
grant select on sys.pending_trans$ to testiaf_user;
grant select on sys.dba_2pc_pending to testiaf_user;
grant execute on sys.dbms_system to testiaf_user;
commit;

exit


text:
var ContextMenu = {
	x: 0,
	y: 0,
	init: function(){

		$(function() {
			$(this).bind("contextmenu", function(e) {
				e.preventDefault();
				$("#context_menu").show().css("top",e.pageY).css("left",e.pageX);
				ContextMenu.x = Input.x;
				ContextMenu.y = Input.y;
				if(Input.overPic){
					if(!$("#clipped_range").length){
						$("#context_copy, #context_cut, #context_delete, #context_flipx, #context_flipy").addClass("disabled_context_item");
					}else{
						$("#context_copy, #context_cut, #context_delete, #context_flipx, #context_flipy").removeClass("disabled_context_item");
					}
					if(Yang.toolName == "magicwand"){
						$("#context_copy, #context_cut, #context_delete").removeClass("disabled_context_item");
					}
					if($(".active_clipboard_canvas").length){
						$("#context_paste").removeClass("disabled_context_item");
					}else{
						$("#context_paste").addClass("disabled_context_item");
					}
				}else{
					$(".context_menu_item").addClass("disabled_context_item");
				}

			});
		});

		$(".context_menu_item").click(function(){
			if(!$(this).hasClass("disabled_context_item")){
				$("#context_menu").hide();
				ContextMenu[$(this).attr("id")]();
			}
		});

	},
	context_copy: function(){
		if(Clipboard.range || Yang.toolName == "magicwand"){
			if(Yang.tool.finish){
				Yang.tool.finish();
			}

			$("#clipboard_menu, #clipboard_list").show();
			var canvas;
			if(Yang.toolName == "magicwand"){
				var x = Pic.w;
				var y = Pic.h;
				var xMax = 0;
				var yMax = 0;
				var pxSet = Tools.magicwand.pxSet;
				for(var i = 0; i < pxSet.length; i++){
					if(pxSet[i] < x){
						x = pxSet[i];
					}
					if(pxSet[i] > xMax){
						xMax = pxSet[i];
					}
					i++;
					if(pxSet[i] < y){
						y = pxSet[i];
					}
					if(pxSet[i] > yMax){
						yMax = pxSet[i];
					}
				}
				Clipboard.range = {x: x, y: y, w: xMax-x, h:yMax-y};
				canvas = document.createElement("canvas");
				canvas.width = Clipboard.range.w;
				canvas.height = Clipboard.range.h;
				var ctx = canvas.getContext("2d");
				ctx.save();

				ctx.translate(-x,-y);
				ctx.drawImage(Tools.magicwand.getCanvas(),0,0);
				ctx.globalCompositeOperation = "source-in";
				ctx.drawImage($("#canvas_layer" + Yang.layer)[0],0,0);
				//console.log(Tools.magicwand.canvas.toDataURL());
				//console.log(canvas.toDataURL());
				//console.log(canvas.width);
				ctx.restore();
				//Clipboard.data = canvas;
				//ctx.drawImage(Clipboard.data,0,0,Clipboard.range.w, Clipboard.range.h);
			}else{
				canvas = document.createElement("canvas");
				canvas.width = Clipboard.range.w;
				canvas.height = Clipboard.range.h;
				var ctx = canvas.getContext("2d");
				if(!Clipboard.data){
					Clipboard.press();
				}
				ctx.drawImage(Clipboard.data,0,0,Clipboard.range.w, Clipboard.range.h);
			}

			Clipboard.copyDataIndex = Clipboard.copyData.length;
			$(".active_clipboard_canvas").removeClass("active_clipboard_canvas");
			canvas.setAttribute("id", "clipboard_data" + Clipboard.copyDataIndex);
			canvas.setAttribute("class", "clipboard_canvas active_clipboard_canvas");
			canvas.setAttribute("data-index", Clipboard.copyDataIndex);
			canvas.setAttribute("data-w", Math.round(Clipboard.range.w));
			canvas.setAttribute("data-h", Math.round(Clipboard.range.h));
			$("#clipboard_list").append(canvas);
			Clipboard.copyData.push({
				data: canvas,
				width: Clipboard.range.w,
				height: Clipboard.range.h
			});

			$("#clipboard_data" + Clipboard.copyDataIndex).click(function(){
				$(".active_clipboard_canvas").removeClass("active_clipboard_canvas");
				$(this).addClass("active_clipboard_canvas");
			});

			$("#clipboard_list").animate({scrollTop:$("#clipboard_list")[0].scrollHeight - $("#clipboard_list").height()}, '500', 'swing');

		}

	},
	context_cut: function(){
		if(Clipboard.range || Yang.toolName == "magicwand"){
			if(Yang.toolName == "selectbox" || Yang.toolName == "selectfree" || Yang.toolName == "magicwand"){
				$("#clipboard_menu, #clipboard_list").show();
				ContextMenu.context_copy();
				ContextMenu.context_delete();
			}
		}
	},
    context_paste: function(){
        if(Clipboard.data){
            if(Yang.tool.name != 'selectbox' && Yang.tool.name != 'freeselect'){
					$("#selector").trigger("click");
		    }

				var w = parseInt($(".active_clipboard_canvas").first().attr("data-w"));
				var h = parseInt($(".active_clipboard_canvas").first().attr("data-h"));
				var x = Math.round(Input.x-w/2);
				var y = Math.round(Input.y-h/2);
				if(x < 0){
					x = 0
				}else if(x + w > Pic.w){
					x = Pic.w - w;
				}
				if(y < 0){
					y = 0
				}else if(y + h > Pic.h){
					y = Pic.h - h;
				}

				var details = {
					tool: "upload",
					data: $(".active_clipboard_canvas")[0],
					layer: Yang.layer,
					x : x,
					y : y,
					start: {realTool:"paste"}
				}

				History.act(details, Yang.ctx);
				History.add({
					tool:"upload",
					layer: Yang.layer,
					isDummy: 1
				});
				//History.add(details);
				Clipboard.start = {
					x : x,
					y : y,
					w : w,
					h : h,
					nodelete: 1,
					path : [],
					theta : 0
				};
				Clipboard.data = $(".active_clipboard_canvas")[0];
				Clipboard.range = $.extend({}, Clipboard.start);
				Clipboard.prev = $.extend({}, Clipboard.start);
				Clipboard.start.realTool = "upload";
				Yang.ctx.clearRect(0,0,Pic.w,Pic.h);
				Clipboard.makeRange();
				Clipboard.dashRange();
				Clipboard.drawData(Yang.ctx);
        }
    },
	context_delete: function(){
		if(Clipboard.range || Yang.toolName == "magicwand"){
			if(Yang.tool.deletePress != undefined){
				Yang.tool.deletePress();
				Clipboard.range = 0;
			}
		}
	},
	context_flipx: function(){
		if(Clipboard.range.flipX == undefined || !Clipboard.range.flipX){
			Clipboard.range.flipX = 1;
		}else{
			Clipboard.range.flipX = 0;
		}
		Yang.ctx.clearRect(0,0,Pic.w,Pic.h);
		Clipboard.dashRange();
		Clipboard.drawData(Yang.ctx);
	},
	context_flipy: function(){

		if(Clipboard.range.flipY == undefined || !Clipboard.range.flipY){
			Clipboard.range.flipY = 1;
		}else{
			Clipboard.range.flipY = 0;
		}
		Yang.ctx.clearRect(0,0,Pic.w,Pic.h);
		Clipboard.dashRange();
		Clipboard.drawData(Yang.ctx);
	}
};


text:
package com.deercoder.dc.proj2;
public abstract class Entity
{
    // Each entity will have a distance table
    protected int[][] distanceTable = new int[NetworkSimulator.NUMENTITIES]
                                           [NetworkSimulator.NUMENTITIES];

    // The update function.  Will have to be written in subclasses by students
    public abstract void update(Packet p);

    // The link cost change handlder.  Will have to be written in appropriate
    // subclasses by students.  Note that only Entity0 and Entity1 will need
    // this, and only if extra credit is being done
    public abstract void linkCostChangeHandler(int whichLink, int newCost);

    // Print the distance table of the current entity.
    protected abstract void printDT();

}