// Stephan Knauss, info@osm-tools.org, 2011
// I release this code into the public domain

#define METATILE (8)
#define BASEPATH "/var/lib/tirex/tiles/osmthen/"

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

static int removeCount=0;
static int metaCount = 0;

int remove_meta(int x, int y, int z)
{
   unsigned char i, hash[5], offset, mask;
   char metafile[1024];

   // Each meta tile winds up in its own file, with several in each leaf directory
   // the .meta tile name is beasd on the sub-tile at (0,0)
   mask = METATILE - 1;
   offset = (x & mask) * METATILE + (y & mask);
   x &= ~mask;
   y &= ~mask;

   for (i=0; i<5; i++) {
      hash[i] = ((x & 0x0f) << 4) | (y & 0x0f);
      x >>= 4;
      y >>= 4;
   }
   sprintf(metafile, "%s%d/%u/%u/%u/%u/%u.meta", BASEPATH, z, hash[4], hash[3], hash[2], hash[1], hash[0]);
   if (remove(metafile) == 0) {
      removeCount++;
      printf("deleted %s\n", metafile);
   }
   return offset;
}

int main (int argc, char *argv[]) {

   int xMin, xMax, yMin, yMax, zoom;
   int x,y;

   if (argc != 6) {
      printf("Syntax: %s <xMin> <xMax> <yMin> <yMax> <zoom>\n", argv[0]);
      return 1;
   }

   xMin = atoi(argv[1]);
   xMax = atoi(argv[2]);
   yMin = atoi(argv[3]);
   yMax = atoi(argv[4]);
   zoom = atoi(argv[5]);

   // round down to metatile boundary
   xMin &= ~(METATILE-1);
   xMax &= ~(METATILE-1);
   yMin &= ~(METATILE-1);
   yMax &= ~(METATILE-1);
   
   for (y=yMin; y<=yMax; y+= METATILE) {
      for (x=xMin; x<=xMax; x+= METATILE) {
         metaCount++;
         remove_meta(x, y, zoom); 
      }
   }

   printf("Out of %d metatiles %d had been removed.\n", metaCount, removeCount);
  
   return 0;
}
