module arg;

import core.stdc.stdlib : abort;

__gshared string argv0;

void parseArgs(ref string[] args, void delegate(char, string delegate(), string delegate(lazy void)) handleArg) {
    argv0 = args[0];
    args = args[1..$];
    
    while (args.length > 0 && args[0].length > 0 && args[0][0] == '-' && args[0].length > 1) {
        if (args[0] == "--") {
            args = args[1..$];
            break;
        }
        
        auto currentArg = args[0];
        args = args[1..$];
        
        for (size_t i = 1; i < currentArg.length; i++) {
            char argc_ = currentArg[i];
            
            string getArgValue() {
                if (i + 1 < currentArg.length) {
                    return currentArg[i+1..$];
                } else if (args.length > 0) {
                    auto val = args[0];
                    args = args[1..$];
                    return val;
                }
                return null;
            }
            
            string requireArgValue(lazy void onError) {
                auto val = getArgValue();
                if (val is null) {
                    onError();
                    abort();
                }
                return val;
            }
            
            handleArg(argc_, &getArgValue, &requireArgValue);
            
            if (i + 1 < currentArg.length && getArgValue() !is null) {
                break;
            }
        }
    }
}