// Welche Includes debuggen ? *************************************************
#define DEBUG
#define DEBUG_sprite_H
#define DEBUG_listen_H
#define DEBUG_communic_H
// Welche Includes debuggen ? *************************************************

#include <unistd.h>
#include <sys/stat.h>

#include "terminal.H"

#define vgax 320
#define vgay 200


#include "scrX11.H"

void hilfe()
{
    printf("\nWrong Parameters ! ************************************************************\n\nUsage:\npaldieb inputfile outputfile [transcolor]\n");
    
    printf("inputfile must be the filename of a picture in pcx-format.\n");
    printf("outputfile is the name of the palfile\n");
    printf("transcolor is the transparent color [default = 0]\n");
    printf("Exmaple:   'dieb test.pcx test.pal'\n");
}


int main(int argc,char **argv)
{
    // Parameterliste korrekt ???
    if ((argc<3)||(argc>4))
	{
	    hilfe();
	    exit(1);
	}
    char transcolor=0;
    if (argc==4)
	transcolor=atoi(argv[3]);
    
    // Source - Sprite anhand PCX-File initen *********************
    init_allsprites_kette("palette.pal");
    sprite_linear_nontransparenttype *source;
    iotype *ioptr=make_file_to_io_check(argv[1]);
    source=ladepcx_to_sprite_linear_nontransparenttype(ioptr,0,0);
    ioptr->seekset(0);
    palettetype *bildpalette=ladepcxpalette_to_palettetype(ioptr);
    delete ioptr;
    int aktx;
    int akty;
    int minx=source->sx;
    int maxx=0;
    int miny=source->sy;
    int maxy=0;
    for (akty=0;akty<source->sy;akty++)
	{
	    for (aktx=0;aktx<source->sx;aktx++)
		{
		    if (source->getpixel(aktx,akty)!=transcolor)
			{
			    if (aktx<minx)
				minx=aktx;
			    if (aktx>maxx)
				maxx=aktx;
			    if (akty<miny)
				miny=akty;
			    if (akty>maxy)
				maxy=akty;
			}
		}
	}
    int midx=(minx+maxx)/2;
    int midy=(miny+maxy)/2;
    aktx=-midx;
    akty=-midy;
    
    sprite_linear_nontransparent_screentype vscreen(0,0,vgax,vgay,(vgax-1)/2,(vgay-1)/2,NULL,NULL);
    vscreen.showpal(bildpalette);
    vscreen.clearsprite(transcolor);
    source->copysprite_clip(aktx,akty,&vscreen);
    vscreen.map();
    while(getchar()!=27){};

    ioptr=new iotype;
    bildpalette->change(ioptr);
    make_io_to_file_check(ioptr,argv[2],S_IWRITE|S_IRUSR|S_IRGRP|S_IROTH|S_IFREG);
    delete ioptr;

    delete source;    
    delete bildpalette;
    deinit_allsprites_kette();
}


