#!/usr/bin/env python
# Parse KIDS files (.KID)
#
#
#---------------------------------------------------------------------------
# Copyright 2011 The Open Source Electronic Health Record Agent
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#---------------------------------------------------------------------------
import sys
import os

def unpack(kid, routineDir):
    # method variables
    routineLines = 0
    routineName = ""
    routine = None
    output = sys.stdout

    with open(kid, 'r') as f:
        for line in f:
            # identifier is the line preceding the data (RTN,BLD,KRN,RPC,etc) that provides processing information
            # actual data is always on the next line
            # Handle Routines Block
            if line.startswith('''"RTN"'''):
                if '''"RTN")''' in line:
                    # Next line contains the number of routines in the build
                    line = f.next()
                    numberOfRoutines = line
                    output.write('Number of routines:  ' + numberOfRoutines)
                    line = f.next()
                    #output.write("line before while:  " + line)
                # Loop over RTN section
                while line.startswith('''"RTN",'''):
                    identifier = line.split(',')
                    if len(identifier) == 2:
                        # Beginning of Routine Header
                        # "RTN","RoutineName")
                        # Data (line+1): Unknown^Unknown^ChecksumAfter^ChecksumBefore
                        line = f.next()
                        routineHeader = line.strip()
                        routineName = identifier[1].strip()
                        routineName = routineName.strip(')\"')
                        output.write('Routine Header:  ' + routineHeader + "\n")
                        output.write('Routine Name:  ' + routineName + "\n")
                        if routine:
                            routine.close()
                            routine = None
                        routine = open(routineDir + "/" + routineName + ".m", 'w')
                        if identifier[1].strip(' \n\")') != routineName:
                            output.write('identifier:  ' + identifier[1] + "\n")
                            output.write('Number of lines in routine: ' + str(routineLines) + "\n")
                            routineLines = 0
                    if len(identifier) == 4:
                        routineLines += 1
                        # Actual Routine Data
                        # "RTN","RoutineName",LineNumber,0)
                        # Data (line+1): Line of M code
                        line = f.next()
                        code = line
                        routine.write(code)
                    line=f.next()

def checksum(routine):
    checksum = 0
    lineNumber = 1
    characterPosition = 1
    savedcharater=""
    with open(routine, 'r') as f:
        for line in f:
            #sys.stdout.write(str(lineNumber) + "  " + line)
            lineNumber += 1
            # ignore the second line
            if lineNumber == 2:
                continue
            for character in line:
                #sys.stdout.write("line position " +str(lineNumber) +"\n")
                #sys.stdout.write("character position " + str(characterPosition) + "\n")
                if characterPosition == 1:
                    sys.stdout.write("1st character " +character + "\n")
                    if character == ' ':
                        sys.stdout.write("indented line")
                        continue
                characterPosition +=1
                if character == ';':
                    continue
                    if savedcharater == ';':
                        # character and next character = ;;
                        # this needs to be counted
                        checksum += ord(character)*lineNumber*characterPosition
                    # this doesn't need to be counted or the rest of the line (comment)
                    continue
                # normal code
                checksum += ord(character)*lineNumber*characterPosition
            characterPosition=0
    sys.stdout.write("Checksum is: "+str(checksum)+"\n")

def main():
    #unpack(sys.argv[1], sys.argv[2])
    checksum(sys.argv[1])
         
if __name__ == '__main__':
    main()

@@ -3361,17 +3361,17 @@
 umber = 
-1
+0
 %0A    cha
@@ -3387,17 +3387,17 @@
 ition = 
-1
+0
 %0A    sav
@@ -3471,69 +3471,8 @@
  f:%0A
-            #sys.stdout.write(str(lineNumber) + %22  %22 + line)%0A
     
@@ -3605,198 +3605,138 @@
     
-for character in line:%0A                #sys.stdout.write(%22line position %22 +str(lineNumber) +%22%5Cn%22)%0A                #sys.stdout.write(%22character position %22 + str(characterPosition) + %22%5Cn%22)%0A   
+lengthOfLine = mFind(line,%22 %22)%0A            if mExtract(line,lengthOfLine) != %22;%22:%0A                lengthOfLine = line.__len__()-1%0A
     
@@ -3747,34 +3747,50 @@
     
- if characterPosition
+elif mExtract(line, 1+lengthOfLine)
  == 
-1
+%22;%22
 :%0A  
@@ -3807,627 +3807,374 @@
     
-    sys.stdout.write(%221st character %22 +character + %22%5Cn%22)%0A                    if character == ' ':%0A                        sys.stdout.write(%22indented line%22)%0A                        continue%0A                characterPosition +=1%0A                if character == ';':%0A                    continue%0A                    if savedcharater == ';':%0A                        # character and next character = ;;%0A                        # this needs to be counted%0A                        checksum += ord(character)*lineNumber*characterPosition%0A                    # this doesn't need to be counted or the rest of the line (comment)%0A  
+lengthOfLine = line.__len__()-1%0A            else:%0A                lengthOfLine = lengthOfLine - 1%0A            for character in xrange(lengthOfLine):%0A                characterPosition +=1%0A                # normal code%0A                temp = lineNumber+characterPosition%0A                checksum += ord(mExtract(line,character))*temp%0A            characterPosition = 0%0A
     
@@ -4185,213 +4185,229 @@
     
+%0A
     
-  continue%0A                # normal code%0A                checksum += ord(character)*lineNumber*characterP
+sys.stdout.write(%22Checksum is: %22+str(checksum)+%22%5Cn%22)%0A%0Adef mExtract(string,p
 osition
+):
 %0A    
-        characterPosition=0%0A    sys.stdout.write(%22Checksum is: %22+str(checksum)+%22%5Cn%22)
+chars = list(string)%0A    return chars%5B--position%5D%0A%0Adef mFind(string,substring):%0A    f = string.index(substring)%0A    return f +1
 %0A%0Ade

Fix logic errors and include mumps functions