I am having problems calculating the average turn around time and average waiting time in my program. Can anyone give me some advice where i am going wrong please? I am first trying to work out the turn around time and then the waiting time so that i can use qaunta to subract away from the TAT.

Code:
/* Process each priority */ 
for ( sb = 0, nsb = 0, priority = 0; priority < PRIORITIES; priority++ )
{
	sb = nsb; 
	
	printf("Starting priority %d. \n", priority );
	
	/* process this priority level */ 
	for ( fp = 1, qsum = 0, ntp = 0, pcur = 0; ; pcur++)
	{
		/* If we have gone too far */ 
		if ( sb + pcur == num_procs || pq[ sb + pcur ].priority > priority )
		{
			if (fp ) /* Is this the first pass? */ 
			{
			nsb = sb + pcur; /* Keep the nsb in the same priority group */ 
			fp = 0;
			ntp += qsum;
			
			printf("Priority %d, qsum %d\n", priority, qsum);
			}
			pcur = 0; /* Reset the bucket */ 
			
			if ( ntp == 0 ) /* Do we have any that we need to process? */ 
			{ 
			printf( "Priority %d finished. \n\n", priority);
			break;
			}
		}

		/* if we have a quantum to process */
		if ( pq [sb + pcur ].quantum > 0 )
		{ 
			if ( fp ) /* On the first pass, sum bucket values */ 
			{ 
			qsum += pq [ sb + pcur ].quantum;
			pq[ sb + pcur ].started = timer; // make note when process starts
			printf("%s started at %d\n", pq[ sb + pcur ].id, pq[ sb + pcur].started);
			}
			
			ntp--;
			printf("%s %d %d\t pq [ %d ]\t ntp: %d\n",pq[ sb + pcur ].id, pq[ sb + pcur].quantum, priority,  sb + pcur, ntp); 
			pq[sb + pcur ].quantum--;
			timer++;
			
			/* If process ended, make note of when it ended */
			if ( pq [sb + pcur ].quantum == 0 ) 
			{
			pq[sb + pcur].finished = timer; // make note when the process ends
			tat = pq[sb + pcur].finished - pq[sb + pcur].started;
			atat += tat; // add all tat times together to work out average 
			printf("%s finished at %d tat of %f\n", pq[sb + pcur].id, pq[sb + pcur].finished, tat);
			}	
		}
	}
	
}

printf("All Process have completed\n");
printf("Average Turn Around Time: %f \n", atat / num_procs);