/* GEM-View 3.00 PROCESSING Modul: Bild horizontal vertauschen
   (c) 22.10.1993 by Dieter Fiebelkorn
                     Grner Weg 29a
                     D-45768 Marl
                     (GERMANY)
*/

#include <stdio.h>
#include "image.h"
#include "moduls.h"

extern char fliptbl[];

Image* gvw_main(PROC_Structure *procS, int verbose)
{
    Image  *image;
    char   *data;
    char   *src, *dst, val;
    long    width, height;
    long    linelen, x, y;
    
    image = procS->image;
    if (image == NULL)
    {
      procS->events.alert(1, "[3][ | No image for process!  | ][  Abort  ]");
      return(NULL);
    }
    data = image->data;
    if (data == NULL)
    {
      procS->events.alert(1, "[3][ | No data in image!  | ][  Abort  ]");
      return(NULL);
    }

    if (ATARIMONOP(image) || ATARI_RGBP(image))
    {
        short   shift1, shift2, shifting;
        
        linelen = (long)image->width >> 3;
        width   = (long)image->unalignwidth;
        width   = (width + 7) >> 3;
        height  = (long)image->height * image->depth;
        
        for (y = height; y > 0; y--)
        {
            src = dst = data;
            dst += width;
            for (x = width >> 1; x > 0; x--)
                val = fliptbl[*src], *src++ = fliptbl[*--dst], *dst = val;
            if ((width & 0x01) != 0)
                *src = fliptbl[*src];
            data += linelen;
        }
        
        shift2 = image->unalignwidth & 0x07;
        shift1 = 8 - shift2;
        if (shift2 != 0)
        {
            data = image->data;
            for (y = height; y > 0; y--)
            {
                src = dst = data;
                ((char*)&shifting)[0] = *src++;
                for (x = width; x > 0; x--)
                {
                    ((char*)&shifting)[1] = *src++;
                    shifting <<= shift1;
                    *dst++ = ((char*)&shifting)[0];
                    shifting <<= shift2;
                }
                data += linelen;
            }
        }
    }
    
    if (ATARI__TCP(image))
    {
        linelen = 3L * image->width;
        width   = (long)image->unalignwidth;
        height  = (long)image->height;
        
        for (y = height; y > 0; y--)
        {
            src = dst = data;
            dst += 3L * width;
            for (x = width >> 1; x > 0; x--)
            {
                dst -= 3;
                val = src[0], src[0] = dst[0], dst[0] = val;
                val = src[1], src[1] = dst[1], dst[1] = val;
                val = src[2], src[2] = dst[2], dst[2] = val;
                src += 3;
            }
            data += linelen;
        }
    }
    
    return(image);
}
