/*  This file is part of lsnet.
    Copyright (C) 2009-2010  Sterling Pickens
    Lsnet 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.

    Lsnet 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 lsnet.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "cores.h"

unsigned int coresdetected() {
	FILE* fp;
	//int count = 0; 
	unsigned int coresdetected = 0;
	char buf[5]; //cpux
	
	//buf = (char *)malloc(

	//char buf[SIZE];

	if( ( fp = fopen( "/proc/stat", "r" ) ) == NULL ) {
		fprintf( stderr, "Error opening /proc/stat !\n" );
		exit( 1 );
	}

        while( fgets(buf, sizeof(buf), fp) != NULL)
        {
		if (buf[0] == 'c'){
			if (buf[1] == 'p'){
				if (buf[2] == 'u'){
					if (buf[3] == '0' || buf[3] == '1' || buf[3] == '2' || buf[3] == '3' || buf[3] == '4' || buf[3] == '5' || buf[3] == '6' || buf[3] == '7' || buf[3] == '8' || buf[3] == '9'){
						coresdetected++;
					}
				}
			}
		}
	}
	//printf( "NUMBER OF CORES: %u\n", coresdetected );

	fclose( fp );
	return( coresdetected );
}

unsigned int mhzdetected(){
	FILE* fp;
	double mhzdetected = 0;
	char buf[25]; //bogomips	: xxxx6414.90
	unsigned short start_of_num = 0;
	//many ways to do this ie: tsc, rdtsc, Mhz from /proc/cpuinfo
	//halving bogomips because it will be more accurate on systems with broken tsc timers (over/underclocked systems)

	if( ( fp = fopen( "/proc/cpuinfo", "r" ) ) == NULL ) {
		fprintf( stderr, "Error opening /proc/stat !\n" );
		exit( 1 );
	}	
	while( fgets(buf, sizeof(buf), fp) != NULL){
		buf[8] = '\0';
		if( strcmp((const char *)buf, "bogomips") == 0 ){
			start_of_num = 9;
			//remove all preceding whitespace/colon just to be sure
			while(buf[start_of_num] == ' ' || buf[start_of_num] == ':' || buf[start_of_num] == '	'){
				start_of_num++;
			}
			//atoi discards preceding whitespace, and trail non-numerics
			mhzdetected = atof((const char *)&buf[start_of_num]);
			//error checks would be 0, INT_MAX, INT_MIN
		}
	}
	fclose( fp );
	//printf( "mhzdetected: %u\n", (unsigned int)ceil(mhzdetected/2) );
	return( (unsigned int)ceil(mhzdetected/2) );

}
