#define GLOBALORIGIN
#include "peg_pic.h"
#undef GLOBALORIGIN



#ifdef WITH_XGRAFIX
#include "xgrafix/xgrafix.h"
#endif

/* This enables to store reflected particles as their own species.
 * It can be enabled in makefile also. */
// #define REFLECTED_OWN_SPECIES


/*
#define DEBUG 
*/

#define SHOW_PROGRESS

int main(int argc, char *argv[]) {
	int  isp;
	char dumpfile[128], datfname[128], coordfname[128];
	int i, currentDumpNo=0, currentDatNo=0;
	int dotstep=0;		/* number of steps between dots in progress */
	int t_min, t_sec;
	time_t t0, t1; /* clock_t defined in <time.h> and <sys/types.h> as int */
	
#ifdef WITH_MT_RANDOM_GENERATOR	
    unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
    
    init_by_array(init, length);
#endif
   	
	for(i=0; i<128 ; i++) {
		/* fill strings for otput filenames with \0 */
		dumpfile[i] = datfname[i] = coordfname[i] = '\0';
	}

/*
	char aa[128] = "/local/disk2/phd-runs/BIT1-virtual-cathode/test-run/run1/test.inp";

	printf("in file=%s\n", argv[1]);
	strcpy(argv[1], aa);
*/

	display_title();				/* title */
	start(argc, argv);    			/* reading input, initialization, space allocation */

	if( start_step_for_dump > 0 ) {
		/* define start numbers for dump and dat files */
		currentDumpNo = currentDatNo = start_step_for_dump + 1;
	}

	/* calculate number of steps between dots when displaying the progress 
	 * it will display 50 dots between dump files */
	dotstep = (dmpstep < 100) ? dmpstep : (int) dmpstep / 100. ;

#ifdef DEBUG
	printf("peg_pic.c:\nstart_step_for_dump = %d\n", start_step_for_dump);
	printf("currentDumpNo = %d\n", currentDumpNo);
	printf("currentDatNo = %d\n", currentDatNo);
#endif

#if WITH_XGRAFIX
	if (dwindow) {
		InitWindows(argc, argv);    /* initialization of windows */    
	}
#endif
	
	accum();			           /* calculation of profiles */

	/* calculation of the field */
	if (field) fields();
	
	history();          /* calculation of time averaged values and histories */
	
	t0 = time(NULL);
	
	while( True  ) {

#ifdef DEBUG
		// printf( "\ntimestep: %d...", tstep );
#endif
		
#ifdef SHOW_PROGRESS
		if( tstep ) {
			if( tstep % dotstep == 0 ) {
				printf(".");
				fflush(stdout);
			}
		}
#endif
		
#if WITH_XGRAFIX
		if (dwindow) {
			/* operating with diagnostics windows */
			XGEvent();
		}
#endif
		
		t += dt;
		tstep++;

		if (tstep>2048000000) { 
			printf("Too many time steps");
			exit(1);
		}

		for(isp=0; isp<nsp; isp++) {
			if(tstep%nstep[isp]) {
				dinj[isp]=0;
			} else {
				dinj[isp]=1;
			}

//printf("nstep[%d]=%d; tstep=%d, dinj[%d]=%d\n", isp, nstep[isp], tstep, isp, dinj[isp]);


		}

		(*move_p)();                      /* particle mover */
		adjust();                         /* boundary effects */

		/* charged-neutrap part. collisions */
		if (Nnum) mcc();                      

		for(isp=0; isp<nsp; isp++) {	
			if (np[isp] > MAXLEN) {
				printf("ADJUST: too many particles, species %d: %d max=%d\n",isp, np[isp], MAXLEN);
				exit(1);
			}
		}

		/* coulomb collisions */
		if (ccc && (!(tstep%cc_step))) bincc();

		/* calculation of profiles */
		accum();    
		
		/* calculation of the field */
		if (field) fields();

		/* calculation of the time averaged values and of the time histories */
		history();
		
		/* files for movie */
		if (mflag) movf(dargv2, mvstep, mflag);      
		
		if ((!dwindow)&&(tstep==last_step)) {			/* dumping the run and exiting */
			/* create filename from base and current dump file number */
			if( origdmp == 3 ) {
				/* we are doing history of dump files, add current step number to file name */
				sprintf(dumpfile, dargv, currentDumpNo );
			} else {
				/* no step number, just copy filename */
				strcpy(dumpfile, dargv);
			}
			
			Dump(dumpfile);                     		/* write dump file (binary or ASCII) */
			DumpCoords(dargv6, dargv7, currentDumpNo);  /* write dump file with only coordinates (x Vx Vy Vz) */
			cridatfile(datfile,dargv1,dargv1a,currentDatNo);    /* creating datfile */
#ifdef SHOW_PROGRESS
			t1 =  time(NULL) - t0;
			t_min = (int) t1 / 60;
			t_sec = t1 - t_min * 60;
			printf("dmp (%d); dt= %3dm %2ds\n", currentDumpNo, t_min, t_sec);
			t0 = time(NULL);
#endif
			currentDumpNo++;                    		/* increase number of created dump files */
			currentDatNo++;
			exit(1);

		}

		if (stopfl) {
			if (!(tstep%stopfl) && np[0]) {     /* Only the first species are checked */
				if (fabs(1- nlast/(float)np[0]) < dn) {
					last_step = tstep + nfft;
					slow= 1;
					stopfl= 0;
				} else  
					nlast = np[0];
			}   					/* Checking the number of simulation 
							   particles (the species 0) and if  
							   its increase is small ends the run */
		}
		
		if (dmpstep) {
			if (!(tstep%dmpstep) && (tstep)) {
				/* create filename from base and current dump file number */
				if( origdmp == 3 ) {
					/* we are dosimg history of dump files, add surrent step number to file name */
					sprintf(dumpfile, dargv, currentDumpNo );
				} else {
					/* no step number, just copy filename */
					strcpy(dumpfile, dargv);
				}

				Dump(dumpfile);                     		/* dumping the run (binary or ASCII) */       
				DumpCoords(dargv6, dargv7, currentDumpNo);  /* write dump file with only coordinates (x Vx Vy Vz) */
#ifdef SHOW_PROGRESS
				t1 =  time(NULL) - t0;
				t_min = (int) t1 / 60;
				t_sec = t1 - t_min * 60;
				printf("dmp (%d); dt= %3dm %2ds\n", currentDumpNo, t_min, t_sec);
				t0 = time(NULL);
#endif
				currentDumpNo++;  							/* increase number of created dump files */
			}
		}
		
		if (!(tstep%datstep)) {
			/* create filename from base and current dump file number */
			cridatfile(datfile,dargv1,dargv1a,currentDatNo);     /* creating datfile */
			currentDatNo++;                   /* increase number of created dat files */
		}

#if WITH_XGRAFIX
		if (dwindow) {
            /* updating windows with diagnostics */
			XGUpdate();
		}
#endif
		
	} /* End of while(True) */
	
	/* free all memory allocated by program */
	freespace();
	
	return 0;
}   /* End of MAIN */

/***********************************************************/
