#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>

#define BUFFER_SIZE 1024

int get_file_size(char *path,off_t *size)
{
	struct stat file_stats;
	if(stat(path,&file_stats))
		return 1;
	*size = file_stats.st_size;
	return 0;
}

int main(int argc,char **argv)
{
	off_t size;
	int byteRead = 0;
	FILE *fp,*fp1;
	char buffer[BUFFER_SIZE];
	if(argc < 4){
                char fullVersion[] = "$Rev: 156 $"; //This line will be automatically 
                                       //populated by svn and should be
                                       //of the form "$Rev: 156 $" else it could
                                       //cause a segmentation fault
                char *shortVersion = strchr(fullVersion,' ')+1; //Eliminate te word "$Rev: " 
                char *secondSpaceInVersion = strchr(shortVersion,' '); //Find the space after the number
                *secondSpaceInVersion ='\0';//Eliminate anything after the number, by zeroing the space
                printf("%s version: 1.0.%s \n",argv[0],shortVersion);
		printf("Usage: splitfile file part1 size1 part2!\n");
		exit(1);
	}
	get_file_size(argv[1],&size);
	printf("sizeof(off_t)is %d,File size is %d\n",sizeof(off_t),size); 
	if(!(fp =  fopen(argv[1],"rb"))){
		printf("FIEL OPEN ERROR\n");
		exit(EXIT_FAILURE);
	}
	if(buffer == NULL){
		printf("error in mem alloc\n");
		exit(EXIT_FAILURE);
	}
	printf("before %d\n",ftell(fp));
	fseek(fp,atoi(argv[3]),SEEK_SET);
	printf("after %d\n",ftell(fp));

	if(!(fp1 = fopen(argv[4],"wb"))){
		printf("FIELD OPEN ERROR\n");
		exit(EXIT_FAILURE);
	}
		
	while(ftell(fp) != size){
		byteRead = fread(buffer,1,BUFFER_SIZE,fp);
		fwrite(buffer,1,byteRead,fp1);
	}
	fclose(fp);
	fclose(fp1);
				
	return  0;
}
