/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * main.c
 * Copyright (C) 2016 drdev <gualtieri@ieee.org>
 * 
 * triangle_interior_point 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.
 * 
 * triangle_interior_point 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

/* Prototypes */
char *strcpy(char *dest, const char *src);
void exit(int status);
void srand(unsigned int seed);
int rand();
float random_num(void);
/* end of prototypes */

char fn1[64];
FILE *outdata;
float P[2]; //(x,y) of interior point
float PA[2],PB[2],PC[2]; //(x,y) of triangle vertices
int b=0; //boolean result
unsigned long i;
unsigned long sum;
int j,k;

float random_num(void)
{

return ((double)rand()/(double)RAND_MAX);

}

int interior(float P[],float PA[],float PB[],float PC[])
{
float denom,a,b,c;

denom = ((PB[1] - PC[1])*(PA[0] - PC[0]) + (PC[0] - PB[0])*(PA[1] - PC[1]));
a = ((PB[1] - PC[1])*(P[0] - PC[0]) + (PC[0] - PB[0])*(P[1] - PC[1])) / denom;
b = ((PC[1] - PA[1])*(P[0] - PC[0]) + (PA[0] - PC[0])*(P[1] - PC[1])) / denom;
c = 1 - a - b;
 
return (0 <= a) && (a <= 1) && (0 <= b) && (b <= 1) && (0 <= c) && (c <= 1);

}


int main(int argc, char *argv[])
{

if (argc<2)
{
strcpy(fn1,"output.txt");
}
else
{
strcpy(fn1,argv[1]);
}

printf("\nOutput file selected = %s\n",fn1);

if ((outdata = fopen(fn1,"w"))==NULL)
	{printf ("\nOutput file cannot be opened.\n");
	exit (1);}

srand(time(NULL));

//P[0]=(float)1/3;
//P[1]=(float)1/3;

for(k=0;k<10000;k++)
{

sum = 0;

for(i=0;i<1000000;i++)
{

//random values for triangle vertices and interior point
for(j=0;j<2;j++)
{
P[j] = random_num();
PA[j] = random_num();
PB[j] = random_num();
PC[j] = random_num();
}

b = interior(P,PA,PB,PC);

if(b>0){sum++;}

//if(k==0){fprintf(outdata,"%d\n%f\t%f\n%f\t%f\n%f\t%f\n%f\t%f\n",b,P[0],P[1],PA[0],PA[1],PB[0],PB[1],PC[0],PC[1]);}

}

printf("%f\n",(float)sum/(float)i);
fprintf(outdata,"%f\n",(float)sum/(float)i);

}

fclose(outdata);

return (0);
}

