#include <stdio.h>
int main(int argc,char* argv[]){
  int bk = -1;
  int notescape = 0;
  unsigned char val = 0;
  if (argc <3){
printf("Usage: sjisfix inputfile outputfile\n");
    return -1;
  }
  FILE* in =fopen(argv[1],"rb");
  FILE* out = fopen(argv[2],"wb");
  if (in == NULL){
printf("Can not open inputfile:%s\n",argv[1]);
    return -1;
  }
  if (out == NULL){
printf("Can not open outputfile:%s\n",argv[2]);
    return -1;
  }
  while(feof(in) == 0){
    unsigned char val = getc(in);
    if (bk > 0x7f && notescape ==0){
      notescape = 1;
    }else if (bk < 0x80 && notescape%2 ==1){
      notescape = 0;
    }else if (val < 0x80 && notescape%2 ==1){
      notescape = 0;
    }else if (notescape > 0){
      notescape++;
    }
#if 0
    if (bk < 0x80  && val < 0x80){
      notescape = 0;
    }else if (bk > 0x80 ){
      notescape++;
    }
#endif
    if (bk > 0x80 && val == '\\' && notescape%2 == 1){
      fprintf(out,"\\x%02x\\",bk);
    }else if (bk == 0x0a && val == 0x0d){
      fprintf(out,"\n");
    }else{
      if (bk != -1){
        putc(bk,out);
      }
    }
    bk = val;
  }
  if (val != 0){
    putc(val,out);
  }
  return 0;
}
