summaryrefslogtreecommitdiff
path: root/src/export/map_coords.c
blob: 4e03e6da2a8e5df5093214fe0b863b8ce3eec128 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#define _WITH_GETLINE
#include "mystdlib.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

static int find_offset( const void *key, const void *line )
{
  size_t l = strlen( (char*)key );
  return strncmp( (char*)key, *(char**)line, l );
}

static int qsort_cmp( const void *a, const void *b )
{
  return strcmp( *(char**)a, *(char**)b );
}

int main( int argc, char ** args )
{
  MAP coords;
  char *p, **offsets, *input = malloc(1024);
  ssize_t ll;
  size_t i, l, lines, input_length = 1024;

  if( argc != 2 ) { fprintf( stderr, "Syntax: printf %%s\\t%%s\\t%%s <zipcode> <streetname> <housenumber> | %s <coords_file>\n", args[0] ); exit(111); }
  coords = map_file( args[1], 1 );
  if( !coords || !input ) { fprintf( stderr, "Error allocating resources\n" ); exit( 111 ); }
  p = (char *)coords->addr;
  for ( i=0, lines=0; i<coords->size; ++i )
    if( p[i] == 0x00 )
      ++lines;

  offsets = malloc( lines * sizeof(char*));
  if( !offsets ) exit( 111 );

  offsets[0] = p; l = 1;
  for ( i=0; i<coords->size; ++i )
    if( p[i] == 0x00 )
      offsets[l++] = p+i+1;

  l--; qsort(offsets, l, sizeof(char*), qsort_cmp );

  while( ( ll = getline( &input, &input_length, stdin ) ) >= 0 )
  {
    char **coord_line;
    input[ll-1]='\t';
    coord_line = bsearch( input, offsets, l, sizeof(char*), find_offset );
    if( !coord_line && ll > 2 && isalpha( input[ll-2] ) )
    {
        input[ll-2] = '\t'; input[ll-1]=0;
        ll--;
        coord_line = bsearch( input, offsets, l, sizeof(char*), find_offset );
    }

    if( coord_line )
      printf( "%s\n", *coord_line + ll );
    else
      puts( "\t" );
  }

  return 0;
}