/*
	Program to Extract a File from a UNIX file system
*/

#include <stdio.h>
#include "mxfilsys.h"

char dflag = FALSE;

main(argc,argv)
int argc;
char **argv;
{
	char fname[44],fsname[44],oname[44];
	long len,cn;
	struct inode inode;
	int i;
	long l;
	FILE *fd;
	char block[BLOCK];

	strcpy(fsname,"/mx/src");
	strcpy(oname,"a.out");

	while(--argc > 0) {
		if(**++argv == '-') {
			switch(tolower((*argv)[1])) {
			case 'd':
				dflag = 1-dflag;
				break;
			case 'x':
				strcpy(fsname,*++argv);
				--argc;
				break;
			case 'f':
				strcpy(fname,*++argv);
				--argc;
				break;
			case 'o':
				strcpy(oname,*++argv);
				--argc;
				break;
			default:
				fprintf(stderr,"unkown switch: %s\n",*argv);
				break;
			}
		}
	}

	fd = creat(oname);
	fsinit(fsname);
	fprintf(stderr,"Search for file %s yields inode %d\n",
		fname,i = srchdir(1,fname));
	geti(i,&inode);
	len = ((long)inode.size0 << 16) + inode.size1;
	if(dflag)
		fprintf(stderr,"File is %ld bytes long.\n",len);
	for(cn = 0; cn < len; cn += l) {
		i = cn >> 9;
		fblock(i,&inode,block);
		if((l = len-cn) >= (long) BLOCK)
			l = BLOCK;
		write(fd,block,l);
	}
	close(fd);
	fsclose();
}
