#include "common.h"

void writemode(FILE* f)
{
fseek(f,ftell(f),SEEK_SET);
}

void fwrite4(FILE* f,int x)
{
writemode(f);
fputc(((x    ) & 0xFF) , f);
fputc(((x>>8 ) & 0xFF) , f);
fputc(((x>>16) & 0xFF) , f);
fputc(((x>>24) & 0xFF) , f);
}

void fwrite2(FILE* f,int x)
{
writemode(f);
fputc(((x    ) & 0xFF) , f);
fputc(((x>>8 ) & 0xFF) , f);
}

int fread4(FILE* f)
{
int x=0;
for(int i=0;i<4;i++)
 {
 int n=fgetc(f);
 if(n==EOF) break;
 x |= ((unsigned int)n << (i*8));
 }
return x;
}

int fread2(FILE* f)
{
int x=0;
for(int i=0;i<2;i++)
 {
 int n=fgetc(f);
 if(n==EOF) break;
 x |= ((unsigned int)n << (i*8));
 }
return x;
}

// Writes standard string, no zero terminator
void fwrites(FILE* f,std::string s)
{
writemode(f);
int l=s.length();
int c=0;
while(l>=1)
 {
 fputc(s[c],f);
 c++;
 l--;
 }
}

// Reads standard string, no zero terminator but length is provided (this checks eof)
std::string freads(FILE* f,int length)
{
std::string rtn="";
while(length>0)
 {
 int  n=fgetc(f);
 if(n>=0 && n<=255)
  rtn += (char)n;
 else
  break;
 length--;
 }
return rtn;
}

void fwritem(FILE* f,int fnum,regint start,regint length)
{
writemode(f);
fwrite((char*)start,1,length,f);
}

void freadm(FILE* f,int fnum,regint start,regint length)
{
fread((char*)start,1,length,f);
}



