//  
//  Copyright (c) 1994 by Mike Romberg (  romberg@md.fsl.noaa.gov )
//
//  This file may be distributed under terms of the GPL
//

// Modifications made Jan '95 
// Copyright Richard Laxton (u2105546@cumulus.csd.unsw.oz.au),
// Distributed under GPL.


#include "cpumeter.h"

CPUMeter::CPUMeter( )
{
  for ( int i = 0 ; i < 2 ; i++ )
    for ( int j = 0 ; j < 4 ; j++ )
      cputime_[i][j] = 0;
  cpuindex_ = 0;
  used_ = total_ = 0;
  stats_ = new ifstream( STATFILENAME );
}

CPUMeter::~CPUMeter( void ){
  delete stats_;
}

int CPUMeter::checkevent( int scale )
{
  static int avg_load=-1, load[10], x;
  
  if (avg_load == -1)      
    for (avg_load=9; avg_load >= 0; avg_load--) load[avg_load] = 0;
      
  getcputime();
  for (x=9; x > 0; x--) load[x] = load[x-1];
  load[0] = (int) (used_/total_)*scale;
  avg_load = (load[0]*64 + load[1]*64 + load[2]*32 + load[3]*32 + load[4]*16 +
              load[5]*8 + load[6]*8  + load[7]*4 + load[8]*2 + load[9])/231;
//  avg_load = (load[0]*5 + load[1] + load[2] + load[3] + load[4] +
//              load[5] + load[6] + load[7] + load[8] + load[9])/15;
  return avg_load;
}

void CPUMeter::getcputime( void ){
  total_ = 0;
  stats_->seekg( 0 );
  char tmp[10];

  *stats_ >>tmp >>cputime_[cpuindex_][0]  
	        >>cputime_[cpuindex_][1]  
	        >>cputime_[cpuindex_][2]  
	        >>cputime_[cpuindex_][3];

  int oldindex = (cpuindex_+1)%2;
  for ( int i = 0 ; i < 4 ; i++ ){
    fields_[i] = cputime_[cpuindex_][i] - cputime_[oldindex][i];
    total_ += fields_[i];
    if (i==2) used_=total_;
  }
  cpuindex_ = (cpuindex_ + 1) % 2;
}
