/**
 * @file  splitfile.cxx
 * @brief Originally part of HAMMER.
 *
 * Copyright (c) 2001, 2012, 2013 University of Pennsylvania.
 *
 * This file is part of DTI-DROID.
 *
 * DTI-DROID is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DTI-DROID is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DTI-DROID.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact: SBIA Group <sbia-software at uphs.upenn.edu>
 */

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

#include <dtidroid/basis.h>


// acceptable in .cxx file
using namespace dtidroid;


#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){
        print_version("splitfile", "", "");
        printf("\n");
		printf("USAGE: splitfile file part1 size1 part2!\n");
		exit(1);
	}
	get_file_size(argv[1],&size);
	printf("sizeof(off_t)is %ld,File size is %ld\n",sizeof(off_t),(long int)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 %ld\n",ftell(fp));
	fseek(fp,atoi(argv[3]),SEEK_SET);
	printf("after %ld\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;
}
