#include <stdio.h>
#include <errno.h>
#include <ctype.h>

main(int argc,char **argv)
{
 FILE *f;
 int r;

 static char in[100],b[4],fn1[40],fn2[40];

 printf("Usage:\n");
 printf(" c <file>:\thexdump of <file>\n");
 printf(" w <file> <text>:\twrite <text> to <file>\n");
 printf(" i:\tdisplay and increment index\n");
 printf(" d <file>:\tdelete <file>\n");
 printf(" m <file> <new>:\trename <file> to <new>\n\n");

 while(1){
   printf("> ");gets(in);
   r=sscanf(in,"%3s %39s %39s",b,fn1,fn2);

   if(tolower(b[0])=='w' && r==3){
    f=fopen(fn1,"w");
    if(!f) printf("Could not open <%s>!\n",fn1);
    else{
      r=fprintf(f,"%s",fn2);
      fclose(f);
    }
   }else if(tolower(b[0])=='d' && r==2)
   {
     r=remove(fn1);
   }else if(tolower(b[0])=='m' && r==3)
   {
     r=rename(fn1,fn2);
   }else if(tolower(b[0])=='i' && r==1)
   {
     int idx;
     f=fopen("index","r");
     if(f){
       r=fscanf(f,"%d",&idx);
       fclose(f);
     }else idx=0;
     printf("idx=%d\n",idx);
     f=fopen("index","w");
     if(!f) printf("Could not write index\n");
     else{
       r=fprintf(f,"%d\n",idx+1);
       fclose(f);
     }
   }else if(tolower(b[0])=='c' && r==2){
    f=fopen(fn1,"r");
    if(!f) printf("Could not open <%s>!\n",fn1);
    else{
      unsigned int i=0;
      while((r=fgetc(f))!=EOF){
       ++i;
       if((i&15)==0) printf("\n%04X: ",i);
       printf("%02X ",r);
      }
      printf("\n");
      fclose(f);
    }
   }else{
     printf("illegal command\n");
   }
   printf("ret=%d errno=%d\n",r,errno);
  }
}

