#include "scr_Bag.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sys/time.h>

scr_Bag::scr_Bag(char* filename){
ifstream infile(filename,ios::in);
int a,b,c,d;
unsigned long int buff;
struct timeval tv;
struct timezone tz;
 //initialize random number generator
 gettimeofday(&tv, &tz);
 srand(tv.tv_usec);
 //clear the values to 0
 for(a=0;a<256;a++) value[a]=0;
 //set this baby up for hex
 infile.unsetf(ios::dec);
 infile.setf(ios::hex);
 totalnum=d=0;
 //grab the tiles from the file
 infile>>types;
 while(d<types){
  infile>>tflag[d]>>b>>value[d];
  if(tflag[d]){
   for(a=0;a<b;a++) tiles[totalnum+a]=tflag[d];
   totalnum+=b;
   d++;
  }
 }
 //lets juggle these tiles around
 for(b=0;b<1000;b++){
  c=rand()%totalnum;
  d=rand()%totalnum;
  buff=tiles[c];
  tiles[c]=tiles[d];
  tiles[d]=buff;
 }
 infile.close();
}

void scr_Bag::PutTile(unsigned long int input){
int a;
 a=rand()%totalnum;
 totalnum++;
 tiles[totalnum]=tiles[a];
 tiles[a]=input;
}

unsigned long int scr_Bag::GetTile(){
  if(totalnum){
    totalnum--;
    return(tiles[totalnum]);
  }
  else return(0);
}

//takes a character and finds its value
int scr_Bag::Value(char req){
  return(value[req]);
}


int scr_Bag::TileValue(unsigned long int req){
  char a;
  for(a=0;a<types;a++)
    if(tflag[a]==req) break;
  return(value[a]);
}

char scr_Bag::Translate(unsigned long int tile){
 char a,b=0;
 for(a=0;tile;a++,tile>>=1){
   if(tile&1){
     if(b){
       a=64;
       break;
     }
     b=1;
   }
 }
 return(a);
}

int scr_Bag::HowMany(){
  return(totalnum);
}

