/* picdis.c  - pic disassembler		*/
/* version 0.1				*/
/* (c) I.King 1994			*/

#include "picdis.h"

char istr[40];

void welcome(char *);
extern void disasm12();
extern void disasm14();
extern void readihex16();

void welcome(char *iam)
{
	printf("\n\nuseage:\n%s [-h] [-p<size>] [-u] [-o<file>] <file>\n",iam);
	printf("\t-h            : this help list\n");
	printf("\t-p<size>      : processor architecture -p12 or -p14\n");
	printf("\t-u            : use UPPER case\n");
	printf("\t-o<file>      : output file (default uses stdout)\n");
	printf("\t<file>        : input file in \"intelhex16\" format\n\n");
}

void main(int argc, char *argv[])
{
	FILE *outputfile = stdout;
	FILE *inputfile  = stdin;
	int opcase = LOWERCASE;
	int i;
	int j;
	char opstr[50];
	int memory[MAXPICSIZE];
	int picarch = 14;
	int minaddr, maxaddr;
	int architecture;

	for(i=1; i< argc;i++)
	{
		if (argv[i][0] == '-')
			switch(argv[i][1])
			{
				case 'U':
				case 'u':	opcase = UPPERCASE;
						break;

				case 'O':
				case 'o':	if ((outputfile = fopen(&argv[i][2],"w")) == NULL)
						{
							printf("Could not open output file %s\n",&argv[i][2]);
							welcome(argv[0]);
							exit(1);
						}
						break;

				case 'P':
				case 'p':	sscanf(&argv[i][2],"%d",&picarch);
						break;

				case 'H':
				case 'h':
				default:	welcome(argv[0]);
						exit(1);
			}
		else
		{
			if ((inputfile = fopen(argv[i], "r")) == NULL)
			{
				printf("Error could not open input file %s\n", argv[i]);
				welcome(argv[0]);
				exit(1);
			}
		}
	}

	switch(picarch)
	{
		case 14:	architecture = PIC14;
				break;
		case 12:	architecture = PIC12;
				break;
		default:	printf("Invalid Architecture %d\n",picarch);
				welcome(argv[0]);
				exit(1);
	}

	readihex16(inputfile, memory, &minaddr, &maxaddr);
	fclose(inputfile);

	for(i=minaddr; i<=maxaddr;i++)
	{
		switch(architecture)
		{
			case PIC12:	disasm12(memory[i]);
					break;
			case PIC14:	disasm14(memory[i]);
					break;
		}

		sprintf(opstr,"%04x\t%04x\t%s\n",i,memory[i],istr);

		if (opcase == UPPERCASE)
		{
			j = 0;
			while(opstr[j])
			{
				opstr[j] = toupper(opstr[j]);
				j++;
			}
		}

		fprintf(outputfile,"%s", opstr);
	}

	fclose(outputfile);
}

/* ... The End ... */
