/* File: IconInfo.m - generates compile time files for Unknown application
 *
 * By: Christopher Lane
 * Symbolic Systems Resources Group
 * Knowledge Systems Laboratory
 * Stanford University
 *
 * Date: 25 January 1991
 *
 * Copyright: 1989, 1990 & 1991 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 */
 
#import <stdio.h>
#import <stdlib.h>

#import <objc/HashTable.h>
#import <objc/typedstream.h>

#define DOCFILE "Makefile.docicons"
#define ICONFILE "Unknown.iconheader"
#define ARCHIVEFILE "Unknown.iconarchive"
#define SECTIONFILE "Makefile.iconsections"

#define APP "app"
#define STRING @encode(char *)
#define BUFFERSIZE 512

void sys_error(char *string)
{
	perror(string);
	exit(EXIT_FAILURE);
}

void main(int argc, char *argv[])
{
	FILE *dfd, *ifd, *sfd;
	NXTypedStream *afd;
	int c;
	BOOL first = YES;
	HashTable *table = [HashTable newKeyDesc:STRING valueDesc:STRING];
	char extension[BUFFERSIZE], application[BUFFERSIZE], program[BUFFERSIZE];
    
	if ((dfd = fopen(DOCFILE, "w")) == NULL) sys_error("fopen");
	if ((ifd = fopen(ICONFILE, "w")) == NULL) sys_error("fopen");
	if ((sfd = fopen(SECTIONFILE, "w")) == NULL) sys_error("fopen");
	if ((afd = NXOpenTypedStreamForFile(ARCHIVEFILE, NX_WRITEONLY)) == NULL) exit(EXIT_FAILURE);
    
	(void) fprintf(dfd, "DOCICONS =");
	(void) fprintf(sfd, "ICONSECTIONS =");
       
	while((c = scanf(" %[^:]:%[^:]:%[^\n]", &extension, &application, &program)) != EOF) {
		if (c < 2) {
			fprintf(stderr, "Invalid iconinfo entry (%s)!\n", extension);
			exit(EXIT_FAILURE);
			} 
		if (c > 2) [table insertKey:NXUniqueString(extension) value:(void *)NXUniqueString(program)];
		if (! first) (void) fprintf(dfd, " \\\n $(TIFFILEDIR)/%s.tiff", extension);
		(void) fprintf(ifd, "%s\t%s\t%s\t%s\n", (first ? "F" : "S"), extension, application, (first ? APP : extension));
		(void) fprintf(sfd, " \\\n -sectcreate __ICON %s $(TIFFILEDIR)/%s.tiff", (first ? APP : extension), extension);
		first = NO;
		}
	
	(void) fprintf(dfd, "\n");
	(void) fprintf(sfd, "\n");
	NXWriteObject(afd, table);
	
	(void) fclose(dfd);
	(void) fclose(ifd);
	(void) fclose(sfd);
	NXCloseTypedStream(afd);
    
	exit(EXIT_SUCCESS);
}
