/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * main.c
 * Copyright (C) 2016 D.M.Gualtieri, gualtieri@ieee.org
 * 
 * circumscibe 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.
 * 
 * circumscibe 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/>.
 */
 
 /*
Finds triangle of minimum area circumscribed about a unit semicircle
 */

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

#define trials 10000
#define triangle_type 0 //0=any angles, 1=right angle triangle

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

char fn1[64];
FILE *outdata;
unsigned long i;
float x1,x2,x3,x4,x5,y3,y4,y5,m3,m4,b1,b2,area,old_area;
float theta1,theta2;

float random_angle()
{
//returns a random angle in radians from 0 to 85 degrees
return ((3.1415926535/180)*(float)(rand() % 85));
}


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));

old_area = 100;

for(i=1;i<=trials;i++)
{
theta1 = random_angle();
//triangle_type=0 for any angles, triangle_type=1 for right angle triangle
if(triangle_type==0)
{
theta2 = random_angle();
}
else
{
theta2 = (3.1415926535/2)-theta1;
}
x1=-1/cos(theta1);
x2=1/cos(theta2);
y4=sin(theta1);
y5=sin(theta2);
x4=-cos(theta1);
x5=cos(theta2);
m3=y4/(x1-x4);
m4=y5/(x2-x5);
b1=m3*x1;
b2=m4*x2;
x3=(b2-b1)/(m3-m4);
y3=(m3*x3)+b1;
area=0.5*(x2-x1)*y3;
//uncomment next line to log all trials to the data file
//fprintf(outdata,"%ld\t%f\t%f\t%f\n",i,theta1*(180/3.1415926535),theta2*(180/3.1415926535),area);
if (area<old_area)
{
old_area=area;
printf("%ld\t%f\t%f\t%f\n",i,theta1*(180/3.1415926535),theta2*(180/3.1415926535),area);
}
}

	
printf("Done\n");

fclose(outdata);

return (0);
}
