#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  FILE            *rh;
  long            olen,len,i,stepsize,n;
  unsigned long   *data;
  char            *declstr;
  
  if(argc <= 2)
  {
error:  
    printf("bin2s -{b|w|l} data\n");
    return(0);
  }
  
  rh = fopen(argv[argc-1],"rb");
  if(rh == NULL)
  {
    printf("cant open file '%s\n",argv[argc-1]);
    return(0);
  }
  
  fseek(rh,0,SEEK_END);
  olen = len = ftell(rh);
  rewind(rh);
  
  if((len&3)!=0) { len-=(len&3);len+=4; } // make it 4 alligned

  // small header 


  stepsize=0;
  if(argv[1][0]=='-')
  {
    if(argv[1][1]=='b') stepsize=1;
    if(argv[1][1]=='w') stepsize=2;
    if(argv[1][1]=='l') stepsize=4;
  }
  if(stepsize==0) goto error;
  
  printf("@ \n");
  printf("@ bin2s by goldmomo\n");
  printf("@ \n");
  printf("@ orgfile '%s'\n",argv[argc-1]);
  printf("@ len = %d (extended to %d)\n",olen,len);
  printf("@ datasize = %d\n",stepsize);
  printf("@ \n");

  data = (unsigned long*) calloc(len,1);
  fread(data,olen,1,rh);
  fclose(rh);
  
 
  switch (stepsize)
  {
   case 1: declstr=".byte";break;
   case 2: declstr=".hword";break;
   case 4: declstr=".word";break;
  }
  
#define ROW_CNT  64  
  
  printf("\n     %s ",declstr);
  
  for(n=0,i=0;i<(len/stepsize);i++,n++)
  {      
     if(n==ROW_CNT/stepsize ) { printf("\n     %s ",declstr);n=0;}
     else            { if(i!=0) printf(","); }

      switch (stepsize)
      {
            case 1: printf("0x%2.2x",(((unsigned char*)data)[i]));break;
            case 2: printf("0x%4.4x",(((unsigned short int*)data)[i]));break;
            case 4: printf("0x%8.8x",(((unsigned long*)data)[i]));break;
      }
     
   
  }
  
  free(data);
  
  puts("");
  
  
  return (0);
}
