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

#define W25		/* 28/25 columns, i.e. 112x144/100x160 pixels */

#ifdef W25
#define WIDTH 100
#define HEIGHT 160
#else
#define WIDTH 112
#define HEIGHT 144
#endif /* W25 */

const char *vers="\0$VER: victo_ppm_ 1.1 (13.12.2000)\n";

unsigned char gfxmem[5120];

int main(int argc, char *argv[]) {
  FILE *handle, *ppmfile;

  /* replaces the 4-bit colour table from the Amiga version */
  static const unsigned char colortable[16][3]= {
    0x00,0x00,0x00, 
    0xf0,0xf0,0xf0, 
    0xd0,0x00,0x20, 	/* red is not so pure */
    0x00,0xf0,0xd0, 
    0xf0,0x00,0xd0, 
    0x00,0xf0,0x00, 
    0x00,0x00,0xd0, 
    0xe0,0xe0,0x00, 

    0xe0,0x60,0x00, 
    0xe0,0xc0,0xa0, 
    0xf0,0xc0,0xc0, 
    0xc0,0xf0,0xf0, 
    0xf0,0xc0,0xf0, 
    0xc0,0xf0,0xc0, 
    0xc0,0xc0,0xf0, 
    0xf0,0xf0,0xc0 };
  
  int x, y, ind, pos, bits,i;
  int g[4], colbits;
  unsigned char rc,gc,bc;

  if(argc != 3) {
    fprintf(stderr, "%s\n",vers+7);
    fprintf(stderr, "Usage: %s vicfile ppmfile\n",argv[0]);
    exit(10);
  }

  if((handle = fopen(argv[1], "rb"))) {
    char tmp[2];
    
    fprintf(stderr, "Converting %s\n", argv[1]);

    fread(tmp, 2, 1, handle); /* Load address */
    fread(gfxmem+768, 5120-768, 1, handle);
    fread(gfxmem, 768, 1, handle);

    if((ppmfile=fopen(argv[2],"w")))
      {
	fprintf(ppmfile,"P6\n# victoppm 1.1\n%d %d\n255\n",WIDTH*3,HEIGHT);
	for(y=0;y<HEIGHT;y++) {
	  for(x=0;x<WIDTH;x++) {
#ifndef W25
	    ind = x/4 + (y/16)*28 + ((y&8)<<5);   /* color memory index */
	    pos = y%16 + (x/4)*16 + (y/16)*16*28; /* grafix memory byte */
#else
	    ind = x/4 + (y/16)*25 + ((y&8)<<5);
	    pos = y%16 + (x/4)*16 + (y/16)*16*25;
#endif /* W25 */
	    bits = (x%4);				/* bit numbers */
	    
	    g[0] = (gfxmem[0x1300+HEIGHT-y]>>4) & 15;	/* == background */
	    g[1] = (gfxmem[0x1300+HEIGHT-y] & 7);	/* Border */
	    g[2] = (gfxmem[0x1000+ind] & 7);		/* color memory */
	    g[3] = (gfxmem[0x1200+HEIGHT-y]>>4) & 15;	/* Aux */
	    
	    colbits = (gfxmem[pos] >> (6-2*bits)) & 3;
	    rc=colortable[g[colbits]][0];
	    gc=colortable[g[colbits]][1];
	    bc=colortable[g[colbits]][2];
	    for (i=0; i<3; i++)
	      fprintf(ppmfile,"%c%c%c",rc,gc,bc);
	  }
	}
	fclose(ppmfile);
      }
    fclose(handle);
  } else {
    fprintf(stderr, "Could not access %s\n", argv[1]);
    exit(10);
  }
  return 0;
}


