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

FILE *fr, *fw;
int lineno;

void print_error(char *fmt,...)
{
  va_list args;

  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);
  fprintf(stderr,"\n");
  exit(-1);
}

char *skip_space(char *s)
{
        while ((*s==' ' || *s=='\t') && *s) s++;
        return s;
}

char *to_space(char *s)
{
        while (*s!=' ' && *s!='\t' && *s) s++;
        return s;
}

void del_nl_space(char *s)
{
        char *t;

        int len=strlen(s);
        if (!*s) return;
        t=s+len-1;
        while ( (*t=='\n' || *t==' ' || *t=='\t' )&& s<t) t--;
        *(t+1)=0;
}

int get_line (u_char *tt)
{
        if (feof(fr))
            return 0;
        while (!feof(fr))
        {
                fgets(tt,128,fr);
                lineno++;
                if (tt[0]=='#') continue;
                else break;
        }
        return 1;
}

void del_enter (char *s)
{
   int n = strlen (s);
   while (n != 0)
   {
      if ( !(s[n] == '\r' || s[n] == '\n' || s[n] == '\0'))
         break;
      n --;
   }
   s[n+1] = '\0';
}

int cmd_arg(u_char *s, u_char **cmd, u_char **arg)
{
        char *t;

        if (get_line(s) == 0)
            return 0;
        if (!*s) { *cmd=*arg=s; return 1; }

        s=skip_space(s);
        t=to_space(s);
        *cmd=s;
        if (!(*t)) {
                *arg=t;
                return 1;
        }
        *t=0;
        t++;
        t=skip_space(t);
        del_nl_space(t);
        *arg=t;
        return 1;
}

void SpliteLineCode (u_char *cmd, u_char *arg, FILE *fpOut)
{
    int i, len = strlen (arg);
    char *p, buf[3];

    buf[2] = '\0';
    for (i = 0; i < len; i += 2)
    {
        if (arg[i] < 0x80)
            break;
        p = buf;
        *p++ = arg[i];
        *p++ = arg[i+1];
        *p = '\0';
        fprintf (fpOut, "%s %s\n", cmd, buf);
    }
}

int main (int argc, char **argv)
{
    FILE *fp, *fpOut;
    u_char buf[128];
    u_char code[32], phrase[128];
    u_char *s, *cmd, *arg;
    if (argc != 3)
    {
        printf ("Usage:%s <Justiny mabiao> <target file> \n");
        exit (0);
    }
    fp = fopen (argv[1], "rt");
    fr = fp;
    fpOut = fopen (argv[2], "wt");
    while (get_line (buf) == 1)
    {
        del_enter (buf);
        cmd_arg(buf, &cmd, &arg);
        SpliteLineCode (cmd, arg, fpOut);
    } 
    fclose (fp);
    fclose (fpOut);
}

