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

#include "picdis.h"
#include "pu_defs.h"

char istr[40];

void welcome(char *);
extern void disasm12(unsigned int);
extern void disasm14(unsigned int);

void welcome(char *iam)
{
	printf("\n\nuseage:\n%s [-h] [-u] [-s<size>] [-o<file>] <file>\n",iam);
	printf("\t-h            : this help list\n");
	printf("\t-u            : use UPPER case\n");
	printf("\t-s<size>      : number of instructions to disassemble (decimal)\n");
	printf("\t-o<file>      : output file (default uses stdout)\n");
	printf("\t<file>        : input file in \"pictool\" format\n\n");
}

void main(int argc, char *argv[])
{
	FILE *outputfile = stdout;
	int opcase = LOWERCASE;
	int numtodisasm = MAXPICSIZE;
	unsigned int maxOps;
	int architecture = PIC14;
	int i;
	int j;
	char opstr[50];
	int autospecifiedsize = 1;
	PICDEFN thispic;

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

				case 'S':
				case 's':	sscanf(&argv[i][2],"%d",&numtodisasm);
						if(numtodisasm > MAXPICSIZE)
							numtodisasm = MAXPICSIZE;
						autospecifiedsize = 0;
						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 'H':
				case 'h':
				default:	welcome(argv[0]);
						exit(1);
			}
		else
		{
			if(PU_Read(argv[i],&thispic, &maxOps) == PU_FAIL)
			{
				printf("PU_Read failed syntax error in inputfile\n");
				welcome(argv[0]);
				exit(1);
			}
		}
	}

	if(autospecifiedsize)
		numtodisasm = maxOps + 1;

	if(thispic.pictype >= 60)
		architecture = PIC14;
	else
		architecture = PIC12;

	for(i=0; i<numtodisasm;i++)
	{
		switch(architecture)
		{
			case PIC12:	disasm12(thispic.picmemmap[i]);
					break;
			case PIC14:	disasm14(thispic.picmemmap[i]);
					break;
		}

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

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

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

	fclose(outputfile);
}

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