/* makedoc.c -- Program to strip doc-strings from C source
   Copyright (C) 1993, 1994 John Harper <jsh@ukc.ac.uk>

   This file is part of Jade.

   Jade 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, or (at your option)
   any later version.

   Jade 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 Jade; see the file COPYING.  If not, write to
   the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

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

extern void exit(int);

static void
usage(void)
{
    fputs("usage: makedoc [-a] doc-file header-file [src-files...]\n", stderr);
    exit(1);
}

static int
scanfile(FILE *src, FILE *docf, FILE *hdrf, int docindex)
{
    char buf[512];
    while(fgets(buf, 512, src))
    {
	char *start = strstr(buf, "::doc:");
	if(start)
	{
	    int startcol = start - buf;
	    start += 6;
	    while(*start && *start != ':')
		start++;
	    *start = 0;
	    fprintf(hdrf, "#define DOC_%s %d\n", buf + startcol + 6,  docindex);
	    while(fgets(buf, 512, src))
	    {
		int linelen = strlen(buf) - startcol;
		if(linelen > 0)
		{
		    if(buf[startcol] == ':')
			break;
		    fputs(buf + startcol, docf);
		    docindex += linelen;
		}
		else
		{
		    fputc('\n', docf);
		    docindex++;
		}
	    }
	    /* back over trailing newline */
	    fseek(docf, -1, 1 /*SEEK_CUR*/);
	    fputc('\f', docf);
	}
    }
    return(docindex);
}

int
main(int ac, char **av)
{
    FILE *docfile, *hdrfile;
    char append_p = 0;
    ac--;
    av++;
    if(ac >= 1 && !strcmp("-a", av[0]))
    {
	append_p = 1;
	ac--; av++;
    }
    if(ac < 2)
	usage();
    docfile = fopen(*av++, append_p ? "r+" : "w");
    hdrfile = fopen(*av++, append_p ? "r+" : "w");
    ac -= 2;
    if(!(docfile && hdrfile))
    {
	fprintf(stderr, "can't open output files.\n");
	exit(2);
    }
    if(append_p)
    {
	fseek(docfile, 0, 2 /*SEEK_END*/);
	fseek(hdrfile, 0, 2 /*SEEK_END*/);
    }
    else
	fputs("/* GENERATED BY MAKEDOC -- DO NOT EDIT! */\n\n", hdrfile);
    if(!ac)
	scanfile(stdin, docfile, hdrfile, 0);
    else
    {
	int docindex = ftell(docfile);
	while(ac)
	{
	    FILE *file = fopen(*av, "r");
	    if(file)
	    {
		docindex = scanfile(file, docfile, hdrfile, docindex);
		fclose(file);
	    }
	    ac--;
	    av++;
	}
    }
    exit(0);
}
