/********************************************************/
/*	Perlin Production Co. Ltd. August 2012		*/
/*	       File invertor, version 2.0              	*/
/********************************************************/
/* INVERT.C */

#include "stdio.h"

main(argc,argv)
int	argc;
char	**argv;
{
	int		src,dst;
	char		byte,*s,srcfn[20],dstfn[20],tmpfn[20];
	char		*defext;
	int		i;
	unsigned	count;

	defext = ".bin";

	if (argc < 2 || argc > 3)
	{
	 puts("Perlin Production Co. Ltd. 1994, 2012 (c)\n");
	 puts("INVERT, ver.2.0. Inverts bytes in file.\n");
	 rev_vid();
	 puts("Usage:");
	 nrm_vid();
	 printf(" invert srcfile[%s] [dstfile[%s]]",defext,defext);
	 exit(0);
	}

	strncpy(srcfn,argv[1],16);
	if ( index(srcfn,'.') == NULL ) strcat(srcfn,defext);

	strncpy(dstfn,argv[argc-1],16);
	if ( index(dstfn,'.') == NULL ) strcat(dstfn,defext);

	if ( (src=open(srcfn,FCB_READ)) == ERROR )
		problem("Can't open source file ",srcfn);

	strcpy(tmpfn,dstfn);
	if ( (s=index(tmpfn,':')) != NULL )
	{
		s++;
		*s=NULL;
	}
	else tmpfn[0]=NULL;
	strcat(tmpfn,"TEMPXX.$$$");
	if ( mktemp(tmpfn) == NULL )
	{
		errno=0;
		problem("Can't generate temporary file name",tmpfn);
	}

	if ( (dst=creat(tmpfn,FCB_WRITE)) == ERROR )
		problem("Can't create temporary file",tmpfn);

	for (count=0; read(src,&byte,1) == 1; ++count)
	{
		byte=~byte;

		if (write(dst,&byte,1) !=1)
		{
		 rev_vid();
		 printf("\007Writing to temporary %s failed\n",tmpfn);
		 nrm_vid();
		 break;
		}
		if (!(count % 128)) putchar('+');
	}
	printf("\n%u (0x%x) bytes written",count,count);

	if ( close(dst) == ERROR )
		problem(", can't close temporary",tmpfn);

	if ( !strcmp(dstfn,srcfn) )
	{
	    if ( unlink(srcfn) == ERROR )
	    {
		printf(", unable to delete source %s\n",srcfn);
		problem("Inverted bytes are in temporary",tmpfn);
	    }
	}
	unlink(dstfn);

	if ( rename(dstfn,tmpfn) == ERROR )
	{
		s = tmpfn;
		printf(", unable to rename temporary to %s\n",dstfn);
		problem("Inverted bytes are in temporary",tmpfn);
	}
	else s = dstfn;
	printf(" to %s\n",s);
}


problem(ts,fns)
char	*ts,*fns;
{
	if (errno)
	{
		printf("%s ",ts);
		perror(fns);
	}
	else	printf("%s %s",ts,fns);
	puts("\007");
	exit(1);
}
