write.c
author viric@mandarina
Mon, 13 Aug 2007 23:45:27 +0200
changeset 6 bc41369f4587
parent 0 7f37716d4f1e
child 8 09ec33061ff3
permissions -rw-r--r--
Fixed things in replace.

#include <stdio.h>
#include "dictre.h"

extern struct Word words[];
extern int nwords;
extern struct Def defs[];
extern int ndefs;

static char num_to_ia5char(int n)
{
    /* From RFC 1421 */
    if (n >= 0 && n <= 25)
        return 'A' + n;
    else if (n >= 26 && n <= 51)
        return 'a' + (n - 26);
    else if (n >= 52 && n <= 61)
        return '0' + (n - 52);
    else if (n == 62)
        return '+';
    else if (n == 63)
        return '-';
    else
        return '!'; /* Error */
}

static int num_to_ia5(char *dest, int n)
{
    char tmp[20];

    int i, max;
   
    for(i =0; i <= 10; ++i)
    {
        tmp[i] = num_to_ia5char(n % 64);
        if (n < 64)
            break;
        n /= 64;
    }

    max = i;

    /* reverse the number */
    for (i=0; i<=max; ++i)
        dest[i] = tmp[max-i];

    /* Ending '\0' */
    dest[max+1] = '\0';
    return max;
}

static int write_dictionary_data(FILE *fdefs)
{
    int i;

    int offset = 0;

    for (i=0; i < ndefs; ++i)
    {
        fwrite(defs[i].d, defs[i].length, 1, fdefs);
        defs[i].offset = offset;
        offset += defs[i].length;
    }
}

static void write_dictionary_index(FILE *index)
{
    int i;

    for (i=0; i < nwords; ++i)
    {
        char offset_str[50];
        char length_str[50];

        num_to_ia5(offset_str, defs[words[i].def].offset);
        num_to_ia5(length_str, defs[words[i].def].length);
        fprintf(index, "%s\t%s\t%s\n",
                words[i].w, offset_str, length_str);
    }
}

void write_dictionary(const char *name)
{
    FILE *i, *d;
    char tmpname[500];

    strcpy(tmpname, name);
    strcat(tmpname, ".dict");
    d = fopen(tmpname, "wb");
    write_dictionary_data(d);
    fclose(d);

    strcpy(tmpname, name);
    strcat(tmpname, ".index");
    i = fopen(tmpname, "wb");
    write_dictionary_index(i);
    fclose(i);
}