function [status,result] = gptcom(command,gptdir)
% function [status,result] = gptcom(command,gptdir)
%
%    Function GPTCOM - execute command in GPT
%
%    GPTCOM allows GPT code to be executed from the Matlab command line, to
%    allow the analysis of GPT data in Matlab.  The command to be executed
%    is passed directly to DOS using the Matlab SYSTEM command.  The GPT
%    output is always echoed to the Matlab command window.
%
%    gptcom('command') - executes COMMAND in the GPT binary directory eg:
%
%        gptcom('gpt -v -o rfq.gdf rfq.in') ;
%
%    ...executes the command 'gpt -v -o rfq.gdf rfq.in' as if it had been
%    run in the GPT command window.  The default GPT directory is
%    C:\Program Files\General Particle Tracer\bin.
%
%    gptcom('command',gptdir) - runs COMMAND in the alternative directory
%        GPTDIR.  This is used if the GPT binaries are not stored in the
%        default directory given above.
%
%    [status,result] = gptcom('...') - returns the STATUS and RESULT
%        variables from the SYSTEM command.

%    Check input and output variables

    if nargin > 2
        error('Can only specify 2 input arguments: [status,result] = gptcom(command,gptdir)') ;
    elseif nargin < 1
        error('Must specify at least 1 input argument: gptcom(command)') ;
    elseif nargout > 2
        error('Can only specify 2 output arguments: [status,result] = gptcom(command,gptdir)') ;
    end

%    Get license information

    comptype = computer ;
    curdir = cd ;
    bsfs = filesep ;

    if ispc
        if strcmp(comptype(end-1:end),'64')
            license = winqueryreg('HKEY_LOCAL_MACHINE', 'SOFTWARE\Wow6432Node\Pulsar Physics\General Particle Tracer\2.8', 'ProductID') ;
        else
            license = winqueryreg('HKEY_LOCAL_MACHINE', 'SOFTWARE\Pulsar Physics\General Particle Tracer\2.8', 'ProductID') ;
        end
    end

%    Set GPT binary directory

    if nargin < 2

        if ispc
            if strcmp(comptype(end-1:end),'64')
                gptdir = ['C:\PROGRA~2\GENERA~1\bin\'] ;
            else
                gptdir = ['C:\PROGRA~1\GENERA~1\bin\'] ;
            end
        elseif ismac
            gptdir = ['~/gpt/bin/'] ;
        end

    end

    if ~ischar(command)
        error('GPT COMMAND variable must be a string') ;
    elseif ~ischar(gptdir)
        error('GPTDIR variable must be a string') ;
    end

    if ~strcmp(gptdir(end),filesep)
        gptdir(end+1) = filesep ;
    end

%    Add license information to run GPT

    if strcmp('gpt ', command(1:4)) == 1
        command = [command ' GPTLICENSE=' license] ;
    end
    
    gptexec = [gptdir command] ;

    disp(' ') ;
    disp([command]) ;
    disp(' ') ;

    [status,result] = system(gptexec,'-echo') ;

    return

