#include <stdlib.h>
#include <stdio.h>

void exitus(char *txt)
{
    if(txt) puts(txt);
   // system("PAUSE");
    exit(0);
}

int main(int argc, char *argv[])
{
  
  FILE *rh;
  FILE *wh;
  long l,x,y,i;
  long width=64,height;
  long gfxwidth=16; // 16 * 16
  long byte_width=2;
  unsigned short v,cx,cy,n,flip;
  unsigned short *data=NULL;
  
  #define swap_sw(a,b) a[0]=a[0]^b[0];b[0]=b[0]^a[0];a[0]=a[0]^b[0];\
                       a[1]=a[1]^b[1];b[1]=b[1]^a[1];a[1]=a[1]^b[1];
  
  int   a[2],b[2],c[2],d[2];
  
  if(argc != 4)
  {
    printf("usage %s filename mapwidth gfxwidth/16\n",argv[0]);
    puts("");
    puts("example:");
    puts("");
    puts("16to8.exe map.data 64 16");
    puts("");
    exit(0);
  }
  
 
  width=atoi(argv[2]);
  gfxwidth=atoi(argv[3]);
  
  printf(";mapwidth = %d gfxwidth/16=%d \n",width,gfxwidth);
  
  rh=fopen(argv[1],"rb");
  if(rh==0)
  {
    exitus(";cant open file");
  }
  
  fseek(rh,0,SEEK_END);
  l=ftell(rh);
  fseek(rh,0,SEEK_SET);
  
  height=l/(width*byte_width);
  
  printf(";mapsize = %dx%d\n",width,height);
  
  data= (unsigned short*) malloc(height*2 * width*2  * sizeof(unsigned short));
  if(data==0)
  {  
    exitus(";no mem");
  }
 
  /* read from 16 to 8*/
  
  for(y=0;y<height;y++)
  {
    for(x=0;x<width;x++)
    {
         fread(&v,2,1,rh);
       
#define data_at(x,y,a,b) data[ ((x)*2)+a+((((y)*2)+b)*(width)*2) ]        
       
         if(v==0xffff) v=0;
         flip = v & 0xc000; // h=8000 v=4000
         v = v & 0x3fff;
       
         cx=v%gfxwidth;             // get x ..
         cy=v/gfxwidth;             // get y von 16ner Teil
         
         
         n=(cy*2)*(gfxwidth*2) + (cx * 2); // in 8 Pos umrechnen 
         
        a[0]=0;a[1]=0; //0 a
        b[0]=1;b[1]=0; //2 c
        c[0]=0;c[1]=1; //1 b
        d[0]=1;d[1]=1; //3 d
         
         
         if ((flip & 0x8000) == 0x8000) 
         {
                  n|=0x400; //H Flip
                  swap_sw(a,b);
                  swap_sw(c,d);
         }
         if ((flip & 0x4000) == 0x4000)
         {
                  n|=0x800; //V Flip
                  swap_sw(a,c);
                  swap_sw(b,d);
         }
       
         /* schreibe vier 8 pro 16 */
       
       
          data_at(x,y,a[0],a[1]) = n;                           
          data_at(x,y,b[0],b[1]) = n+1;
          data_at(x,y,c[0],c[1]) = n+gfxwidth*2;
          data_at(x,y,d[0],d[1]) = n+1+gfxwidth*2;
               
         
        
    }
  
  }
  
  // Ausgeben
  
  for(i=0;i<(width*2*+height*2);i++)
  {
   if((i%(width*2))==0)   
   {   
      printf("\n  @dcw  "); 
   }
    
    printf("$%4.4x%s",data[i],(((i+1)%(width*2))!=0)?",":""); 
  }
  
  if(data) 
    {
        free(data);
    }
    
  exitus(NULL);	
  return 0;
}
