/*
 * this file is a part of yabbs - yet another bulletin board system.
 * Copyright (C) 1993, 1994 Alex Wetmore.  
 * email: alex@phred.org
 * address: 6 rech ave
 *          oreland pa 19075
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include "bbs_struct.h"
#include "bbs_files.h"

void main(int argc, char **argv) {
    FILE *mfile, *ifile, *dfile;
    irec idx;
    mrec msg;
    unsigned long offset, size, i;
    char fnameold[1024], fnameidx[1024], fnamedat[1024];

    if (argc == 1) {
        printf("usage: makeidx <data file>\n");
        printf("  converts old format yabbs message files to new format message files\n");
        exit(1);
    }

    strcpy(fnameold, argv[1]);
    strcpy(fnameidx, argv[1]); strcat(fnameidx, F_MIDXEXT);
    strcpy(fnamedat, argv[1]); strcat(fnamedat, F_MDATAEXT);

    if ((mfile = fopen(fnameold, "rb")) == NULL) {
        perror("makeidx: error opening msg data file for read");
        exit(1);
    }

    if ((ifile = fopen(fnameidx, "wb")) == NULL) {
        perror("makeidx: error opening msg index file for write");
        exit(1);
    }

    if ((dfile = fopen(fnamedat, "wb")) == NULL) {
        perror("makeidx: error opening msg data file for write");
        exit(1);
    }
    
    i = 0; offset = 0;
    while (fread(&size, sizeof(size), 1, mfile) == 1) {
        size += HDRLEN;
        fread(msg.to, 9, 1, mfile);
        fread(msg.from, 9, 1, mfile);
        fread(msg.title, 33, 1, mfile);
        fread(msg.time, 32, 1, mfile);
        fread(&msg.deleted, 1, 1, mfile);
        fread(msg.msg, size - HDRLEN, 1, mfile);

        idx.length = size;
        idx.offset = offset;
        fwrite(&idx, sizeof(idx), 1, ifile);

        fwrite(msg.to, 9, 1, dfile);
        fwrite(msg.from, 9, 1, dfile);
        fwrite(msg.title, 33, 1, dfile);
        fwrite(msg.time, 32, 1, dfile);
        fwrite(&msg.deleted, 1, 1, dfile);
        fwrite(msg.msg, size - HDRLEN, 1, dfile);

        printf("indexing %s: %i (%i, %i)      \r", fnameold, i++, offset, size);
        offset += size;
    }
    printf("\nwrote %i messages to index %s, data %s\n", i - 1, 
        fnameidx, fnamedat);

    fclose(ifile);
    fclose(mfile);
    fclose(dfile);
}
