text:
extern "C"
{
#endif

//*****************************************************************************
//
//! This structure defines the extents of a rectangle.  All points greater than
//! or equal to the minimum and less than or equal to the maximum are part of
//! the rectangle.
//
//*****************************************************************************
typedef struct
{
    //
    //! The minimum X coordinate of the rectangle.
    //
    short sXMin;

    //
    //! The minimum Y coordinate of the rectangle.
    //
    short sYMin;

    //
    //! The maximum X coordinate of the rectangle.
    //
    short sXMax;

    //
    //! The maximum Y coordinate of the rectangle.
    //
    short sYMax;
}
tRectangle;

//*****************************************************************************
//
//! This structure defines the characteristics of a display driver.
//
//*****************************************************************************
typedef struct
{
    //
    //! The size of this structure.
    //
    int lSize;

    //
    //! A pointer to display driver-specific data.
    //
    void *pvDisplayData;

    //
    //! The width of this display.
    //
    unsigned short usWidth;

    //
    //! The height of this display.
    //
    unsigned short usHeight;

    //
    //! A pointer to the function to draw a pixel on this display.
    //
    void (*pfnPixelDraw)(void *pvDisplayData, int lX, int lY,
                         unsigned int ulValue);

    //
    //! A pointer to the function to draw multiple pixels on this display.
    //
    void (*pfnPixelDrawMultiple)(void *pvDisplayData, int lX, int lY,
                                 int lX0, int lCount, int lBPP,
                                 const unsigned char *pucData,
                                 const unsigned char *pucPalette);

    //
    //! A pointer to the function to draw a horizontal line on this display.
    //
    void (*pfnLineDrawH)(void *pvDisplayData, int lX1, int lX2, int lY,
                         unsigned int ulValue);

    //
    //! A pointer to the function to draw a vertical line on this display.
    //
    void (*pfnLineDrawV)(void *pvDisplayData, int lX, int lY1, int lY2,
                         unsigned int ulValue);

    //
    //! A pointer to the function to draw a filled rectangle on this display.
    //
    void (*pfnRectFill)(void *pvDisplayData, const tRectangle *pRect,
                        unsigned int ulValue);

    //
    //! A pointer to the function to translate 24-bit RGB colors to
    //! display-specific colors.
    //
    unsigned int (*pfnColorTranslate)(void *pvDisplayData,
                                       unsigned int ulValue);

    //
    //! A pointer to the function to flush any cached drawing operations on
    //! this display.
    //
    void (*pfnFlush)(void *pvDisplayData);
}
tDisplay;

//*****************************************************************************
//
//! This structure describes a font used for drawing text onto the screen.
//
//*****************************************************************************
typedef struct
{
    //
    //! The format of the font.  Can be one of FONT_FMT_UNCOMPRESSED or
    //! FONT_FMT_PIXEL_RLE.
    //
    unsigned char ucFormat;

    //
    //! The maximum width of a character; this is the width of the widest
    //! character in the font, though any individual character may be narrower
    //! than this width.
    //
    unsigned char ucMaxWidth;

    //
    //! The height of the character cell; this may be taller than the font data
    //! for the characters (to provide inter-line spacing).
    //
    unsigned char ucHeight;

    //
    //! The offset between the top of the character cell and the baseline of
    //! the glyph.  The baseline is the bottom row of a capital letter, below
    //! which only the descenders of the lower case letters occur.
    //
    unsigned char ucBaseline;

    //
    //! The offset within pucData to the data for each character in the font.
    //
    unsigned short pusOffset[96];

    //
    //! A pointer to the data for the font.
    //
    const unsigned char *pucData;
}
tFont;

//*****************************************************************************
//
//! Indicates that the font data is stored in an uncompressed format.
//
//*****************************************************************************
#define FONT_FMT_UNCOMPRESSED   0x00

//*****************************************************************************
//
//! Indicates that the font data is stored using a pixel-based RLE format.
//
//*****************************************************************************
#define FONT_FMT_PIXEL_RLE      0x01

//*****************************************************************************
//
//! Indicates that the image data is not compressed and represents each pixel
//! with a single bit.
//
//*****************************************************************************
#define IMAGE_FMT_1BPP_UNCOMP   0x01

//*****************************************************************************
//
//! Indicates that the image data is not compressed and represents each pixel
//! with four bits.
//
//*****************************************************************************
#define IMAGE_FMT_4BPP_UNCOMP   0x04

//*****************************************************************************
//
//! Indicates that the image data is not compressed and represents each pixel
//! with eight bits.
//
//*****************************************************************************
#define IMAGE_FMT_8BPP_UNCOMP   0x08

//*****************************************************************************
//
//! Indicates that the image data is compressed and represents each pixel with
//! a single bit.
//
//*****************************************************************************
#define IMAGE_FMT_1BPP_COMP     0x81

//*****************************************************************************
//
//! Indicates that the image data is compressed and represents each pixel with
//! four bits.
//
//*****************************************************************************
#define IMAGE_FMT_4BPP_COMP     0x84

//*****************************************************************************
//
//! Indicates that the image data is compressed and represents each pixel with
//! eight bits.
//
//*****************************************************************************
#define IMAGE_FMT_8BPP_COMP     0x88

#define IMAGE_FMT_16BPP_UNCOMP   0x10
#define IMAGE_FMT_16BPP_COMP     0x90

#define IMAGE_FMT_24BPP_UNCOMP   0x20
#define IMAGE_FMT_24BPP_COMP     0xA0

//*****************************************************************************
//
//! This structure defines a drawing context to be used to draw onto the
//! screen.  Multiple drawing contexts may exist at any time.
//
//*****************************************************************************
typedef struct
{
    //
    //! The size of this structure.
    //
    int lSize;

    //
    //! The screen onto which drawing operations are performed.
    //
    const tDisplay *pDisplay;

    //
    //! The clipping region to be used when drawing onto the screen.
    //
    tRectangle sClipRegion;

    //
    //! The color used to draw primitives onto the screen.
    //
    unsigned int ulForeground;

    //
    //! The background color used to draw primitives onto the screen.
    //
    unsigned int ulBackground;

    //
    //! The font used to render text onto the screen.
    //
    const tFont *pFont;
}
tContext;

//*****************************************************************************
//
//! Sets the background color to be used.
//!
//! \param pContext is a pointer to the drawing context to modify.
//! \param ulValue is the 24-bit RGB color to be used.
//!
//! This function sets the background color to be used for drawing operations
//! in the specified drawing context.
//!
//! \return None.
//
//*****************************************************************************
#define GrContextBackgroundSet(pContext, ulValue)                        \
        do                                                               \
        {                                                                \
            tContext *pC = pContext;                                     \
            pC->ulBackground = DpyColorTranslate(pC->pDisplay, ulValue); \
        }                                                                \
        while(0)

//*****************************************************************************
//
//! Sets the background color to be used.
//!
//! \param pContext is a pointer to the drawing context to modify.
//! \param ulValue is the display driver-specific color to be used.
//!
//! This function sets the background color to be used for drawing operations
//! in the specified drawing context, using a color that has been previously
//! translated to a driver-specific color (for example, via
//! DpyColorTranslate()).
//!
//! \return None.
//
//*****************************************************************************
#define GrContextBackgroundSetTranslated(pContext, ulValue) \
        do                                                  \
        {                                                   \
            tContext *pC = pContext;                        \
            pC->ulBackground = ulValue;                     \
        }                                                   \
        while(0)

//*****************************************************************************
//
//! Gets the width of the display being used by this drawing context.
//!
//! \param pContext is a pointer to the drawing context to query.
//!
//! This function returns the width of the display that is being used by this
//! drawing context.
//!
//! \return Returns the width of the display in pixels.
//
//*****************************************************************************
#define GrContextDpyWidthGet(pContext)      \
        (DpyWidthGet((pContext)->pDisplay))

//*****************************************************************************
//
//! Gets the height of the display being used by this drawing context.
//!
//! \param pContext is a pointer to the drawing context to query.
//!
//! This function returns the height of the display that is being used by this
//! drawing context.
//!
//! \return Returns the height of the display in pixels.
//
//*****************************************************************************
#define GrContextDpyHeightGet(pContext)      \
        (DpyHeightGet((pContext)->pDisplay))

//*****************************************************************************
//
//! Sets the font to be used.
//!
//! \param pContext is a pointer to the drawing context to modify.
//! \param pFnt is a pointer to the font to be used.
//!
//! This function sets the font to be used for string drawing operations in the
//! specified drawing context.
//!
//! \return None.
//
//*****************************************************************************
#define GrContextFontSet(pContext, pFnt) \
        do                               \
        {                                \
            tContext *pC = pContext;     \
            const tFont *pF = pFnt;      \
            pC->pFont = pF;              \
        }                                \
        while(0)

//*****************************************************************************
//
//! Sets the foreground color to be used.
//!
//! \param pContext is a pointer to the drawing context to modify.
//! \param ulValue is the 24-bit RGB color to be used.
//!
//! This function sets the color to be used for drawing operations in the
//! specified drawing context.
//!
//! \return None.
//
//*****************************************************************************
#define GrContextForegroundSet(pContext, ulValue)                        \
        do                                                               \
        {                                                                \
            tContext *pC = pContext;                                     \
            pC->ulForeground = DpyColorTranslate(pC->pDisplay, ulValue); \
        }                                                                \
        while(0)

//*****************************************************************************
//
//! Sets the foreground color to be used.
//!
//! \param pContext is a pointer to the drawing context to modify.
//! \param ulValue is the display driver-specific color to be used.
//!
//! This function sets the foreground color to be used for drawing operations
//! in the specified drawing context, using a color that has been previously
//! translated to a driver-specific color (for example, via
//! DpyColorTranslate()).
//!
//! \return None.
//
//*****************************************************************************
#define GrContextForegroundSetTranslated(pContext, ulValue) \
        do                                                  \
        {                                                   \
            tContext *pC = pContext;                        \
            pC->ulForeground = ulValue;                     \
        }                                                   \
        while(0)

//*****************************************************************************
//
//! Flushes any cached drawing operations.
//!
//! \param pContext is a pointer to the drawing context to use.
//!
//! This function flushes any cached drawing operations.  For display drivers
//! that draw into a local frame buffer before writing to the actual display,
//! calling this function will cause the display to be updated to match the
//! contents of the local frame buffer.
//!
//! \return None.
//
//*****************************************************************************
#define GrFlush(pContext)                  \
        do                                 \
        {                                  \
            const tContext *pC = pContext; \
            DpyFlush(pC->pDisplay);        \
        }                                  \
        while(0)

//*****************************************************************************
//
//! Gets the baseline of a font.
//!
//! \param pFont is a pointer to the font to query.
//!
//! This function determines the baseline position of a font.  The baseline is
//! the offset between the top of the font and the bottom of the capital
//! letters.  The only font data that exists below the baseline are the
//! descenders on some lower-case letters (such as ``y'').
//!
//! \return Returns the baseline of the font, in pixels.
//
//*****************************************************************************
#define GrFontBaselineGet(pFont) \
        ((pFont)->ucBaseline)

//*****************************************************************************
//
//! Gets the height of a font.
//!
//! \param pFont is a pointer to the font to query.
//!
//! This function determines the height of a font.  The height is the offset
//! between the top of the font and the bottom of the font, including any
//! ascenders and descenders.
//!
//! \return Returns the height of the font, in pixels.
//
//*****************************************************************************
#define GrFontHeightGet(pFont) \
        ((pFont)->ucHeight)

//*****************************************************************************
//
//! Gets the maximum width of a font.
//!
//! \param pFont is a pointer to the font to query.
//!
//! This function determines the maximum width of a font.  The maximum width is
//! the width of the widest individual character in the font.
//!
//! \return Returns the maximum width of the font, in pixels.
//
//*****************************************************************************
#define GrFontMaxWidthGet(pFont) \
        ((pFont)->ucMaxWidth)

//*****************************************************************************
//
//! Gets the number of colors in an image.
//!
//! \param pucImage is a pointer to the image to query.
//!
//! This function determines the number of colors in the palette of an image.
//! This is only valid for 4bpp and 8bpp images; 1bpp images do not contain a
//! palette.
//!
//! \return Returns the number of colors in the image.
//
//*****************************************************************************
#define GrImageColorsGet(pucImage)           \
        (((unsigned char *)pucImage)[5] + 1)

//*****************************************************************************
//
//! Gets the height of an image.
//!
//! \param pucImage is a pointer to the image to query.
//!
//! This function determines the height of an image in pixels.
//!
//! \return Returns the height of the image in pixels.
//
//*****************************************************************************
#define GrImageHeightGet(pucImage)          \
        ((unsigned short)(*(pucImage+4) << 8) | *(pucImage+3))

//*****************************************************************************
//
//! Gets the width of an image.
//!
//! \param pucImage is a pointer to the image to query.
//!
//! This function determines the width of an image in pixels.
//!
//! \return Returns the width of the image in pixels.
//
//*****************************************************************************
#define GrImageWidthGet(pucImage)           \
		   ((unsigned short)(*(pucImage+2) << 8) | *(pucImage+1))

//*****************************************************************************
//
//! Determines the size of the buffer for a 1 BPP off-screen image.
//!
//! \param lWidth is the width of the image in pixels.
//! \param lHeight is the height of the image in pixels.
//!
//! This function determines the size of the memory buffer required to hold a
//! 1 BPP off-screen image of the specified geometry.
//!
//! \return Returns the number of bytes required by the image.
//
//*****************************************************************************
#define GrOffScreen1BPPSize(lWidth, lHeight) \
        (5 + (((lWidth + 7) / 8) * lHeight))

//*****************************************************************************
//
//! Determines the size of the buffer for a 4 BPP off-screen image.
//!
//! \param lWidth is the width of the image in pixels.
//! \param lHeight is the height of the image in pixels.
//!
//! This function determines the size of the memory buffer required to hold a
//! 4 BPP off-screen image of the specified geometry.
//!
//! \return Returns the number of bytes required by the image.
//
//*****************************************************************************
#define GrOffScreen4BPPSize(lWidth, lHeight)            \
        (6 + (16 * 3) + (((lWidth + 1) / 2) * lHeight))

//*****************************************************************************
//
//! Determines the size of the buffer for a 16 BPP off-screen image.
//!
//! \param lWidth is the width of the image in pixels.
//! \param lHeight is the height of the image in pixels.
//!
//! This function determines the size of the memory buffer required to hold a
//! 16 BPP off-screen image of the specified geometry.
//!
//! \return Returns the number of bytes required by the image.
//
//*****************************************************************************
#define GrOffScreen16BPPSize(lWidth, lHeight)            \
        (4 + (16*2) + (lWidth * lHeight * 2))

//*****************************************************************************
//
//! Determines the size of the buffer for a 24 BPP off-screen image.
//!
//! \param lWidth is the width of the image in pixels.
//! \param lHeight is the height of the image in pixels.
//!
//! This function determines the size of the memory buffer required to hold a
//! 16 BPP off-screen image of the specified geometry.
//!
//! \return Returns the number of bytes required by the image.
//
//*****************************************************************************
#define GrOffScreen24BPPSize(lWidth, lHeight, pack)            \
        (4 + (8*4) + (lWidth * lHeight * (3+pack)))

//*****************************************************************************
//
//! Determines the size of the buffer for an 8 BPP off-screen image.
//!
//! \param lWidth is the width of the image in pixels.
//! \param lHeight is the height of the image in pixels.
//!
//! This function determines the size of the memory buffer required to hold an
//! 8 BPP off-screen image of the specified geometry.
//!
//! \return Returns the number of bytes required by the image.
//
//*****************************************************************************
#define GrOffScreen8BPPSize(lWidth, lHeight) \
        (6 + (256 * 3) + (lWidth * lHeight))

//*****************************************************************************
//
//! Draws a pixel.
//!
//! \param pContext is a pointer to the drawing context to use.
//! \param lX is the X coordinate of the pixel.
//! \param lY is the Y coordinate of the pixel.
//!
//! This function draws a pixel if it resides within the clipping region.
//!
//! \return None.
//
//*****************************************************************************
#define GrPixelDraw(pContext, lX, lY)                                 \
        do                                                            \
        {                                                             \
            const tContext *pC = pContext;                            \
            if((lX >= pC->sClipRegion.sXMin) &&                       \
               (lX <= pC->sClipRegion.sXMax) &&                       \
               (lY >= pC->sClipRegion.sYMin) &&                       \
               (lY <= pC->sClipRegion.sYMax))                         \
            {                                                         \
                DpyPixelDraw(pC->pDisplay, lX, lY, pC->ulForeground); \
            }                                                         \
        }                                                             \
        while(0)

//*****************************************************************************
//
//! Gets the baseline of a string.
//!
//! \param pContext is a pointer to the drawing context to query.
//!
//! This function determines the baseline position of a string.  The baseline
//! is the offset between the top of the string and the bottom of the capital
//! letters.  The only string data that exists below the baseline are the
//! descenders on some lower-case letters (such as ``y'').
//!
//! \return Returns the baseline of the string, in pixels.
//
//*****************************************************************************
#define GrStringBaselineGet(pContext)   \
        ((pContext)->pFont->ucBaseline)

//*****************************************************************************
//
//! Draws a centered string.
//!
//! \param pContext is a pointer to the drawing context to use.
//! \param pcString is a pointer to the string to be drawn.
//! \param lLength is the number of characters from the string that should be
//! drawn on the screen.
//! \param lX is the X coordinate of the center of the string position on the
//! screen.
//! \param lY is the Y coordinate of the center of the string position on the
//! screen.
//! \param bOpaque is \b true if the background of each character should be
//! drawn and \b false if it should not (leaving the background as is).
//!
//! This function draws a string of test on the screen centered upon the
//! provided position.  The \e lLength parameter allows a portion of the
//! string to be examined without having to insert a NULL character at the
//! stopping point (which would not be possible if the string was located in
//! flash); specifying a length of -1 will cause the entire string to be
//! rendered (subject to clipping).
//!
//! \return None.
//
//*****************************************************************************
#define GrStringDrawCentered(pContext, pcString, lLength, lX, lY, bOpaque)  \
        do                                                                  \
        {                                                                   \
            const tContext *pC = pContext;                                  \
            const char *pcStr = pcString;                                   \
                                                                            \
            GrStringDraw(pC, pcStr, lLength,                                \
                         (lX) - (GrStringWidthGet(pC, pcStr, lLength) / 2), \
                         (lY) - (pC->pFont->ucBaseline / 2), bOpaque);      \
        }                                                                   \
        while(0)

//*****************************************************************************
//
//! Gets the height of a string.
//!
//! \param pContext is a pointer to the drawing context to query.
//!
//! This function determines the height of a string.  The height is the offset
//! between the top of the string and the bottom of the string, including any
//! ascenders and descenders.  Note that this will not account for the case
//! where the string in question does not have any characters that use
//! descenders but the font in the drawing context does contain characters with
//! descenders.
//!
//! \return Returns the height of the string, in pixels.
//
//*****************************************************************************
#define GrStringHeightGet(pContext)   \
        ((pContext)->pFont->ucHeight)

//*****************************************************************************
//
//! Gets the maximum width of a character in a string.
//!
//! \param pContext is a pointer to the drawing context to query.
//!
//! This function determines the maximum width of a character in a string.  The
//! maximum width is the width of the widest individual character in the font
//! used to render the string, which may be wider than the widest character
//! that is used to render a particular string.
//!
//! \return Returns the maximum width of a character in a string, in pixels.
//
//*****************************************************************************
#define GrStringMaxWidthGet(pContext)   \
        ((pContext)->pFont->ucMaxWidth)

//*****************************************************************************
//
// A set of color definitions.  This set is the subset of the X11 colors (from
// rgb.txt) that are supported by typical web browsers.
//
//*****************************************************************************
#define ClrAliceBlue            0x00F0F8FF
#define ClrAntiqueWhite         0x00FAEBD7
#define ClrAqua                 0x0000FFFF
#define ClrAquamarine           0x007FFFD4
#define ClrAzure                0x00F0FFFF
#define ClrBeige                0x00F5F5DC
#define ClrBisque               0x00FFE4C4
#define ClrBlack                0x00000000
#define ClrBlanchedAlmond       0x00FFEBCD
#define ClrBlue                 0x000000FF
#define ClrBlueViolet           0x008A2BE2
#define ClrBrown                0x00A52A2A
#define ClrBurlyWood            0x00DEB887
#define ClrCadetBlue            0x005F9EA0
#define ClrChartreuse           0x007FFF00
#define ClrChocolate            0x00D2691E
#define ClrCoral                0x00FF7F50
#define ClrCornflowerBlue       0x006495ED
#define ClrCornsilk             0x00FFF8DC
#define ClrCrimson              0x00DC143C
#define ClrCyan                 0x0000FFFF
#define ClrDarkBlue             0x0000008B
#define ClrDarkCyan             0x00008B8B
#define ClrDarkGoldenrod        0x00B8860B
#define ClrDarkGray             0x00A9A9A9
#define ClrDarkGreen            0x00006400
#define ClrDarkKhaki            0x00BDB76B
#define ClrDarkMagenta          0x008B008B
#define ClrDarkOliveGreen       0x00556B2F
#define ClrDarkOrange           0x00FF8C00
#define ClrDarkOrchid           0x009932CC
#define ClrDarkRed              0x008B0000
#define ClrDarkSalmon           0x00E9967A
#define ClrDarkSeaGreen         0x008FBC8F
#define ClrDarkSlateBlue        0x00483D8B
#define ClrDarkSlateGray        0x002F4F4F
#define ClrDarkTurquoise        0x0000CED1
#define ClrDarkViolet           0x009400D3
#define ClrDeepPink             0x00FF1493
#define ClrDeepSkyBlue          0x0000BFFF
#define ClrDimGray              0x00696969
#define ClrDodgerBlue           0x001E90FF
#define ClrFireBrick            0x00B22222
#define ClrFloralWhite          0x00FFFAF0
#define ClrForestGreen          0x00228B22
#define ClrFuchsia              0x00FF00FF
#define ClrGainsboro            0x00DCDCDC
#define ClrGhostWhite           0x00F8F8FF
#define ClrGold                 0x00FFD700
#define ClrGoldenrod            0x00DAA520
#define ClrGray                 0x00808080
#define ClrGreen                0x00008000
#define ClrGreenYellow          0x00ADFF2F
#define ClrHoneydew             0x00F0FFF0
#define ClrHotPink              0x00FF69B4
#define ClrIndianRed            0x00CD5C5C
#define ClrIndigo               0x004B0082
#define ClrIvory                0x00FFFFF0
#define ClrKhaki                0x00F0E68C
#define ClrLavender             0x00E6E6FA
#define ClrLavenderBlush        0x00FFF0F5
#define ClrLawnGreen            0x007CFC00
#define ClrLemonChiffon         0x00FFFACD
#define ClrLightBlue            0x00ADD8E6
#define ClrLightCoral           0x00F08080
#define ClrLightCyan            0x00E0FFFF
#define ClrLightGoldenrodYellow 0x00FAFAD2
#define ClrLightGreen           0x0090EE90
#define ClrLightGrey            0x00D3D3D3
#define ClrLightPink            0x00FFB6C1
#define ClrLightSalmon          0x00FFA07A
#define ClrLightSeaGreen        0x0020B2AA
#define ClrLightSkyBlue         0x0087CEFA
#define ClrLightSlateGray       0x00778899
#define ClrLightSteelBlue       0x00B0C4DE
#define ClrLightYellow          0x00FFFFE0
#define ClrLime                 0x0000FF00
#define ClrLimeGreen            0x0032CD32
#define ClrLinen                0x00FAF0E6
#define ClrMagenta              0x00FF00FF
#define ClrMaroon               0x00800000
#define ClrMediumAquamarine     0x0066CDAA
#define ClrMediumBlue           0x000000CD
#define ClrMediumOrchid         0x00BA55D3
#define ClrMediumPurple         0x009370DB
#define ClrMediumSeaGreen       0x003CB371
#define ClrMediumSlateBlue      0x007B68EE
#define ClrMediumSpringGreen    0x0000FA9A
#define ClrMediumTurquoise      0x0048D1CC
#define ClrMediumVioletRed      0x00C71585
#define ClrMidnightBlue         0x00191970
#define ClrMintCream            0x00F5FFFA
#define ClrMistyRose            0x00FFE4E1
#define ClrMoccasin             0x00FFE4B5
#define ClrNavajoWhite          0x00FFDEAD
#define ClrNavy                 0x00000080
#define ClrOldLace              0x00FDF5E6
#define ClrOlive                0x00808000
#define ClrOliveDrab            0x006B8E23
#define ClrOrange               0x00FFA500
#define ClrOrangeRed            0x00FF4500
#define ClrOrchid               0x00DA70D6
#define ClrPaleGoldenrod        0x00EEE8AA
#define ClrPaleGreen            0x0098FB98
#define ClrPaleTurquoise        0x00AFEEEE
#define ClrPaleVioletRed        0x00DB7093
#define ClrPapayaWhip           0x00FFEFD5
#define ClrPeachPuff            0x00FFDAB9
#define ClrPeru                 0x00CD853F
#define ClrPink                 0x00FFC0CB
#define ClrPlum                 0x00DDA0DD
#define ClrPowderBlue           0x00B0E0E6
#define ClrPurple               0x00800080
#define ClrRed                  0x00FF0000
#define ClrRosyBrown            0x00BC8F8F
#define ClrRoyalBlue            0x004169E1
#define ClrSaddleBrown          0x008B4513
#define ClrSalmon               0x00FA8072
#define ClrSandyBrown           0x00F4A460
#define ClrSeaGreen             0x002E8B57
#define ClrSeashell             0x00FFF5EE
#define ClrSienna               0x00A0522D
#define ClrSilver               0x00C0C0C0
#define ClrSkyBlue              0x0087CEEB
#define ClrSlateBlue            0x006A5ACD
#define ClrSlateGray            0x00708090
#define ClrSnow                 0x00FFFAFA
#define ClrSpringGreen          0x0000FF7F
#define ClrSteelBlue            0x004682B4
#define ClrTan                  0x00D2B48C
#define ClrTeal                 0x00008080
#define ClrThistle              0x00D8BFD8
#define ClrTomato               0x00FF6347
#define ClrTurquoise            0x0040E0D0
#define ClrViolet               0x00EE82EE
#define ClrWheat                0x00F5DEB3
#define ClrWhite                0x00FFFFFF
#define ClrWhiteSmoke           0x00F5F5F5
#define ClrYellow               0x00FFFF00
#define ClrYellowGreen          0x009ACD32

//*****************************************************************************
//
// Masks and shifts to aid in color format translation by drivers.
//
//*****************************************************************************
#define ClrRedMask              0x00FF0000
#define ClrRedShift             16
#define ClrGreenMask            0x0000FF00
#define ClrGreenShift           8
#define ClrBlueMask             0x000000FF
#define ClrBlueShift            0

//*****************************************************************************
//
// Prototypes for the predefined fonts in the graphics library.  ..Cm.. is the
// computer modern font, which is a serif font.  ..Cmsc.. is the computer
// modern small-caps font, which is also a serif font.  ..Cmss.. is the
// computer modern sans-serif font.
//
//*****************************************************************************
extern const tFont g_sFontCm12;
extern const tFont g_sFontCm12b;
extern const tFont g_sFontCm12i;
extern const tFont g_sFontCm14;
extern const tFont g_sFontCm14b;
extern const tFont g_sFontCm14i;
extern const tFont g_sFontCm16;
extern const tFont g_sFontCm16b;
extern const tFont g_sFontCm16i;
extern const tFont g_sFontCm18;
extern const tFont g_sFontCm18b;
extern const tFont g_sFontCm18i;
extern const tFont g_sFontCm20;
extern const tFont g_sFontCm20b;
extern const tFont g_sFontCm20i;
extern const tFont g_sFontCm22;
extern const tFont g_sFontCm22b;
extern const tFont g_sFontCm22i;
extern const tFont g_sFontCm24;
extern const tFont g_sFontCm24b;
extern const tFont g_sFontCm24i;
extern const tFont g_sFontCm26;
extern const tFont g_sFontCm26b;
extern const tFont g_sFontCm26i;
extern const tFont g_sFontCm28;
extern const tFont g_sFontCm28b;
extern const tFont g_sFontCm28i;
extern const tFont g_sFontCm30;
extern const tFont g_sFontCm30b;
extern const tFont g_sFontCm30i;
extern const tFont g_sFontCm32;
extern const tFont g_sFontCm32b;
extern const tFont g_sFontCm32i;
extern const tFont g_sFontCm34;
extern const tFont g_sFontCm34b;
extern const tFont g_sFontCm34i;
extern const tFont g_sFontCm36;
extern const tFont g_sFontCm36b;
extern const tFont g_sFontCm36i;
extern const tFont g_sFontCm38;
extern const tFont g_sFontCm38b;
extern const tFont g_sFontCm38i;
extern const tFont g_sFontCm40;
extern const tFont g_sFontCm40b;
extern const tFont g_sFontCm40i;
extern const tFont g_sFontCm42;
extern const tFont g_sFontCm42b;
extern const tFont g_sFontCm42i;
extern const tFont g_sFontCm44;
extern const tFont g_sFontCm44b;
extern const tFont g_sFontCm44i;
extern const tFont g_sFontCm46;
extern const tFont g_sFontCm46b;
extern const tFont g_sFontCm46i;
extern const tFont g_sFontCm48;
extern const tFont g_sFontCm48b;
extern const tFont g_sFontCm48i;
extern const tFont g_sFontCmsc12;
extern const tFont g_sFontCmsc14;
extern const tFont g_sFontCmsc16;
extern const tFont g_sFontCmsc18;
extern const tFont g_sFontCmsc20;
extern const tFont g_sFontCmsc22;
extern const tFont g_sFontCmsc24;
extern const tFont g_sFontCmsc26;
extern const tFont g_sFontCmsc28;
extern const tFont g_sFontCmsc30;
extern const tFont g_sFontCmsc32;
extern const tFont g_sFontCmsc34;
extern const tFont g_sFontCmsc36;
extern const tFont g_sFontCmsc38;
extern const tFont g_sFontCmsc40;
extern const tFont g_sFontCmsc42;
extern const tFont g_sFontCmsc44;
extern const tFont g_sFontCmsc46;
extern const tFont g_sFontCmsc48;
extern const tFont g_sFontCmss12;
extern const tFont g_sFontCmss12b;
extern const tFont g_sFontCmss12i;
extern const tFont g_sFontCmss14;
extern const tFont g_sFontCmss14b;
extern const tFont g_sFontCmss14i;
extern const tFont g_sFontCmss16;
extern const tFont g_sFontCmss16b;
extern const tFont g_sFontCmss16i;
extern const tFont g_sFontCmss18;
extern const tFont g_sFontCmss18b;
extern const tFont g_sFontCmss18i;
extern const tFont g_sFontCmss20;
extern const tFont g_sFontCmss20b;
extern const tFont g_sFontCmss20i;
extern const tFont g_sFontCmss22;
extern const tFont g_sFontCmss22b;
extern const tFont g_sFontCmss22i;
extern const tFont g_sFontCmss24;
extern const tFont g_sFontCmss24b;
extern const tFont g_sFontCmss24i;
extern const tFont g_sFontCmss26;
extern const tFont g_sFontCmss26b;
extern const tFont g_sFontCmss26i;
extern const tFont g_sFontCmss28;
extern const tFont g_sFontCmss28b;
extern const tFont g_sFontCmss28i;
extern const tFont g_sFontCmss30;
extern const tFont g_sFontCmss30b;
extern const tFont g_sFontCmss30i;
extern const tFont g_sFontCmss32;
extern const tFont g_sFontCmss32b;
extern const tFont g_sFontCmss32i;
extern const tFont g_sFontCmss34;
extern const tFont g_sFontCmss34b;
extern const tFont g_sFontCmss34i;
extern const tFont g_sFontCmss36;
extern const tFont g_sFontCmss36b;
extern const tFont g_sFontCmss36i;
extern const tFont g_sFontCmss38;
extern const tFont g_sFontCmss38b;
extern const tFont g_sFontCmss38i;
extern const tFont g_sFontCmss40;
extern const tFont g_sFontCmss40b;
extern const tFont g_sFontCmss40i;
extern const tFont g_sFontCmss42;
extern const tFont g_sFontCmss42b;
extern const tFont g_sFontCmss42i;
extern const tFont g_sFontCmss44;
extern const tFont g_sFontCmss44b;
extern const tFont g_sFontCmss44i;
extern const tFont g_sFontCmss46;
extern const tFont g_sFontCmss46b;
extern const tFont g_sFontCmss46i;
extern const tFont g_sFontCmss48;
extern const tFont g_sFontCmss48b;
extern const tFont g_sFontCmss48i;
extern const tFont g_sFontCmtt12;
extern const tFont g_sFontCmtt14;
extern const tFont g_sFontCmtt16;
extern const tFont g_sFontCmtt18;
extern const tFont g_sFontCmtt20;
extern const tFont g_sFontCmtt22;
extern const tFont g_sFontCmtt24;
extern const tFont g_sFontCmtt26;
extern const tFont g_sFontCmtt28;
extern const tFont g_sFontCmtt30;
extern const tFont g_sFontCmtt32;
extern const tFont g_sFontCmtt34;
extern const tFont g_sFontCmtt36;
extern const tFont g_sFontCmtt38;
extern const tFont g_sFontCmtt40;
extern const tFont g_sFontCmtt42;
extern const tFont g_sFontCmtt44;
extern const tFont g_sFontCmtt46;
extern const tFont g_sFontCmtt48;
extern const tFont g_sFontFixed6x8;

//*****************************************************************************
//
// Language identifiers supported by the string table processing functions.
//
//*****************************************************************************
#define GrLangZhPRC             0x0804      // Chinese (PRC)
#define GrLangZhTW              0x0404      // Chinese (Taiwan)
#define GrLangEnUS              0x0409      // English (United States)
#define GrLangEnUK              0x0809      // English (United Kingdom)
#define GrLangEnAUS             0x0C09      // English (Australia)
#define GrLangEnCA              0x1009      // English (Canada)
#define GrLangEnNZ              0x1409      // English (New Zealand)
#define GrLangFr                0x040C      // French (Standard)
#define GrLangDe                0x0407      // German (Standard)
#define GrLangHi                0x0439      // Hindi
#define GrLangIt                0x0410      // Italian (Standard)
#define GrLangJp                0x0411      // Japanese
#define GrLangKo                0x0412      // Korean
#define GrLangEsMX              0x080A      // Spanish (Mexico)
#define GrLangEsSP              0x0C0A      // Spanish (Spain)
#define GrLangSwKE              0x0441      // Swahili (Kenya)
#define GrLangUrIN              0x0820      // Urdu (India)
#define GrLangUrPK              0x0420      // Urdu (Pakistan)

//*****************************************************************************
//
//! Translates a 24-bit RGB color to a display driver-specific color.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//! \param ulValue is the 24-bit RGB color.  The least-significant byte is the
//! blue channel, the next byte is the green channel, and the third byte is the
//! red channel.
//!
//! This function translates a 24-bit RGB color into a value that can be
//! written into the display's frame buffer in order to reproduce that color,
//! or the closest possible approximation of that color.
//!
//! \return Returns the display-driver specific color.
//
//*****************************************************************************
#define DpyColorTranslate(pDisplay, ulValue)                                \
        ((pDisplay)->pfnColorTranslate((pDisplay)->pvDisplayData, ulValue))

//*****************************************************************************
//
//! Flushes cached drawing operations.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//!
//! This function flushes any cached drawing operations on a display.
//!
//! \return None.
//
//*****************************************************************************
#define DpyFlush(pDisplay)                   \
        do                                   \
        {                                    \
            const tDisplay *pD = pDisplay;   \
            pD->pfnFlush(pD->pvDisplayData); \
        }                                    \
        while(0)

//*****************************************************************************
//
//! Gets the height of the display.
//!
//! \param pDisplay is a pointer to the display driver structure for the
//! display to query.
//!
//! This function determines the height of the display.
//!
//! \return Returns the height of the display in pixels.
//
//*****************************************************************************
#define DpyHeightGet(pDisplay) \
        ((pDisplay)->usHeight)

//*****************************************************************************
//
//! Draws a horizontal line on a display.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//! \param lX1 is the starting X coordinate of the line.
//! \param lX2 is the ending X coordinate of the line.
//! \param lY is the Y coordinate of the line.
//! \param ulValue is the color to draw the line.
//!
//! This function draws a horizontal line on a display.  This assumes that
//! clipping has already been performed, and that both end points of the line
//! are within the extents of the display.
//!
//! \return None.
//
//*****************************************************************************
#define DpyLineDrawH(pDisplay, lX1, lX2, lY, ulValue)                   \
        do                                                              \
        {                                                               \
            const tDisplay *pD = pDisplay;                              \
            pD->pfnLineDrawH(pD->pvDisplayData, lX1, lX2, lY, ulValue); \
        }                                                               \
        while(0)

//*****************************************************************************
//
//! Draws a vertical line on a display.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//! \param lX is the X coordinate of the line.
//! \param lY1 is the starting Y coordinate of the line.
//! \param lY2 is the ending Y coordinate of the line.
//! \param ulValue is the color to draw the line.
//!
//! This function draws a vertical line on a display.  This assumes that
//! clipping has already been performed, and that both end points of the line
//! are within the extents of the display.
//!
//! \return None.
//
//*****************************************************************************
#define DpyLineDrawV(pDisplay, lX, lY1, lY2, ulValue)                   \
        do                                                              \
        {                                                               \
            const tDisplay *pD = pDisplay;                              \
            pD->pfnLineDrawV(pD->pvDisplayData, lX, lY1, lY2, ulValue); \
        }                                                               \
        while(0)

//*****************************************************************************
//
//! Draws a pixel on a display.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//! \param lX is the X coordinate of the pixel.
//! \param lY is the Y coordinate of the pixel.
//! \param ulValue is the color to draw the pixel.
//!
//! This function draws a pixel on a display.  This assumes that clipping has
//! already been performed.
//!
//! \return None.
//
//*****************************************************************************
#define DpyPixelDraw(pDisplay, lX, lY, ulValue)                   \
        do                                                        \
        {                                                         \
            const tDisplay *pD = pDisplay;                        \
            pD->pfnPixelDraw(pD->pvDisplayData, lX, lY, ulValue); \
        }                                                         \
        while(0)

//*****************************************************************************
//
//! Draws a horizontal sequence of pixels on a display.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//! \param lX is the X coordinate of the first pixel.
//! \param lY is the Y coordinate of the first pixel.
//! \param lX0 is sub-pixel offset within the pixel data, which is valid for 1
//! or 4 bit per pixel formats.
//! \param lCount is the number of pixels to draw.
//! \param lBPP is the number of bits per pixel; must be 1, 4, or 8.
//! \param pucData is a pointer to the pixel data.  For 1 and 4 bit per pixel
//! formats, the most significant bit(s) represent the left-most pixel.
//! \param pucPalette is a pointer to the palette used to draw the pixels.
//!
//! This function draws a horizontal sequence of pixels on a display, using the
//! supplied palette.  For 1 bit per pixel format, the palette contains
//! pre-translated colors; for 4 and 8 bit per pixel formats, the palette
//! contains 24-bit RGB values that must be translated before being written to
//! the display.
//!
//! \return None.
//
//*****************************************************************************
#define DpyPixelDrawMultiple(pDisplay, lX, lY, lX0, lCount, lBPP, pucData,   \
                             pucPalette)                                     \
        do                                                                   \
        {                                                                    \
            const tDisplay *pD = pDisplay;                                   \
            pD->pfnPixelDrawMultiple(pD->pvDisplayData, lX, lY, lX0, lCount, \
                                     lBPP, pucData, pucPalette);             \
        }                                                                    \
        while(0)

//*****************************************************************************
//
//! Fills a rectangle on a display.
//!
//! \param pDisplay is the pointer to the display driver structure for the
//! display to operate upon.
//! \param pRect is a pointer to the structure describing the rectangle to
//! fill.
//! \param ulValue is the color to fill the rectangle.
//!
//! This function fills a rectangle on the display.  This assumes that clipping
//! has already been performed, and that all sides of the rectangle are within
//! the extents of the display.
//!
//! \return None.
//
//*****************************************************************************
#define DpyRectFill(pDisplay, pRect, ulValue)                   \
        do                                                      \
        {                                                       \
            const tDisplay *pD = pDisplay;                      \
            pD->pfnRectFill(pD->pvDisplayData, pRect, ulValue); \
        }                                                       \
        while(0)

//*****************************************************************************
//
//! Gets the width of the display.
//!
//! \param pDisplay is a pointer to the display driver structure for the
//! display to query.
//!
//! This function determines the width of the display.
//!
//! \return Returns the width of the display in pixels.
//
//*****************************************************************************
#define DpyWidthGet(pDisplay) \
        ((pDisplay)->usWidth)

//*****************************************************************************
//
//! Determines if a point lies within a given rectangle.
//!
//! \param pRect is a pointer to the rectangle which the point is to be checked
//! against.
//! \param lX is the X coordinate of the point to be checked.
//! \param lY is the Y coordinate of the point to be checked.
//!
//! This function determines whether point (lX, lY) lies within the rectangle
//! described by \e pRect.
//!
//! \return Returns 1 if the point is within the rectangle or 0 otherwise.
//
//*****************************************************************************
#define GrRectContainsPoint(pRect, lX, lY)                                  \
            ((((lX) >= (pRect)->sXMin) && ((lX) <= (pRect)->sXMax) &&       \
              ((lY) >= (pRect)->sYMin) && ((lY) <= (pRect)->sYMax)) ? 1 : 0)

//*****************************************************************************
//
// Prototypes for the graphics library functions.
//
//*****************************************************************************
extern void GrCircleDraw(const tContext *pContext, int lX, int lY,
                         int lRadius);
extern void GrCircleFill(const tContext *pContext, int lX, int lY,
                         int lRadius);
extern void GrContextClipRegionSet(tContext *pContext, tRectangle *pRect);
extern void GrContextInit(tContext *pContext, const tDisplay *pDisplay);
extern void GrImageDraw(const tContext *pContext,
                        const unsigned char *pucImage, int lX, int lY);
extern void GrLineDraw(const tContext *pContext, int lX1, int lY1, int lX2,
                       int lY2);
extern void GrLineDrawH(const tContext *pContext, int lX1, int lX2, int lY);
extern void GrLineDrawV(const tContext *pContext, int lX, int lY1, int lY2);
extern void GrOffScreen1BPPInit(tDisplay *pDisplay, unsigned char *pucImage,
                                int lWidth, int lHeight);
extern void GrOffScreen4BPPInit(tDisplay *pDisplay, unsigned char *pucImage,
                                int lWidth, int lHeight);
extern void GrOffScreen4BPPPaletteSet(tDisplay *pDisplay,
                                      unsigned int *pulPalette,
                                      unsigned int ulOffset,
                                      unsigned int ulCount);
extern void GrOffScreen8BPPInit(tDisplay *pDisplay, unsigned char *pucImage,
                                int lWidth, int lHeight);
extern void GrOffScreen8BPPPaletteSet(tDisplay *pDisplay,
                                      unsigned int *pulPalette,
                                      unsigned int ulOffset,
                                      unsigned int ulCount);
extern void GrOffScreen16BPPInit(tDisplay *pDisplay, unsigned char *pucImage,
                                int lWidth, int lHeight);
extern void GrOffScreen24BPPInit(tDisplay *pDisplay, unsigned char *pucImage,
                                int lWidth, int lHeight);
extern void GrRectDraw(const tContext *pContext, const tRectangle *pRect);
extern void GrRectFill(const tContext *pContext, const tRectangle *pRect);
extern void GrStringDraw(const tContext *pContext, const char *pcString,
                         int lLength, int lX, int lY,
                         unsigned int bOpaque);
extern int GrStringWidthGet(const tContext *pContext, const char *pcString,
                             int lLength);
extern void GrStringTableSet(const void *pvTable);
unsigned int GrStringLanguageSet(unsigned short usLangID);
unsigned int GrStringGet(int iIndex, char *pcData, unsigned int ulSize);
extern int GrRectOverlapCheck(tRectangle *psRect1, tRectangle *psRect2);
extern int GrRectIntersectGet(tRectangle *psRect1, tRectangle *psRect2,
                               tRectangle *psIntersect);

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************

#endif // __GRLIB_H__


text:
package congestion

import (
	"time"

	"github.com/lucas-clemente/quic-go/protocol"
	"github.com/lucas-clemente/quic-go/utils"
)

// Note(pwestin): the magic clamping numbers come from the original code in
// tcp_cubic.c.
const hybridStartLowWindow = protocol.ByteCount(16)

// Number of delay samples for detecting the increase of delay.
const hybridStartMinSamples = uint32(8)

// Exit slow start if the min rtt has increased by more than 1/8th.
const hybridStartDelayFactorExp = 3 // 2^3 = 8
// The original paper specifies 2 and 8ms, but those have changed over time.
const hybridStartDelayMinThresholdUs = int64(4000)
const hybridStartDelayMaxThresholdUs = int64(16000)

// HybridSlowStart implements the TCP hybrid slow start algorithm
type HybridSlowStart struct {
	endPacketNumber      protocol.PacketNumber
	lastSentPacketNumber protocol.PacketNumber
	started              bool
	currentMinRTT        time.Duration
	rttSampleCount       uint32
	hystartFound         bool
}

// StartReceiveRound is called for the start of each receive round (burst) in the slow start phase.
func (s *HybridSlowStart) StartReceiveRound(lastSent protocol.PacketNumber) {
	s.endPacketNumber = lastSent
	s.currentMinRTT = 0
	s.rttSampleCount = 0
	s.started = true
}

// IsEndOfRound returns true if this ack is the last packet number of our current slow start round.
func (s *HybridSlowStart) IsEndOfRound(ack protocol.PacketNumber) bool {
	return s.endPacketNumber < ack
}

// ShouldExitSlowStart should be called on every new ack frame, since a new
// RTT measurement can be made then.
// rtt: the RTT for this ack packet.
// minRTT: is the lowest delay (RTT) we have seen during the session.
// congestionWindow: the congestion window in packets.
func (s *HybridSlowStart) ShouldExitSlowStart(latestRTT time.Duration, minRTT time.Duration, congestionWindow protocol.ByteCount) bool {
	if !s.started {
		// Time to start the hybrid slow start.
		s.StartReceiveRound(s.lastSentPacketNumber)
	}
	if s.hystartFound {
		return true
	}
	// Second detection parameter - delay increase detection.
	// Compare the minimum delay (s.currentMinRTT) of the current
	// burst of packets relative to the minimum delay during the session.
	// Note: we only look at the first few(8) packets in each burst, since we
	// only want to compare the lowest RTT of the burst relative to previous
	// bursts.
	s.rttSampleCount++
	if s.rttSampleCount <= hybridStartMinSamples {
		if s.currentMinRTT == 0 || s.currentMinRTT > latestRTT {
			s.currentMinRTT = latestRTT
		}
	}
	// We only need to check this once per round.
	if s.rttSampleCount == hybridStartMinSamples {
		// Divide minRTT by 8 to get a rtt increase threshold for exiting.
		minRTTincreaseThresholdUs := int64(minRTT / time.Microsecond >> hybridStartDelayFactorExp)
		// Ensure the rtt threshold is never less than 2ms or more than 16ms.
		minRTTincreaseThresholdUs = utils.MinInt64(minRTTincreaseThresholdUs, hybridStartDelayMaxThresholdUs)
		minRTTincreaseThreshold := time.Duration(utils.MaxInt64(minRTTincreaseThresholdUs, hybridStartDelayMinThresholdUs)) * time.Microsecond

		if s.currentMinRTT > (minRTT + minRTTincreaseThreshold) {
			s.hystartFound = true
		}
	}
	// Exit from slow start if the cwnd is greater than 16 and
	// increasing delay is found.
	return congestionWindow >= hybridStartLowWindow && s.hystartFound
}

// OnPacketSent is called when a packet was sent
func (s *HybridSlowStart) OnPacketSent(packetNumber protocol.PacketNumber) {
	s.lastSentPacketNumber = packetNumber
}

// OnPacketAcked gets invoked after ShouldExitSlowStart, so it's best to end
// the round when the final packet of the burst is received and start it on
// the next incoming ack.
func (s *HybridSlowStart) OnPacketAcked(ackedPacketNumber protocol.PacketNumber) {
	if s.IsEndOfRound(ackedPacketNumber) {
		s.started = false
	}
}

// Started returns true if started
func (s *HybridSlowStart) Started() bool {
	return s.started
}

// Restart the slow start phase
func (s *HybridSlowStart) Restart() {
	s.started = false
	s.hystartFound = false
}

redpajama_set_name: RedPajamaGithub


text:
require 'grpc'
require 'google/cloud/texttospeech/v1/cloud_tts_pb'

module Google
  module Cloud
    module TextToSpeech
      module V1
        module TextToSpeech
          # Service that implements Google Cloud Text-to-Speech API.
          class Service

            include ::GRPC::GenericService

            self.marshal_class_method = :encode
            self.unmarshal_class_method = :decode
            self.service_name = 'google.cloud.texttospeech.v1.TextToSpeech'

            # Returns a list of Voice supported for synthesis.
            rpc :ListVoices, ::Google::Cloud::TextToSpeech::V1::ListVoicesRequest, ::Google::Cloud::TextToSpeech::V1::ListVoicesResponse
            # Synthesizes speech synchronously: receive results after all text input
            # has been processed.
            rpc :SynthesizeSpeech, ::Google::Cloud::TextToSpeech::V1::SynthesizeSpeechRequest, ::Google::Cloud::TextToSpeech::V1::SynthesizeSpeechResponse
          end

          Stub = Service.rpc_stub_class
        end
      end
    end
  end
end


text:
Kuler.waitHtml = '';

(function () {
	var $notification = $('#notification'),
		timer;

	if (Kuler.show_custom_notification) {
		Kuler.notification_show_time = parseInt(Kuler.notification_show_time) || 2500;
	}

	function kulerAlert(type, message) {
		if (!$notification.length) {
			$notification = $('#notification');
		}

		clearTimeout(timer);

		$notification
			.html('
' + message + '
');

		if (Kuler.show_custom_notification) {
			$notification
				.addClass('active')
				.children()
					.css('display', 'none')
					.fadeIn('slow', function () {
						timer = setTimeout(function () {
							$notification.removeClass('active');
						}, Kuler.notification_show_time);
					});
		} else {
			$('html, body').animate({ scrollTop: 0 }, 'slow');
		}
	}

	window.kulerAlert = kulerAlert;
})();

var _cartTimer;
function addToCart(product_id, quantity) {
	quantity = typeof(quantity) != 'undefined' ? quantity : 1;

	clearTimeout(_cartTimer);

	$.ajax({
		url: 'index.php?route=checkout/cart/add',
		type: 'post',
		data: 'product_id=' + product_id + '&quantity=' + quantity,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information, .error').remove();

			if (json['redirect']) {
				location = json['redirect'];
			}

			if (json['success']) {
				kulerAlert('success', json['success']);
				Kuler.cart_product_total += quantity;

				$('#cart-total').html(json['total']);
				$('#cart-product-total').html(Kuler.cart_product_total);
			}
		}
	});
}

var _wishListTimer;
function addToWishList(product_id) {
	clearTimeout(_wishListTimer);

	$.ajax({
		url: 'index.php?route=account/wishlist/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['success']) {
				kulerAlert('success', json['success']);

				$('#wishlist-total').html(json['total']);
			}
		}
	});
}

var _compareTimer;
function addToCompare(product_id) {
	clearTimeout(_compareTimer);

	$.ajax({
		url: 'index.php?route=product/compare/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['success']) {
				kulerAlert('success', json['success']);

				$('#compare-total').html(json['total']);
			}
		}
	});
}

if (Kuler.show_quick_view) {
    function initQuickView(selector) {
	    $(selector).on('click', function (evt) {
		    evt.preventDefault();

		    var $el = $(this);

		    $.magnificPopup.open({
			    items: {
				    src: this.href || $el.data('href')
			    },
			    type: 'iframe',
			    mainClass: 'mfp-fade'
		    });
        });
    };
}

jQuery(document).ready(function ($) {
	var $window = $(window);

	// Fixed Header
	if (Kuler.fixed_header) {
		var $fixedEl = $('#header');

		$window.bind('scroll', function() {
			if ($window.scrollTop() > 46) {
				$fixedEl.addClass('fix');
			} else {
				$fixedEl.removeClass('fix');
			}
		});
	}

    // Currency
    $('#currency a').on('click', function(e) {
        e.preventDefault();

        $('#currency input[name=\'currency_code\']').attr('value', $(this).attr('href'));

        $('#currency').submit();
    });

    // Language
    $('#language a').on('click', function(e) {
        e.preventDefault();

        $('#language input[name=\'language_code\']').attr('value', $(this).attr('href'));

        $('#language').submit();
    });

	// Quick View
	if (Kuler.show_quick_view) {
        initQuickView('.quick-view a');
	}

	// Newsletter
	if (Kuler.show_newsletter) {
		$('#newsletter-form').on('submit', function () {
			var $mail = $('#newsletter-mail'),
				$button = $('#newsletter-submit'),
				mail = $mail.val();

			if (!mail) {
				return false;
			}

			$mail.prop('disabled', true);
			$button.prop('disabled', true);
			$button.after(Kuler.waitHtml);

			$.post(Kuler.newsletter_subscribe_link, {
				mail: mail
			}, function (data) {
				var type = data.status ? 'success' : 'error';

				kulerAlert(type, data.message);

				$mail.prop('disabled', false);
				$button.prop('disabled', false);

				$button.next().remove();
			}, 'json');

			return false;
		});
	}

	//Smooth scroll to on page element
    $(".review a").click(function(event){
        event.preventDefault();
        //calculate destination place
        var dest=0;
        if($(this.hash).offset().top > $(document).height()-$(window).height()){
            dest=$(document).height()-$(window).height();
        } else {
            dest=$(this.hash).offset().top;
        }
        //go to destination
        $('html,body').animate({scrollTop:dest}, 500,'swing');
     });

	// Login Popup
	if (Kuler.login_popup) {
		$('a').each(function () {
			if (this.href == Kuler.login_url) {
				$(this).on('click', function (evt) {
					evt.preventDefault();

					$.magnificPopup.open({
						items: [
							{
								src: '#login-popup'
							}
						],
						type: 'inline',
						mainClass: 'mfp-fade'
					});
				});
			}
		});
	}

	var $popupLoginForm = $('#popup-login-form');
	$popupLoginForm.on('submit', function (evt) {
		evt.preventDefault();

		$.ajax({
			url: Kuler.popup_login_url,
			type: 'POST',
			dataType: 'json',
			data: $popupLoginForm.serialize(),
			beforeSend: function () {
				$popupLoginForm.find('[type="submit"]').after(Kuler.waitHtml);
				$popupLoginForm.find('.warning').remove();
			},
			complete: function () {
				$popupLoginForm.find('.wait').remove();
			},
			success: function (data) {
				if (data.status) {
					location.reload();
				} else {
					$popupLoginForm.prepend('
'+ data.message +'
');
				}
			}
		})
	});

    // Scroll up
    if (Kuler.enable_scroll_up) {
        var $scrollup = $('.scrollup');

        $window.scroll(function() {
            if ($window.scrollTop() > 100) {
                $scrollup.addClass('show');
            } else {
                $scrollup.removeClass('show');
            }
        });

        $scrollup.on('click', function(evt) {
            $("html, body").animate({ scrollTop: 0 }, 600);
            evt.preventDefault();
        });
    }

	if (Kuler.category_menu_type === 'accordion') {
		var $boxCategory = $('.box-category');

		$('.box-category .toggle').on('click', function () {
			var $this = $(this);

			$boxCategory
				.find('li.active')
					.removeClass('active')
					.find('ul')
						.slideUp();
			$this.next().slideDown();
			$this.parent().addClass('active');
		});
	}

    $('.dropdown-toggle').on('click', function () {
        $(this).next().toggleClass('open');
    });

	// Setup mobile main menu
    $('#btn-mobile-toggle').toggle(
        function() {
            $(this).removeClass('expand').next().slideUp();
        },
        function() {
            $(this).addClass('expand').next().slideDown();
        }
    );

    $('.btn-expand-menu').toggle(
        function() {
            $(this).next().slideUp().parent().removeClass('expand');
        },
        function() {
            $(this).next().slideDown().parent().addClass('expand');
        }
    );

    var innerWidth = $(window).innerWidth();

    if (innerWidth < 768) {
        $('#btn-mobile-toggle').trigger('click');
        $('.btn-expand-menu').trigger('click');
    }

    // Setup mobile tabs
    $('#btn-tabs-toggle').toggle(
        function() {
            $(this).parent().removeClass('collapse').addClass('expand').find('.ui-state-default').slideDown();
        },
        function() {
            $(this).parent().removeClass('expand').addClass('collapse').find('.ui-state-default:not(.ui-state-active)').slideUp();
        }
    );

});


text:
/**
 * The ImageView control of Cocos GUI
 * @class
 * @extends ccui.Widget
 */
ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
    _scale9Enabled: false,
    _prevIgnoreSize: true,
    _capInsets: null,
    _imageRenderer: null,
    _textureFile: "",
    _imageTexType: ccui.Widget.LOCAL_TEXTURE,
    _imageTextureSize: null,
    _className:"ImageView",
    _imageRendererAdaptDirty: true,

    /**
     * allocates and initializes a ccui.ImageView.
     * Constructor of ccui.ImageView, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
     * @param {String} imageFileName
     * @param {Number} [texType==ccui.Widget.LOCAL_TEXTURE]
     * @example
     * // example
     * var uiImageView = new ccui.ImageView;
     */
    ctor: function (imageFileName, texType) {
        this._capInsets = cc.rect(0,0,0,0);
        this._imageTextureSize = cc.size(this._capInsets.width, this._capInsets.height);
        ccui.Widget.prototype.ctor.call(this);

        texType && this.init(imageFileName, texType);
    },

    /**
     * Initializes an imageView. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
     * @param {String} imageFileName
     * @param {Number} [texType==ccui.Widget.LOCAL_TEXTURE]
     * @returns {boolean}
     */
    init: function(imageFileName, texType){
        if(ccui.Widget.prototype.init.call(this)){
            if(imageFileName === undefined)
                this._imageTexType = ccui.Widget.LOCAL_TEXTURE;
            else
                this.loadTexture(imageFileName, texType);
            return true;
        }
        return false;
    },

    _initRenderer: function () {
        this._imageRenderer = cc.Sprite.create();
        this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1);
    },

    /**
     * Loads textures for button.
     * @param {String} fileName
     * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
     */
    loadTexture: function (fileName, texType) {
        if (!fileName) {
            return;
        }
        var self = this;
        texType = texType || ccui.Widget.LOCAL_TEXTURE;
        this._textureFile = fileName;
        this._imageTexType = texType;
        var imageRenderer = self._imageRenderer;

        switch (self._imageTexType) {
            case ccui.Widget.LOCAL_TEXTURE:
                if(self._scale9Enabled){
                    imageRenderer.initWithFile(fileName);
                    imageRenderer.setCapInsets(self._capInsets);
                }else{
                    //SetTexture cannot load resource
                    imageRenderer.initWithFile(fileName);
                }
                break;
            case ccui.Widget.PLIST_TEXTURE:
                if(self._scale9Enabled){
                    imageRenderer.initWithSpriteFrameName(fileName);
                    imageRenderer.setCapInsets(self._capInsets);
                }else{
                    //SetTexture cannot load resource
                    imageRenderer.initWithSpriteFrameName(fileName);
                }
                break;
            default:
                break;
        }

        if(!imageRenderer.texture || !imageRenderer.texture.isLoaded()){
            imageRenderer.addLoadedEventListener(function(){
                self._findLayout();

                self._imageTextureSize = imageRenderer.getContentSize();
                self._updateFlippedX();
                self._updateFlippedY();

                self._updateChildrenDisplayedRGBA();

                self._updateContentSizeWithTextureSize(self._imageTextureSize);
                self._imageRendererAdaptDirty = true;
            });
        }

        self._imageTextureSize = imageRenderer.getContentSize();
        self._updateFlippedX();
        self._updateFlippedY();

        this._updateChildrenDisplayedRGBA();

        self._updateContentSizeWithTextureSize(self._imageTextureSize);
        self._imageRendererAdaptDirty = true;
    },

    /**
     * Sets texture rect
     * @param {cc.Rect} rect
     */
    setTextureRect: function (rect) {
        if (!this._scale9Enabled)
            this._imageRenderer.setTextureRect(rect);
    },

    _updateFlippedX: function () {
        if (this._scale9Enabled)
            this._imageRenderer.setScaleX(this._flippedX ? -1 : 1);
        else
            this._imageRenderer.setFlippedX(this._flippedX);
    },

    _updateFlippedY: function () {
        if (this._scale9Enabled)
            this._imageRenderer.setScaleY(this._flippedY ? -1 : 1);
        else
            this._imageRenderer.setFlippedY(this._flippedY);
    },

    /**
     * Sets if button is using scale9 renderer.
     * @param {Boolean} able
     */
    setScale9Enabled: function (able) {
        if (this._scale9Enabled == able)
            return;

        this._scale9Enabled = able;
        this.removeProtectedChild(this._imageRenderer);
        this._imageRenderer = null;
        if (this._scale9Enabled) {
            this._imageRenderer = new ccui.Scale9Sprite();
        } else {
            this._imageRenderer = cc.Sprite.create();
        }
        this.loadTexture(this._textureFile, this._imageTexType);
        this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1);
        if (this._scale9Enabled) {
            var ignoreBefore = this._ignoreSize;
            this.ignoreContentAdaptWithSize(false);
            this._prevIgnoreSize = ignoreBefore;
        } else
            this.ignoreContentAdaptWithSize(this._prevIgnoreSize);
        this.setCapInsets(this._capInsets);
    },

    /**
     * Returns ImageView is using scale9 renderer or not.
     * @returns {Boolean}
     */
    isScale9Enabled:function(){
        return this._scale9Enabled;
    },

    /**
     * Ignore the imageView's custom size, true that imageView will ignore it's custom size, use renderer's content size, false otherwise.
     * @override
     * @param {Boolean} ignore
     */
    ignoreContentAdaptWithSize: function (ignore) {
        if (!this._scale9Enabled || (this._scale9Enabled && !ignore)) {
            ccui.Widget.prototype.ignoreContentAdaptWithSize.call(this, ignore);
            this._prevIgnoreSize = ignore;
        }
    },

    /**
     * Sets capinsets for button, if button is using scale9 renderer.
     * @param {cc.Rect} capInsets
     */
    setCapInsets: function (capInsets) {
        if(!capInsets)
            return;
        var locInsets = this._capInsets;
        locInsets.x = capInsets.x;
        locInsets.y = capInsets.y;
        locInsets.width = capInsets.width;
        locInsets.height = capInsets.height;

        if (!this._scale9Enabled)
            return;
        this._imageRenderer.setCapInsets(capInsets);
    },

    /**
     * Returns cap insets of ccui.ImageView.
     * @returns {cc.Rect}
     */
    getCapInsets:function(){
        return cc.rect(this._capInsets);
    },

    _onSizeChanged: function () {
        ccui.Widget.prototype._onSizeChanged.call(this);
        this._imageRendererAdaptDirty = true;
    },

    _adaptRenderers: function(){
        if (this._imageRendererAdaptDirty){
            this._imageTextureScaleChangedWithSize();
            this._imageRendererAdaptDirty = false;
        }
    },

    /**
     * Returns the image's texture size.
     * @returns {cc.Size}
     */
    getVirtualRendererSize: function(){
        return cc.size(this._imageTextureSize);
    },

    /**
     * Returns the renderer of ccui.ImageView
     * @override
     * @returns {cc.Node}
     */
    getVirtualRenderer: function () {
        return this._imageRenderer;
    },

    _imageTextureScaleChangedWithSize: function () {
        if (this._ignoreSize) {
            if (!this._scale9Enabled)
                this._imageRenderer.setScale(1.0);
        } else {
            if (this._scale9Enabled)
                this._imageRenderer.setPreferredSize(this._contentSize);
            else {
                var textureSize = this._imageRenderer.getContentSize();
                if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
                    this._imageRenderer.setScale(1.0);
                    return;
                }
                this._imageRenderer.setScaleX(this._contentSize.width / textureSize.width);
                this._imageRenderer.setScaleY(this._contentSize.height / textureSize.height);
            }
        }
        this._imageRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
    },

    /**
     * Returns the "class name" of ccui.ImageView.
     * @override
     * @returns {string}
     */
    getDescription: function () {
        return "ImageView";
    },

    _createCloneInstance:function(){
        return ccui.ImageView.create();
    },

    _copySpecialProperties: function (imageView) {
        if(imageView instanceof ccui.ImageView){
            this._prevIgnoreSize = imageView._prevIgnoreSize;
            this.setScale9Enabled(imageView._scale9Enabled);
            this.loadTexture(imageView._textureFile, imageView._imageTexType);
            this.setCapInsets(imageView._capInsets);
        }
    }

});

/**
 * Allocates and initializes a UIImageView.
 * @deprecated since v3.0, please use new ccui.ImageView() instead.
 * @param {string} imageFileName
 * @param {Number} texType
 * @return {ccui.ImageView}
 * @example
 * // example
 * var uiImageView = ccui.ImageView.create();
 */
ccui.ImageView.create = function (imageFileName, texType) {
    return new ccui.ImageView(imageFileName, texType);
};

// Constants
/**
 * The zOrder value of ccui.ImageView's renderer.
 * @constant
 * @type {number}
 */
ccui.ImageView.RENDERER_ZORDER = -1;


text:
<?php

class Laporan_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper('security');
        $this->load->helper('string');
        $this->load->helper('date');
    }

    function get_cabang_id($idCabang) {
        if ($idCabang == 0) {
            return "Semua Cabang";
        } else {
            $res = $this->db->get_where("cabang", array('IDCabang' => $idCabang))->row();
            return $res->provinsi . " - " . $res->kabupaten;
        }
    }

    function select_laporan() {
        $sql = "";
        if ($this->session->userdata("Level") == 0) {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi, lp.status_kas
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin";
            if ($this->input->post("btn_pilih")) {
                if ($this->input->post("cabang") != 0) {
                    $sql.= " WHERE c.IDCabang = " . $this->input->post("cabang") . ";";
                }
            }
        } else if ($this->session->userdata("Level") == 1) {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi, lp.status_kas
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin WHERE a.username = '" . $this->session->userdata("Username") . "'";
        } else if ($this->session->userdata("Level") == 2) {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi, lp.status_kas
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin_kantor WHERE a.username = '" . $this->session->userdata("Username") . "'";
        }

        $query = $this->db->query($sql);
        return $query->result();
    }

    function select_laporan_pembatalan() {
        $sql = "";
        if ($this->session->userdata("Level") == 0) {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi, lp.status_kas
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin";
            if ($this->input->post("btn_pilih")) {
                if ($this->input->post("cabang") != 0) {
                    $sql.= " WHERE c.IDCabang = " . $this->input->post("cabang") . " AND lp.status_kas = 0 AND AND lp.IDPenjualan NOT IN (SELECT lb.IDPenjualan FROM laporan_pembatalan_penjualan lb);";
                } else {
                    $sql .= "WHERE lp.status_kas = 0 AND lp.IDPenjualan NOT IN (SELECT lb.IDPenjualan FROM laporan_pembatalan_penjualan lb);";
                }
            }
            else {
                $sql .= "WHERE lp.status_kas = 0 AND lp.IDPenjualan NOT IN (SELECT lb.IDPenjualan FROM laporan_pembatalan_penjualan lb);";
            }
        } else if ($this->session->userdata("Level") == 1) {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi, lp.status_kas
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin WHERE a.username = '" . $this->session->userdata("Username") . "' AND lp.status_kas = 0 AND lp.IDPenjualan NOT IN (SELECT lb.IDPenjualan FROM laporan_pembatalan_penjualan lb);";
        } else if ($this->session->userdata("Level") == 2) {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi, lp.status_kas
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin_kantor WHERE a.username = '" . $this->session->userdata("Username") . "' AND lp.status_kas = 0 AND lp.IDPenjualan NOT IN (SELECT lb.IDPenjualan FROM laporan_pembatalan_penjualan lb);";
        }

        $query = $this->db->query($sql);
        return $query->result();
    }

    function get_saldo_kantor($IDCabang) {
        $sql = "SELECT s.*, c.provinsi, c.kabupaten
                FROM setoran_bank s
                INNER JOIN cabang c ON c.IDCabang = s.IDCabang
                WHERE c.IDCabang = " . $IDCabang . ";";
        return $this->db->query($sql)->result();
    }

    function get_saldo_kas_bank($IDCabang) {
        $sql = "SELECT t.*, c.provinsi, c.kabupaten
                FROM tarik_kas_bank t
                INNER JOIN cabang c ON c.IDCabang = t.IDCabang
                WHERE c.IDCabang = " . $IDCabang . ";";
        return $this->db->query($sql)->result();
    }

    function select_laporan_periode($awal, $akhir) {
        if ($this->input->post("cabang")) {
//            echo $this->input->post("cabang"); exit;
            if ($this->input->post("cabang") == 0) {
                $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin
                Where DATE(tanggal) BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "'";
            } else {
                $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin
                Where DATE(tanggal) BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "' AND c.IDCabang = " . $this->input->post("cabang");
            }
        } else {
            $sql = "SELECT lp.IDPenjualan as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, lp.keterangan as keterangan, a.username as username, lp.totalPenjualan as totalPenjualan, lp.totalKomisi as totalKomisi
                FROM cabang c
                INNER JOIN laporan_penjualan lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin
                Where DATE(tanggal) BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "'";
        }
        $query = $this->db->query($sql);
        return $query->result();
    }

    function select_laporan_pengeluaran() {
        $sql = "";
        if ($this->session->userdata("Level") == 0) {
            $sql = "SELECT lp.IDPengeluaran as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, a.username as username, lp.totalPengeluaran as totalPengeluaran
                FROM cabang c
                INNER JOIN laporan_pengeluaran lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin";
            if ($this->input->post("btn_pilih")) {
                if ($this->input->post("cabang") != 0) {
                    $sql.= " WHERE c.IDCabang = " . $this->input->post("cabang") . ";";
                }
            }
        } else if ($this->session->userdata("Level") == 1) {
            $sql = "SELECT lp.IDPengeluaran as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, a.username as username, lp.totalPengeluaran as totalPengeluaran
                FROM cabang c
                INNER JOIN laporan_pengeluaran lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin WHERE a.username = '" . $this->session->userdata("Username") . "'";
        } else if ($this->session->userdata("Level") == 2) {
            $sql = "SELECT lp.IDPengeluaran as idlaporan, lp.IDCabang as idcabang, lp.tanggal as tanggal, a.username as username, lp.totalPengeluaran as totalPengeluaran
                FROM cabang c
                INNER JOIN laporan_pengeluaran lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin_kantor WHERE a.username = '" . $this->session->userdata("Username") . "'";
        }
        $query = $this->db->query($sql);
        return $query->result();
    }

    function get_laporan_gaji() {
        if ($this->session->userdata("Level") == 0) {
            $sql = "SELECT lp.*, c.provinsi, c.kabupaten, a.IDAdmin, c.saldo, a.username
                FROM cabang c
                INNER JOIN laporan_penggajian lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin_kantor
                WHERE lp.keterangan = 'gaji' ";
            if ($this->input->post("btn_submit")) {
                if ($this->input->post("cabang")) {
                    $sql.= "AND c.IDCabang = " . $this->input->post('cabang') . ";";
                }
            }
        } else {
            $sql = "SELECT lp.*, c.provinsi, c.kabupaten, a.IDAdmin, c.saldo, a.username
                FROM cabang c
                INNER JOIN laporan_penggajian lp ON c.IDCabang = lp.IDCabang
                INNER JOIN admin a ON a.IDAdmin = c.IDAdmin_kantor
                WHERE a.username = '" . $this->session->userdata("Username") . "' AND lp.keterangan = 'gaji';";
        }
        $query = $this->db->query($sql);
        return $query->result();
    }

    function cek_laporan_per_tanggal() {
        date_default_timezone_set('Asia/Jakarta');
        $isValue = "0";

        $tanggal_laporan = strftime("%Y-%m-%d", strtotime($this->input->post("tanggal")));

        $sql = "Select * From laporan_penjualan  Where tanggal = '$tanggal_laporan'";
        $result = $this->db->query($sql);

        if ($result->num_rows() > 0) {
            $isValue = "1";
        }

        return $isValue;
    }

    function get_laporan_gaji_id($IDLaporan) {
        return $this->db->get_where("laporan_penggajian", array("IDPenggajian" => $IDLaporan))->row();
    }

    function get_detail_laporan_gaji($IDLaporan) {
        $sql = "SELECT dp.*, s.IDSales, s.nama, s.totalGaji
                FROM detail_penggajian dp
                INNER JOIN sales s ON s.IDSales = dp.IDSales
                WHERE dp.IDPenggajian = $IDLaporan;";
        $query = $this->db->query($sql);
        return $query->result();
    }

    function get_sales($IDSales) {
        return $this->db->get_where("sales", array("IDSales" => $IDSales))->row();
    }

    function get_barang($IDBarang) {
        return $this->db->get_where("barang", array("IDBarang" => $IDBarang))->row();
    }

    function get_lokasi($IDLokasi) {
        return $this->db->query("SELECT l.IDLokasi as id_lokasi, l.desa, l.kecamatan as lokasi
                                FROM cabang c
                                INNER JOIN lokasi l ON l.IDCabang = c.IDCabang
                                WHERE l.IDLokasi = $IDLokasi")->row();
    }

    function get_stok_cabang($username) {
        $cabang = $this->db->query("SELECT c.IDCabang FROM cabang c INNER JOIN admin a ON a.IDAdmin = c.IDAdmin WHERE a.username = '" . $username . "';")->row();
        $sql = "SELECT b.IDBarang, b.namaBarang, cb.jumlah FROM cabang c INNER JOIN cabang_barang cb ON cb.IDCabang = c.IDCabang INNER JOIN barang b ON b.IDBarang = cb.IDBarang WHERE c.IDCabang = " . $cabang->IDCabang;
        return $this->db->query($sql)->result();
    }

    function select_top_sales() {
        $sql = "SELECT *
                FROM(Select s.nama as nama, s.foto as foto, (Select SUM(j1.hargaJual)
			FROM jual as j1
			Where j1.IDSales = j.IDSales) as totalpenjualan
                FROM sales s
                INNER JOIN jual as j ON j.IDSales = s.IDSales
                INNER JOIN laporan_penjualan as lp ON lp.IDPenjualan = j.IDPenjualan
                GROUP BY s.IDSales) as table1
                ORDER BY table1.totalpenjualan DESC";
//        echo $sql; exit;
        $query = $this->db->query($sql);
        return $query->result();
    }

    function select_top_sales_periode($awal, $akhir) {
        $awal = strftime("%Y-%m-%d", strtotime($awal));
        $akhir = strftime("%Y-%m-%d", strtotime($akhir));
        $sql = "Select s.nama as nama, (Select SUM(j1.hargaJual)
			FROM jual as j1
			Where j1.IDSales = j.IDSales) as totalpenjualan
                FROM sales s
                INNER JOIN jual as j ON j.IDSales = s.IDSales
                INNER JOIN laporan_penjualan as lp ON lp.IDPenjualan = j.IDPenjualan
                Where DATE(lp.tanggal) BETWEEN '$awal' AND '$akhir'";
        $query = $this->db->query($sql);
        return $query->result();
    }

    /* Daniel */

    function select_all_pengeluaran($awal = FALSE, $akhir = FALSE, $bulan = FALSE) {
        $sql = "SELECT *
                from ((
                        SELECT laporan_pengeluaran.IDCabang as IDCabang,laporan_pengeluaran.tanggal, detail_pengeluaran.keterangan as keterangan, SUM(detail_pengeluaran.total_pengeluaran) as jumlah, detail_pengeluaran.keterangan_lanjut
                        FROM detail_pengeluaran
                        INNER JOIN laporan_pengeluaran on laporan_pengeluaran.IDPengeluaran = detail_pengeluaran.IDPengeluaran
                        GROUP BY keterangan, keterangan_lanjut, tanggal)
                        UNION (
                        SELECT laporan_penggajian.IDCabang as IDCabang, detail_penggajian.Tanggal, CONCAT(laporan_penggajian.keterangan,' ', sales.nama) as keterangan, detail_penggajian.total_gaji as jumlah, '' as keterangan_lanjut
                        FROM detail_penggajian
                        INNER JOIN sales on sales.IDSales = detail_penggajian.IDSales
                        INNER JOIN laporan_penggajian ON laporan_penggajian.IDPenggajian = detail_penggajian.IDPenggajian)
                        ORDER BY tanggal DESC) as table1 ";
        if ($awal && $akhir) {
            $sql.=" WHERE table1.tanggal BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "'  ";
        } else if ($bulan) {
            $sql.=" WHERE month(table1.tanggal) = $bulan AND year(table1.tanggal) = year(now()) ";
        } else {
            $sql.=" WHERE month(table1.tanggal) = month(now()) AND year(table1.tanggal) = year(now()) ";
        }
        if ($this->input->post("cabang")) {
            if ($this->input->post("cabang") != 0) {
                $sql.=" AND table1.IDCabang = " . $this->input->post("cabang");
            }
        } else if ($this->session->userdata('Level') != 0) {
            $sql.=" AND table1.IDCabang = " . $this->session->userdata('IDCabang') . " ";
        }
//        print_r($sql);exit;
        return $this->db->query($sql)->result();
    }

    function select_lain_lain($awal = FALSE, $akhir = FALSE, $bulan = FALSE) {
        $sql = "SELECT laporan_pengeluaran.tanggal, detail_pengeluaran.keterangan, SUM(detail_pengeluaran.total_pengeluaran) as jumlah, detail_pengeluaran.keterangan_lanjut FROM detail_pengeluaran INNER JOIN laporan_pengeluaran on laporan_pengeluaran.IDPengeluaran = detail_pengeluaran.IDPengeluaran ";
        if ($awal && $akhir) {
            $sql.=" WHERE tanggal BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "'  ";
        } else if ($bulan) {
            $sql.=" WHERE month(tanggal) = $bulan AND year(tanggal) = year(now()) ";
        } else {
            $sql.=" WHERE month(tanggal) = month(now()) AND year(tanggal) = year(now()) ";
        }
        if ($this->input->post("cabang")) {
            if ($this->input->post("cabang") != 0) {
                $sql.=" AND laporan_pengeluaran.IDCabang = " . $this->input->post("cabang");
            }
        } else if ($this->session->userdata('Level') != 0) {
            $sql.=" AND laporan_pengeluaran.IDCabang = " . $this->session->userdata('IDCabang') . " ";
        }
        $sql.= " AND detail_pengeluaran.keterangan NOT IN ('Bensin', 'Makan', 'Parkir', 'Tol') GROUP BY keterangan, laporan_pengeluaran.tanggal, keterangan_lanjut ORDER BY tanggal DESC";
//        print_r($sql);
//        exit;
        return $this->db->query($sql)->result();
    }

    function select_gaji($jenis, $awal = FALSE, $akhir = FALSE, $bulan = FALSE) {
        if ($this->input->post("cabang")) {
            $sql = "SELECT '' as keterangan_lanjut, detail_penggajian.Tanggal as tanggal, CONCAT(lp.keterangan, ' ', sales.nama) as keterangan, detail_penggajian.total_gaji as jumlah FROM detail_penggajian INNER JOIN sales on sales.IDSales = detail_penggajian.IDSales INNER JOIN laporan_penggajian lp ON lp.IDPenggajian = detail_penggajian.IDPenggajian ";
        } else {
            $sql = "SELECT '' as keterangan_lanjut, detail_penggajian.Tanggal as tanggal, CONCAT(lp.keterangan, ' ', sales.nama) as keterangan, detail_penggajian.total_gaji as jumlah FROM detail_penggajian INNER JOIN sales on sales.IDSales = detail_penggajian.IDSales INNER JOIN laporan_penggajian lp ON lp.IDPenggajian = detail_penggajian.IDPenggajian ";
        }
        if ($awal && $akhir) {
            $sql.=" WHERE tanggal BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "'  ";
        } else if ($bulan) {
            $sql.=" WHERE month(detail_penggajian.tanggal) = $bulan AND year(detail_penggajian.tanggal) = year(now()) ";
        } else {
            $sql.=" WHERE month(detail_penggajian.tanggal) = month(now()) AND year(detail_penggajian.tanggal) = year(now()) ";
        }
        if ($this->input->post("cabang")) {
            if ($this->input->post("cabang") != 0) {
                $sql.=" AND lp.IDCabang = " . $this->input->post("cabang");
            }
        } else if ($this->session->userdata('Level') != 0) {
            $sql.=" AND lp.IDCabang = " . $this->session->userdata('IDCabang') . " ";
        }
        $sql.= "AND lp.keterangan = '$jenis' ORDER BY tanggal DESC";
//        print_r($sql); exit;
        return $this->db->query($sql)->result();
    }

    function select_per_jenis($jenis, $awal = FALSE, $akhir = FALSE, $bulan = FALSE) {
        $sql = "SELECT laporan_pengeluaran.tanggal, SUM(detail_pengeluaran.total_pengeluaran) as jumlah FROM detail_pengeluaran INNER JOIN laporan_pengeluaran on laporan_pengeluaran.IDPengeluaran = detail_pengeluaran.IDPengeluaran ";
        if ($awal && $akhir) {
            $sql.=" WHERE tanggal BETWEEN '" . strftime("%Y-%m-%d", strtotime($awal)) . "' AND '" . strftime("%Y-%m-%d", strtotime($akhir)) . "'  ";
        } else if ($bulan) {
            $sql.=" WHERE month(tanggal) = $bulan AND year(tanggal) = year(now()) ";
        } else {
            $sql.=" WHERE month(tanggal) = month(now()) AND year(tanggal) = year(now()) ";
        }
        if ($this->input->post("cabang")) {
            if ($this->input->post("cabang") != 0) {
                $sql.=" AND laporan_pengeluaran.IDCabang = " . $this->input->post("cabang") . " ";
            }
        } else if ($this->session->userdata('Level') != 0) {
            $sql.=" AND laporan_pengeluaran.IDCabang = " . $this->session->userdata('IDCabang') . " ";
        }
        $sql.= "AND detail_pengeluaran.keterangan = '$jenis' GROUP BY tanggal ORDER BY tanggal DESC";
//        print_r($sql); exit;
        return $this->db->query($sql)->result();
    }

}