/* Copyright 2007 Vince Busam */
/* Distributable under GPLv2 */
/* Version 0.4 */
/* This does a bit of a brute force decoding of the file, as I haven't */
/* figured out some of the inconsistencies between different files. */

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

#define NUMSTR 4 /* Name, Mobile, Home, Work, Junk */
#define STRLEN 128

void print_record(char strings[NUMSTR][STRLEN]) {
  int i;
  if (strlen(strings[0]) < 1)
    return;
  /* Prettify an all-caps record */
  if ((strlen(strings[0])>1) && isupper(strings[0][1]))
    for (i=1;i<strlen(strings[0]);i++)
      strings[0][i] = tolower(strings[0][i]);
  
  printf("\"%s\",\"%s\",\"%s\",\"%s\"\n",strings[0],strings[1],strings[2],strings[3]);
}

int main(int argc, char *argv[]) {
  FILE *fp;
  int c, charcount=0, zero=0, type=0;
  char buf[64];
  char strings[NUMSTR][STRLEN], t[4];
  
  if (argc < 1) exit(1);
  fp = fopen(argv[1],"rb");
  if (!fp) exit(1);
  fread(buf,1,22,fp);
  if (strncmp(buf,"CELLPBK",7))
    exit(1);
  printf("\"First\",\"Mobile\",\"Home\",\"Work\"\n");
  while (!feof(fp)) {
    c=getc(fp);
    switch (c) {
      case 0: /* Count the number of zeros in a row we get, discard them */
        zero++;
        break;
      default:
        /* If we've seen more than one zero, we're moving to another field */
        if (zero > 1) {
          /* If we've just finished off a string of type non-zero (a name) */
          /* of more than one character, we're seeing a new name */
          if ((charcount > 1) && (type != 0)) {
            type = 0;
            charcount = 0;
          } else if (charcount > 1) {
            /* If we see something after the zeros after the name, it's */
            /* either the type marker for the next string, or the sequence */
            /* number of the record, which may or may not be preceded by a 1 */
            type = NUMSTR-1; /* Put this junk in an unprinted string */
          }
        }
        zero = 0;
        /* A 1,2 or 3 marks the beginning of a phone number */
        if ((c > 0) && (c < (NUMSTR-1))) {
          type = c;
          //printf("(0x%0x,%i)",c,zero);
          strcpy(strings[type],"");
          charcount = 0;
        }
        if (!isprint(c))
          break;
        /* If we're seeing the first character of a name, print the last */
        /* record and wipe the slate clean */
        if ((type==0) && (charcount==0)) {
          print_record(strings);
          memset(strings,0,sizeof(strings));
        }
        charcount++;

        sprintf(t,"%c",c);
        if (strlen(strings[type]) < (STRLEN-1))
          strcat(strings[type],t);
        break;
    }
  }
  print_record(strings);
  fclose(fp);
  return 0;
}

