/* Read from the open file fp, and create the linked data structure
   that represents the Makefile contained in the file.
   See the top of pmake.h for the specification of Makefile contents.
 */




Rule *parse_file(FILE *fp) {
    // Implement this function and remove the stubbed return statement below.
    Rule *rules = NULL;
    Rule *cur_rule = NULL;
    char line[MAXLINE];

    while(fgets(line, MAXLINE, fp) != NULL) {
        // Skip comments and empty lines
        if(is_comment_or_empty(line)) {
            continue;
        }
        // Target line
        if(line[0] != '\t') {
            // Create a new rule
            Rule *rule = malloc(sizeof(Rule));
            rule->target = malloc(strlen(strtok(line, ": ")) + 1);
            strcpy(rule->target, strtok(line, ": "));
            rule->dependencies = NULL;
            rule->actions = NULL;
            rule->next_rule = NULL;
         
            // Add the new rule to the list of rules
            if(rules == NULL) {
                rules = rule;
            } else {
                cur_rule->next_rule = rule;
            }
            cur_rule = rule;

        // Action line
        } else {
            // Create a new action
            Action *act = malloc(sizeof(Action));
            act->args = NULL;
            act->next_act = NULL;

            // Add arguments
            int arg_count = 0;
            char *arg_str = strtok(line, " \t\n");
            while(arg_str != NULL) {
                act->args = realloc(act->args, (arg_count + 2) * sizeof(char *));
                act->args[arg_count] = malloc(strlen(arg_str) + 1); // Allocate memory
                strcpy(act->args[arg_count], arg_str); // Copy string
                arg_count++;

                arg_str = strtok(NULL, " \t\n");
            }
            act->args[arg_count] = NULL;

            // Add the new action to the current rule
            if(cur_rule->actions == NULL) {
                cur_rule->actions = act;
            } else {
                Action *cur_act = cur_rule->actions;
                while(cur_act->next_act != NULL) {
                    cur_act = cur_act->next_act;
                }
                cur_act->next_act = act;
            }
        }
    }
    return rules;
}