compile function next_mesa_invoice_key( Operation, Key )
begin condition
pre:
post:
end condition
* this function will return the next available MESA invoice key number
* It will get a lock and hold it so the calling routine will
* be responsible for unlocking
$insert logical
$insert msg_equates
declare function msg

if Operation = 'NEXT' then
    open 'INVOICE' to InvoiceTable else
        MsgInfo = ''
        MsgInfo<mcol$>  = -2
        MsgInfo<mrow$>  = -2
        MsgInfo<mtext$> = 'Unable to open INVOICE'
        Void = msg( '', MsgInfo )
        return 0
    end
	NextRecId = xlate( 'DICT.INVOICE', '%MESASK%', 1 , 'X' )
	Locked = false$
	loop
	    if rowexists( 'INVOICE', NextRecId ) then
	        NextRecId += 1 
	    end else
		    lock InvoiceTable, NextRecId then
		        Locked = true$
		    end else
		        NextRecId += 1
		    end
		end
	  until Locked
	repeat
	return NextRecId
end else
    open 'DICT.INVOICE' to DictInvoiceTable else
        MsgInfo = ''
        MsgInfo<mcol$>  = -2
        MsgInfo<mrow$>  = -2
        MsgInfo<mtext$> = 'Unable to open DICT.INVOICE...'     
        Void = msg( '', MsgInfo )
        return 0
    end
    Locked = false$
    loop
        lock DictInvoiceTable, '%MESASK%' then
            Locked = true$
        end
      until Locked
    repeat
    NewKey = Key+1
    write NewKey on DictInvoiceTable, '%MESASK%' else
        MsgInfo = ''
        MsgInfo<mcol$>  = -2
        MsgInfo<mrow$>  = -2
		MsgInfo<mtext$> = 'Unable to write ':NewKey:' DICT.INVOICE %MESASK%...'
        Void = msg( '', MsgInfo )
        return 0
    end
    unlock DictInvoiceTable, '%MESASK%' else
        MsgInfo = ''
        MsgInfo<mcol$>  = -2
        MsgInfo<mrow$>  = -2
		MsgInfo<mtext$> = 'Unable to unlock DICT.INVOICE %MESASK%'     
        Void = msg( '', MsgInfo )
        return 0
    end
    return 0
end   

