/*
* A C program to calculate the p-value of a certain result in Experiment 5-4, written by John Alden
*
*
*/

#include <math.h>
#include <stdio.h>

#define MAX 100

int power[MAX+1];
double sum[MAX+1],p[MAX];

void main(void)

{
 /* Define variables */
 char filename[100],description[200];
 register int j;
 register long i;
 FILE *fp;
 int nexp,nobs;
 int idx;
 double temp,cumul1[MAX+1],cumul2[MAX+1];

 /* Read file */
 printf("\nEnter filename:"); scanf("%s",filename);
 fp=fopen(filename,"rt");
 if(fp==NULL){printf("Couldn't open file !!!"); exit(1);}
 fgets(description,200,fp);
 fscanf(fp,"%d",&nexp); fgets(filename,100,fp);
 fscanf(fp,"%d",&nobs); fgets(filename,100,fp);
 fgets(filename,100,fp);
 for(j=0; j<=nexp; j++) fscanf(fp,"%lf",p+j);
 fclose(fp);


 /* Run */
 for(i=0; i<power[nexp]; i++)
 {
  temp=1;
  idx=((i>>nexp)&1);
  for(j=0; j<nexp; j++) {idx+=((i>>j)&1);temp*=(i&power[j])? p[j] : 1-p[j];}
  sum[idx]+=temp;
 }

 /* Output */
 description[strlen(description)-1]='\0';
 printf("\n\n");
 for(j=0; j<strlen(description)+4; j++) putchar('=');
 printf("\n| %s |\n",description);
 for(j=0; j<strlen(description)+4; j++) putchar('=');
 cumul1[0]=0;
 printf("\n\nResults\n"); for(j=0; j<80; j++) putchar('='); printf("\n"); 
 for(j=0; j<=nexp; j++) printf("(%d)\t%f\t%f\n",j,sum[j],cumul1[j+1]=cumul1[j]+sum[j]);
 printf("\nP-value (for getting %d or more by chance): %f\n",nobs,1-cumul1[nobs]);
 printf("P-value (for getting %d or less by chance): %f (=P value for reverse hypothesis)\n\n",nobs,cumul1[nobs+1]);
}
