#include "kernel/types.h"
#include "user/user.h"
#include "kernel/param.h"

// #define MAXARG       32  // max exec arguments

int main(int argc, char *argv[]){
    int i, count = 0;
    int k, m = 0;
    char *splitLine[MAXARG], *p; // p is to help with passing the parameters
    char block[32], buf[32]; // block and buf store the read content
    p = buf;
    for (i = 1; i<argc; i++){         // this is to copy the command line parameters to splitLine
        splitLine[count++] = argv[i]; // start from 1 because i = 0 is to store the path of the file
    }
    while( (k = read(0, block, sizeof(block) )) > 0 ){ // to read all the parameters till it ends
        for(i = 0; i<k; i++){ // analyse a parameter letter by letter
            if(block[i] == '\n'){ // when meeting '\n',
                buf[m] = 0;
                splitLine[count++] = p;
                splitLine[count] = 0;
                m = 0;
                p = buf;
                count = argc - 1; // prepare for reading the next new parameter
                if(fork() == 0){
                    exec(argv[1], splitLine); // the path and parameters
                }
                wait(0);
            }
            else if(block[i] == ' '){ // when meeting ' ',new the buf and p
                buf[m++] = 0;
                splitLine[count++] = p;
                p = &buf[m];
            }
            else{ // just commonly store the patameter letter by letter
                buf[m++] = block[i];
            }
        }
    }
    exit(0);
}