// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.*;

public class CmdParse {
    public static void foo(int a, int b) {
        System.out.println("foo " + a + " " + b);
    }

    public static void bar(String c) {
        System.out.println("bar " + c);
    }

    public static void process(String cmdlin) {
        StringBuffer sb = new StringBuffer("");
        List parts = new ArrayList();
        boolean inquote = false;
        boolean dquote = false;
        for(int i = 0; i < cmdlin.length(); i++) {
            char c = cmdlin.charAt(i);
            switch(c) {
                case ' ':
                    if(!inquote) {
                        if(sb.length() > 0) {
                            parts.add(sb.toString());
                            sb = new StringBuffer("");
                        }
                    } else {
                        sb.append(c);
                    }
                    break;
                case '"':
                    if(dquote && (i > 0) && cmdlin.charAt(i-1)=='"') {
                        sb.append(c);
                        dquote = false;
                    } else if(inquote && (i < cmdlin.length() - 1) && cmdlin.charAt(i+1)=='"') {
                        dquote = true;
                    } else {
                        inquote = !inquote;
                    }
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        if(sb.length() > 0) {
            parts.add(sb.toString());
        }
        String cmd = (String)parts.get(0);
        if(cmd.equals("foo")) {
            foo(Integer.parseInt((String)parts.get(1)), Integer.parseInt((String)parts.get(1)));
        } else if(cmd.equals("bar")) {
            bar((String)parts.get(1));
        } else {
            System.out.println("unknown command");
        }
    }

    public static void main(String[] args) {
        process("foo 123 456");
        process("bar \"Dette er en test\"");
        process("xxxx");
        process("foo    123    456   ");
        process("bar    \"Dette er en test\"");
        process("bar \"\"\"\"");
    }
}
