#include <string>
#include "sprite01.H"

void help()
{
  cout <<"makepal: find all different colors in ppmfiles and create ppm file with this colors\n";
  cout <<"makepal [-output ofile] file1 file2 ...\n";
  cout <<"ofile: outpile filename, standard: 'palette.pal'\n";
  cout <<"file1 file2 ... : the input ppm files\n";
  exit(1);
}

int main(int argc,char **argv)
{
  string ofile="palette.pal";
  if (argc<2)
    help();
  palentry_kettetype palentry_kette;
  for (int aktp=1;aktp<argc;aktp++)
    {
      string aktps=argv[aktp];
      if (aktps=="-output")
	{
	  aktp++;
	  if (aktp==argc)
	    help();
	  ofile=argv[aktp];
	}
      else
	{
	  iotype *ioptr=make_file_to_io_check(aktps.c_str());
	  cfgtype *cfgptr=choose_cfgtype(ioptr,CFG_TEXT_MODE);
	  int32 sx,sy;
	  string header;
	  cfgptr->change_string_check(&header);
	  string hs=header.c_str();
	  if (hs!="P6")
	    fatalfehler("Input files must be ppm files");
	  cfgptr->change_int32_check(&sx);
	  cfgptr->change_int32_check(&sy);
	  int32 maxval;
	  cfgptr->change_int32_check(&maxval);
	  if (maxval!=255)
	    fatalfehler("makepal: ppmfiles entries must be scaled to 255");
	  delete cfgptr;
	  palentrytype aktentry;
	  int32 anzdots=0;
	  while (anzdots<sx*sy)
	    {
	      aktentry.change(ioptr,CFG_BINAER_MODE);
	      int gefunden=0;
	      palentry_zeigerelemtype *eptr=palentry_kette.anfang->next;
	      while (eptr!=palentry_kette.ende)
		{
		  if (*eptr==aktentry)
		    {
		      gefunden=1;
		      break;
		    }
		  eptr=eptr->next;
		}
	      if (!gefunden)
		{
		  palentry_zeigerelemtype *neues=new palentry_zeigerelemtype;
		  neues->red=aktentry.red;
		  neues->green=aktentry.green;
		  neues->blue=aktentry.blue;
		  palentry_kette.zeiger_push(neues);
		}
	      anzdots++;
	    }
	  delete ioptr;
	  cout << "Input Files left: "<<argc-aktp-1<<endl;
	}
    }  

  iotype output;
  output.io_write('P');
  output.io_write('6');
  output.io_write('\n');
  cfgtype *cfgptr=choose_cfgtype(&output,CFG_TEXT_MODE);
  cfgptr->change_int32_check((int32 *)&palentry_kette.anzzeigerelem);
  int32 y=1;
  cfgptr->change_int32_check(&y);
  int32 maxval=255;
  cfgptr->change_int32_check(&maxval);
  delete cfgptr;
  palentry_zeigerelemtype *eptr=palentry_kette.anfang->next;
  while (eptr!=palentry_kette.ende)
    {
      eptr->change(&output,CFG_BINAER_MODE);
      eptr=eptr->next;
    }
  make_io_to_file_check(&output,ofile.c_str(),S_IWRITE|S_IRUSR|S_IRGRP|S_IROTH|S_IFREG);
  cout <<"makepal: I found "<<palentry_kette.anzzeigerelem<<" different colors\n";
  exit(0);
}



