/**************************
**   Color Correct 1.0   **
**                       **
** by Frédéric Calendini **
**************************/

#include <exec/memory.h>
#include <intuition/IntuitionBase.h>
#include <stdlib.h>

#include <clib/graphics_protos.h>
#include <clib/exec_protos.h>

void main(int argc, char **argv)
{
    struct IntuitionBase *IntuitionBase;
    struct ExecBase *ExecBase;
    struct GfxBase *GfxBase;
    struct Screen *frontscreen;
    ULONG *table, nb_colors, col, i, R, G, B, level = 245;

    /* Opening Intuition Library */
    if ((IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library", 0)) != NULL);
    {
        /* Opening Exec Library */
        if ((ExecBase = (struct ExecBase *)OpenLibrary("exec.library", 0)) != NULL);
        {
            /* Opening GFX Library */
            if ((GfxBase = (struct GfxBase *)OpenLibrary("graphics.library", 0)) != NULL);
            {
                /* Check if an argument was passed */
                if (argc > 1)
                    level = atol(argv[1]);

                /* We allocate the color table */
                if (table = AllocMem(258 * 3 * sizeof(ULONG), MEMF_ANY))
                {
                    /* Address of the frontmost screen */
                    frontscreen = IntuitionBase->FirstScreen;
                    nb_colors = 1 << frontscreen->RastPort.BitMap->Depth ;

                    /* We get the screen palette */
                    GetRGB32(frontscreen->ViewPort.ColorMap, 0, nb_colors, table);
                    i = 0;
                    for (col = 0; col < nb_colors; col++)
                    {
                        R = (table[i++] >> 24);
                        G = (table[i++] >> 24);
                        B = (table[i++] >> 24);

                        /* We set the new brightness */
                        if (R == G && G == B && B > level)
                            SetRGB32(&(frontscreen->ViewPort), col, level << 24, level << 24, level << 24);
                    }

                    FreeMem(table, 258 * 3 * sizeof(ULONG));
                }

                CloseLibrary((struct Library *) GfxBase);
            }
            CloseLibrary((struct Library *) ExecBase);
        }
        CloseLibrary((struct Library *) IntuitionBase);

    }
}
