/******************************************************************************************/
/*	Short Description :				                           			  	                        */
/*	AU program calculates the gradient offset based on experimental parameters          	*/
/*	and generates a new difflist which can be used directly for DOSY processing         	*/
/*  for PSYCHE-iDOSY experiment 																													*/
/*  Mohammadali Foroozandeh																																*/
/*	29/07/2016																																						*/
/******************************************************************************************/

float tau_psyche,g_psyche,little_delta,big_delta,g_stab,delta_grad,gr_val;
int i;

FILE	*curr_diff_list, *new_diff_list, *diff_list_backup;
char	currlist[PATH_MAX], newlist[PATH_MAX];

FETCHPAR("P 40",&tau_psyche)
FETCHPAR("GPZ 10",&g_psyche)
FETCHPAR("P 30",&little_delta)
FETCHPAR("D 20",&big_delta)
FETCHPAR("D 16",&g_stab)

delta_grad = (3*(tau_psyche/1000000)*(g_psyche*0.01*53.5)*(2*(little_delta/1000000)-2*big_delta+4*g_stab+(tau_psyche/1000000)))/(4*(little_delta/1000000)*((little_delta/1000000)-3*big_delta));

Proc_err(INFO_OPT,"gradient offset = %f G/cm",delta_grad);

/* backing up the original difflist and save it as difflist_orig  */

if ((diff_list_backup = fopen(ACQUPATH("difflist_orig"), "wt")) == NULL)
STOPMSG("cannot open new difflist for write")

strcpy(currlist, ACQUPATH("difflist"));
if ((curr_diff_list = fopen(currlist, "r")) == NULL)
STOPMSG ("cannot open difflist file");

i = 0;
while (fscanf(curr_diff_list, "%f", &gr_val) > 0)
	{
	fprintf(diff_list_backup, "%f\n", gr_val);
	i++;
	}

if (i == 0)
STOPMSG("No gradient value found");

fclose (curr_diff_list);
fclose (diff_list_backup);

/*Proc_err(INFO_OPT,"original difflist was backed up");*/

/* making new difflist using difflist_orig and gradient offset and save it as difflist  */

if ((new_diff_list = fopen(ACQUPATH("difflist"), "wt")) == NULL)
STOPMSG("cannot open new difflist for write")

strcpy(currlist, ACQUPATH("difflist_orig"));
if ((curr_diff_list = fopen(currlist, "r")) == NULL)
STOPMSG ("cannot open difflist file");

i = 0;
while (fscanf(curr_diff_list, "%f", &gr_val) > 0)
	{
	fprintf(new_diff_list, "%f\n", gr_val + delta_grad);
	i++;
	}

if (i == 0)
STOPMSG("No gradient value found");

fclose (curr_diff_list);
fclose (new_diff_list);

/*Proc_err(INFO_OPT,"difflist with gradient offset was updated");*/

QUIT