Problem with inner hgrid

Hi All,
Im able to display a hgrid in page, but when i modified the hgrid to display inner hgrid Im unable to display the second level hgrid. please correct me where Im wrong. Please find the following VL, AM, PG. And I have 2 VOs for master record and child record.
View Link
<?xml version='1.0' encoding='windows-1252' ?>
<!DOCTYPE ViewLink SYSTEM "jbo_03_01.dtd">
<ViewLink
Name="ItemsVL2" >
<DesignTime>
<Attr Name="_isCodegen" Value="true" />
<Attr Name="_version" Value="10.1.3.41.57" />
</DesignTime>
<ViewLinkDefEnd
Name="SubTableVO"
Cardinality="1"
Owner="oracle.apps.cz.cx.server.SubTableVO"
Source="true" >
<AttrArray Name="Attributes">
<Item Value="oracle.apps.cz.cx.server.SubTableVO.ItemID" />
<Item Value="oracle.apps.cz.cx.server.SubTableVO.SessionId" />
</AttrArray>
<DesignTime>
<Attr Name="_finderName" Value="SubTableVO" />
<Attr Name="_isUpdateable" Value="true" />
</DesignTime>
</ViewLinkDefEnd>
<ViewLinkDefEnd
Name="AcessorVO"
Cardinality="-1"
Owner="oracle.apps.cz.cx.server.SubTableVO" >
<AttrArray Name="Attributes">
<Item Value="oracle.apps.cz.cx.server.SubTableVO.ParentItemID" />
<Item Value="oracle.apps.cz.cx.server.SubTableVO.SessionId" />
</AttrArray>
<DesignTime>
<Attr Name="_finderName" Value="AcessorVO" />
<Attr Name="_isUpdateable" Value="true" />
</DesignTime>
</ViewLinkDefEnd>
</ViewLink>
AM
<ViewLinkUsage
Name="ItemsVL1"
ViewLinkObjectName="oracle.apps.cz.cx.server.ItemsVL"
SrcViewUsageName="oracle.apps.cz.cx.server.ConfigAM.TableVO1"
DstViewUsageName="oracle.apps.cz.cx.server.ConfigAM.SubTableVO1" >
<DesignTime>
<Attr Name="_isCodegen" Value="true" />
<Attr Name="_version" Value="10.1.3.41.57" />
</DesignTime>
</ViewLinkUsage>
<ViewLinkUsage
Name="ItemsVL2_1"
ViewLinkObjectName="oracle.apps.cz.cx.server.ItemsVL2"
SrcViewUsageName="oracle.apps.cz.cx.server.ConfigAM.SubTableVO1"
DstViewUsageName="oracle.apps.cz.cx.server.ConfigAM.SubTableVO2" >
<DesignTime>
<Attr Name="_isCodegen" Value="true" />
<Attr Name="_version" Value="10.1.3.41.57" />
</DesignTime>
</ViewLinkUsage>
Page
<oa:tree id="ServiceItemRG" text="Service Item" usage="hGrid">
<members>
<oa:nodeDef id="nodeDef1" viewName="TableVO1" viewAttr="Item"/>
<oa:childNode id="childNode1" viewLink="ItemsVL" viewLinkAccessorName="AcessorVO">
<members>
<oa:nodeDef id="nodeDef2" viewName="SubTableVO1" viewAttr="Item"/>
<oa:childNode id="childNode2" ancestorNode="oracle/apps/cz/cx/webui/ItemsPG.childNode1"
viewLink="ItemsVL2" viewLinkAccessorName="AcessorVO"/>
</members>
</oa:childNode>
</members>
</oa:tree>
I executed query for master records VO only like ItemID = 2904 , I haven't executed any query for child records or for the sub child record.
The data in the database would be
Item ItemID ParentItem
Master Record 2904
Child Record 0912 2904
Sub Child Record 0912
only the first level of hgrid is displayed, cannot see the second level or the records of sub child.
Thanks,

Hi,
Really thanks for the reply, its a 2 level hgrid. Please correct me if Im wrong you can find the snippets of xmls in the above post. And one thing is that after adding ItemsVL1 which is first level hgrid i tried adding ItemsVL2 to the child the instance it created is SubTableVO2 but i manual edited the xml changing it to SubTableVO1 I guess we need to use the same VO instance for child and second level parent.
Ex
In AM for first level hgrid the parent Vo is
--------------TableVO1 (to this parent vo I added child VO through ItemsVL1)
------------------SubTableVO1 via ItemsVL1(and to this child VO, I added second level hgrid View link ItemsVL2)
------------------------SubTableVO1 via ItemsVL2(so actually here it created instance SubTableVO2 but I manually edited the xml and changed to SubTableVO1, as I guess we need to use the same Vo for first level child and second level parent, I think here I may be worng but frankly I tried with SubTableVO2 also but of no use.)
So any correections , please let me know.
Thanks,

Similar Messages

  • Problems with inner classes in JasminXT

    I hava problems with inner classes in JasminXT.
    I wrote:
    ;This is outer class
    .source Outer.j
    .class Outer
    .super SomeSuperClass
    .method public createrInnerClass()V
         .limit stack 10
         .limit locals 10
         ;create a Inner object
         new Outer$Inner
         dup
         invokenonvirtual Outer$Inner/<init>(LOuter;)V
         ;test function must print a Outer class name
         invokevirtual Outer$Inner/testFunction ()V
    .end method
    ;This is inner class
    .source Outer$Inner.j
    .class Outer$Inner
    .super java/lang/Object
    .field final this$0 LOuter;
    ;contructor
    .method pubilc <init>(LOuter;)V
         .limit stack 10
         .limit locals 10
         aload_0
         invokenonvirtual Object/<init>()V
         aload_0
         aload_1
         putfield Inner$Outer/this$0 LOuter;
         return
    .end method
    ;test
    .method public testFunction ()V
         .limit stack 10
         .limit locals 10
         ;get out object
         getstatic java/io/PrintStream/out  java/io/PrintStream;
         aload_0
         invokevirtual java/lang/Object/getClass()java/lang/Class;
         ;now in stack Outer$Inner class
         invokevirtual java/Class/getDeclaringClass()java/lang/Class;
         ;but now in stack null
         invokevirtual java/io/PrintStream/print (Ljava/lang/Object;)V
    .end methodI used dejasmin. Code was equal.
    What I have to do? Why getDeclatingClass () returns null, but in dejasmin code
    it returns Outer class?

    Outer$Inner naming convention is not used by JVM to get declaring class.
    You need to have proper InnerClasses attribute (refer to http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#79996)
    in the generated classes. Did you check using jclasslib or another class file viewer and verified that your .class files have proper InnerClasses attribute?

  • Problems with inner classes

    I ran into the following problems when I tried to read into an inner class:
    This is my .jdo file
    <?xml version="1.0"?>
    <jdo>
    <package name="com.globalrefund.jdo.mna">
    <class name="Parameter$Syspar" objectid-class="SysparId">
    <extension vendor-name="kodo" key="table" value="syspar"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="landescode" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="landescode"/>
    </field>
    <field name="waehrungscode">
    <extension vendor-name="kodo" key="data-column"
    value="waehrungscode"/>
    </field>
    </class>
    </package>
    </jdo>
    1.) appidtool does not work for this inner class, I get this stack trace
    C:\users\Bernhard\jbProject\refundManual>appidtool
    src\com\globalrefund\jdo\mna\Parameter$Syspar.jdo
    Generating an application id for type "class
    com.globalrefund.jdo.mna.Parameter$Syspar"...
    Exception in thread "main" java.lang.NullPointerException
    at com.solarmetric.kodo.enhance.ApplicationIdTool.getFile(Unknown
    Source)
    at
    com.solarmetric.kodo.enhance.ApplicationIdTool.writeApplicationId(Unknown
    Source)
    at
    com.solarmetric.kodo.enhance.ApplicationIdTool.writeApplicationId(Unknown
    Source)
    at com.solarmetric.kodo.enhance.ApplicationIdTool.main(Unknown
    Source)
    2.) I tried to use a hand coded inner class as ID class, but id did not work
    (is this not possible ?)
    Exception in thread "main" java.lang.NoSuchMethodError:
    com.globalrefund.jdo.mna.Parameter$SysparId: method <init>()V not found
    at
    com.globalrefund.jdo.mna.Parameter$Syspar.jdoNewObjectIdInstance(Parameter.j
    ava)
    at
    javax.jdo.spi.JDOImplHelper.newObjectIdInstance(JDOImplHelper.java:166)
    at com.solarmetric.kodo.util.ObjectIds.fromPKValues(Unknown Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.createFromResultSet(
    Unknown Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager$2.getResultObject(Un
    known Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.instantiateRow(Unknown
    Source)
    at com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.get(Unknown
    Source)
    at java.util.AbstractList$Itr.next(AbstractList.java:416)
    at com.solarmetric.kodo.runtime.ResultListIterator.next(Unknown
    Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.ResultListFactory.createResultList(Un
    known Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.executeQuery(Unknown
    Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCQuery.executeQuery(Unknown
    Source)
    at com.solarmetric.kodo.query.QueryImpl.executeWithMap(Unknown
    Source)
    at com.solarmetric.kodo.query.QueryImpl.execute(Unknown Source)
    at
    com.solarmetric.kodo.query.QueryImpl$SynchronizedQuery.execute(Unknown
    Source)
    at com.globalrefund.jdo.mna.Parameter.<init>(Parameter.java:71)
    3.) It worked after I moved the ID class into a separate class
    Regards,
    Bernhard

    1.) appidtool does not work for this inner class, I get this stack traceThis is a bug. It will be corrected in the final release of 2.3, due out
    Real Soon Now. Thanks for catching this!
    2.) I tried to use a hand coded inner class as ID class, but id did not work
    (is this not possible ?)
    Exception in thread "main" java.lang.NoSuchMethodError:
    com.globalrefund.jdo.mna.Parameter$SysparId: method <init>()V not foundThis exception is saying that your application ID class does not have a
    no-args constructor. Make sure the id class is a static inner class;
    otherwise Java transparently adds a parent object parameter to each
    constructor, and so the application id class will violoate the JDO constraint
    of having a no-args constructor.

  • Performance problem with inner join

    Hi
    With this Query
    SELECT *
    FROM TABLE1
    INNER JOIN TABLE2
    ON TABLE1.Col1 = TABLE2.Col2 AND TABLE1.Col2 = TABLE2.Col2
    WHERE TABLE1.Col3 = 'AB' AND
    TABLE2.Col4 = 'ZZ';
    TABLE1 have 6,000,000 of records
    TABLE2 have 9,000,000 of records
    when I run this query the result take 30 secs
    If I change the Optimizer_mode for 'RULE'
    the result take 4 secs
    All statistics is ok
    Primary Key exists for TABLE1 and TABLE2 base-on Col1 and Col2
    And index on Table1.Col3,Table1.Col4
    somebody can help me ?

    Analyze tables compute statistics
    and analyze index compute statistics
    I join explain plan
    STATEMENT_ID TIMESTAMP REMARKS OPERATION OPTIONS OBJECT_NODE OBJECT_OWNER OBJECT_NAME OBJECT_INSTANCE OBJECT_TYPE OPTIMIZER SEARCH_COLUMNS ID PARENT_ID POSITION COST CARDINALITY BYTES
    OTHER_TAG PARTITION_START PARTITION_STOP PARTITION_ID OTHER DISTRIBUTION CPU_COST IO_COST TEMP_SPACE
    WithRule1 2004-01-19 16:28:43 SELECT STATEMENT RULE 0
    WithRule1 2004-01-19 16:28:43 SORT AGGREGATE 1 0 1
    WithRule1 2004-01-19 16:28:43 NESTED LOOPS 2 1 1
    WithRule1 2004-01-19 16:28:43 TABLE ACCESS BY INDEX ROWID MICRODEV T088_INSC 1 ANALYZED 3 2 1
    WithRule1 2004-01-19 16:28:43 INDEX RANGE SCAN MICRODEV IX4_T088_INSC NON-UNIQUE ANALYZED 2 4 3 1
    WithRule1 2004-01-19 16:28:43 TABLE ACCESS BY INDEX ROWID MICRODEV T090_CPOS_DEM 2 ANALYZED 5 2 2
    WithRule1 2004-01-19 16:28:43 INDEX UNIQUE SCAN MICRODEV PK_T090_CPOS_DEM UNIQUE ANALYZED 2 6 5 1
    7 rows selected.
    STATEMENT_ID TIMESTAMP REMARKS OPERATION OPTIONS OBJECT_NODE OBJECT_OWNER OBJECT_NAME OBJECT_INSTANCE OBJECT_TYPE OPTIMIZER SEARCH_COLUMNS ID PARENT_ID POSITION COST CARDINALITY BYTES
    OTHER_TAG PARTITION_START PARTITION_STOP PARTITION_ID OTHER DISTRIBUTION CPU_COST IO_COST TEMP_SPACE
    WithChoose1 2004-01-19 16:29:37 SELECT STATEMENT CHOOSE 0 21680 21680 1 40
    21680
    WithChoose1 2004-01-19 16:29:37 SORT AGGREGATE 1 0 1 1 40
    WithChoose1 2004-01-19 16:29:37 HASH JOIN 2 1 1 21680 59050 2362000
    21680 3875000
    WithChoose1 2004-01-19 16:29:37 TABLE ACCESS BY INDEX ROWID MICRODEV T088_INSC 1 ANALYZED 3 2 1 7031 96727 2708356
    7031
    WithChoose1 2004-01-19 16:29:37 INDEX RANGE SCAN MICRODEV IX4_T088_INSC NON-UNIQUE ANALYZED 2 4 3 1 232 96727
    232
    WithChoose1 2004-01-19 16:29:37 TABLE ACCESS FULL MICRODEV T090_CPOS_DEM 2 ANALYZED 5 2 2 11224 5662693 67952316
    11224
    6 rows selected.

  • Problem with display tags (not accepting inner tags)

    Hi guys ,
    I am using display tags which is fine but i had a problem with anchor tag and the jsp display tag.
    <display:column title="Row_Id" >
    ' target="-blank" onclick=""><c:out value="${row_rowNum}"/>
    </display:column>
    here i got the exception:
    The value of attribute "href" associated with an element type "a" must not contain the '<' character.
    here if jstl is not used then how to put my value in anchor tag
    please help me.

    Can you use EL directly:
    <a href="example.jsp?id=${row.id"/"></a>

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problem with writing and reading using serialization

    I am having a problem with writing and reading an object that has another object in it. The purpose of the class is to write a order that has multiple items in it. And there will be several orders. This is for an IB project, where one of the requirements is to utilize a hierarchical composite data structure. That is, it is "one that contains more than one element and at least one of the elements is a composite data structure. Examples are, an array or linked list of records, a record that has one field that is another record, or an array". The code is shown below:
    The error produced is
    java.lang.NullPointerException
         at SamsonRubberIndustries.CustomerOrderDetails.createCustOrdDetailsScreen(CustomerOrderDetails.java:150)
         at SamsonRubberIndustries.CustomerOrderDetails$1.run(CustomerOrderDetails.java:78)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    public class CustOrdObject implements Serializable {
         public int CustID;
         public int CustOrderID;
         public Object OrderDate;
         public InnerCustOrdObject[] innerCustOrdObj;
         public float GrandTotal;
         public int MaxItems;
         public CustOrdObject() {}
         public CustOrdObject(InnerCustOrdObject[] innerCustOrdObj,
    int CustID, int CustOrderID, Object OrderDate,
    float GrandTotal, int innerarrlength, int innerarrpos, int MaxItems) {
              this.CustID = CustID;
              this.CustOrderID = CustOrderID;
              this.OrderDate = OrderDate;
              this.GrandTotal = GrandTotal;          
              this.MaxItems = MaxItems;
              this.innerCustOrdObj = new InnerCustOrdObject[MaxItems];
         public InnerCustOrdObject[] getInnerCustOrdObj() {
              return innerCustOrdObj;
         public void setInnerCustOrdObj(InnerCustOrdObject[] innerCustOrdObj) {
              this.innerCustOrdObj = innerCustOrdObj;
         public int getCustID() {
              return CustID;
         public void setCustID(int custID) {
              CustID = custID;
         public int getCustOrderID() {
              return CustOrderID;
         public void setCustOrderID(int custOrderID) {
              CustOrderID = custOrderID;
         public Object getOrderDate() {
              return OrderDate;
         public void setOrderDate(Object orderDate) {
              OrderDate = orderDate;
         public void setGrandTotal(float grandTotal) {
              GrandTotal = grandTotal;
         public float getGrandTotal() {
              return GrandTotal;
         public int getMaxItems() {
              return MaxItems;
         public void setMaxItems(int maxItems) {
              MaxItems = maxItems;
    public class InnerCustOrdObject implements Serializable{
         public int ItemNumber;
         public float UnitPrice;
         public int QuantityRequired;
         public float TotalPrice;
         public InnerCustOrdObject() {}
         public InnerCustOrdObject(int ItemNumber, float
    UnitPrice, int QuantityRequired, float TotalPrice){
              this.ItemNumber = ItemNumber;
              this.UnitPrice = UnitPrice;
              this.QuantityRequired = QuantityRequired;
              this.TotalPrice = TotalPrice;
         public int getItemNumber() {
              return ItemNumber;
         public void setItemNumber(int itemNumber) {
              ItemNumber = itemNumber;
         public int getQuantityRequired() {
              return QuantityRequired;
         public void setQuantityRequired(int quantityRequired) {
              QuantityRequired = quantityRequired;
         public float getTotalPrice() {
              return TotalPrice;
         public void setTotalPrice(float totalPrice) {
              TotalPrice = totalPrice;
         public float getUnitPrice() {
              return UnitPrice;
         public void setUnitPrice(float unitPrice) {
              UnitPrice = unitPrice;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems;
         private static boolean FileExists, recFileExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.dat");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                 innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord-1);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              //TotPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++CurrentRecord;
                             //readOrder();
                             //readInnerOrderRecord(CurrentRecord);
                             setInnerFieldText(currentItem);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             //readOrder();
                             setInnerFieldText(currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             writeRecordNumber(MaxRecord);
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             currentItem++;
                             setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              System.err.println("currentItem" + currentItem);
              getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07
    Message was edited by:
    Kilik07

    ok i got reading to work to a certain extent... but the prob is i cnt seem to save my innerCustOrdObj proprly...when ever i look for a record using the gotorecordbtn, the outerobject, which is the orderDetails, seems to change but the innerCustOrdObj remains the same... heres the new code..
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems = 1;
         private static boolean FileExists, recFileExists;
         private static boolean RecordExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.ser");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                   //CurrentRecord--;
                   //System.out.println("Current Rec Here"+CurrentRecord);
                   if(orderDetails[CurrentRecord] == null){
                        System.err.println("CustomerOrderObj 1 is null !!");
                   }else{
                        System.err.println("CustomerOrderObj 1 is  not null !!");
                   if(orderDetails[CurrentRecord].getInnerCustOrdObj() == null){
                        System.err.println("InnerCustomerOrderObj is null !!");
                   }else{
                        System.err.println("InnerCustomerOrderObj is  not null !!");
                   innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord);
                   getInnerFieldText(MaxItems);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              //CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              TotPriceTxt.setEditable(false);
              TotPriceTxt.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt){
                        TotPriceTxt.setText(""+Integer.parseInt(UnitPriceTxt.getText())*Integer.parseInt(QuantityReqTxt.getText()));
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println("Current Record " + CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             CurrentRecord = MaxRecord;
                             orderDetails[CurrentRecord] = new CustOrdObject();
                             writeRecordNumber(MaxRecord);
                             MaxItems = 1;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        setInnerFieldText(MaxItems);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             MaxItems++;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             System.out.println("Max Items "+MaxItems);
                             currentItem = MaxItems;
                             orderDetails[CurrentRecord].setMaxItems(MaxItems);
                             ///setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              gotorecordbtn = new JButton("Go To Record", createGotoButtonIcon());
              gotorecordbtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt){
                         * The text from the GotorecordTxt textfield will be taken and assigned
                         * to a temporary integer variable called Find. 
                        int Find = Integer.parseInt(CustOrderIDTxt.getText());
                        for(int j=1; j <= MaxRecord; j++){
                              * Using a for loop, each record can be read using the readCustRecord
                              * method.
                             getFieldText(j);
                              * An if condition is utilized to check whether the temporary stored variable, Find,
                              * matches a field in a record. If this record is found, then using the RecordExists
                              * which was declared at the top, either a true or false statement can be assigned
                              * If the record exists, then a true statement will be assigned, if not a false
                              * statement will be assigned.
                             if(orderDetails[j].getCustOrderID() == Find){
                                  RecordExists = true;
                                  break;
                             }else{
                                  RecordExists = false;
                        if(RecordExists == false){
                              * If the RecordExists is assigned a false statement, then a message will be
                              * displayed to show that the record does not exist.
                             JOptionPane.showMessageDialog(null, "Record Does Not Exist!", "Error Message", JOptionPane.ERROR_MESSAGE, createErrorIcon());
                        }else{
                             getFieldText(Find);
              buttonpanel.add(gotorecordbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setMaxItems(MaxItems);
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              orderDetails[orderID].getInnerCustOrdObj();
              System.err.println("currentItem" + currentItem);
              //getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   /*               System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());*/
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07

  • Problem with XMLTABLE and LEFT OUTER JOIN

    Hi all.
    I have one problem with XMLTABLE and LEFT OUTER JOIN, in 11g it returns correct result but in 10g it doesn't, it is trated as INNER JOIN.
    SELECT * FROM v$version;
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
    PL/SQL Release 11.2.0.1.0 - Production
    "CORE     11.2.0.1.0     Production"
    TNS for Linux: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    --test for 11g
    CREATE TABLE XML_TEST(
         ID NUMBER(2,0),
         XML XMLTYPE
    INSERT INTO XML_TEST
    VALUES
         1,
         XMLTYPE
              <msg>
                   <data>
                        <fields>
                             <id>g1</id>
                             <dat>data1</dat>
                        </fields>
                   </data>
              </msg>
    INSERT INTO XML_TEST
    VALUES
         2,
         XMLTYPE
              <msg>
                   <data>
                        <fields>
                             <id>g2</id>
                             <dat>data2</dat>
                        </fields>
                   </data>
              </msg>
    INSERT INTO XML_TEST
    VALUES
         3,
         XMLTYPE
              <msg>
                   <data>
                        <fields>
                             <id>g3</id>
                             <dat>data3</dat>
                        </fields>
                        <fields>
                             <id>g4</id>
                             <dat>data4</dat>
                        </fields>
                        <fields>
                             <dat>data5</dat>
                        </fields>
                   </data>
              </msg>
    SELECT
         t.id,
         x.dat,
         y.seqno,
         y.id_real
    FROM
         xml_test t,
         XMLTABLE
              '/msg/data/fields'
              passing t.xml
              columns
                   dat VARCHAR2(10) path 'dat',
                   id XMLTYPE path 'id'
         )x LEFT OUTER JOIN
         XMLTABLE
              'id'
              passing x.id
              columns
                   seqno FOR ORDINALITY,
                   id_real VARCHAR2(30) PATH '.'
         )y ON 1=1
    ID     DAT     SEQNO     ID_REAL
    1     data1     1     g1
    2     data2     1     g2
    3     data3     1     g3
    3     data4     1     g4
    3     data5          Here's everything fine, now the problem:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for HPUX: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    --exactly the same environment as 11g (tables and rows)
    SELECT
         t.id,
         x.dat,
         y.seqno,
         y.id_real
    FROM
         xml_test t,
         XMLTABLE
              '/msg/data/fields'
              passing t.xml
              columns
                   dat VARCHAR2(10) path 'dat',
                   id XMLTYPE path 'id'
         )x LEFT OUTER JOIN
         XMLTABLE
              'id'
              passing x.id
              columns
                   seqno FOR ORDINALITY,
                   id_real VARCHAR2(30) PATH '.'
         )y ON 1=1
    ID     DAT     SEQNO     ID_REAL
    1     data1     1     g1
    2     data2     1     g2
    3     data3     1     g3
    3     data4     1     g4As you can see in 10g I don't have the last row, it seems that Oracle 10g doesn't recognize the LEFT OUTER JOIN.
    Is this a bug?, Metalink says that sometimes we can have an ORA-0600 but in this case there is no error returned, just incorrect results.
    Please help.
    Regards.

    Hi A_Non.
    Thanks a lot, I tried with this:
    SELECT
         t.id,
         x.dat,
         y.seqno,
         y.id_real
    FROM
         xml_test t,
         XMLTABLE
              '/msg/data/fields'
              passing t.xml
              columns
                   dat VARCHAR2(10) path 'dat',
                   id XMLTYPE path 'id'
         )x,
         XMLTABLE
              'id'
              passing x.id
              columns
                   seqno FOR ORDINALITY,
                   id_real VARCHAR2(30) PATH '.'
         )(+) y ;And is giving me the complete output.
    Thanks again.
    Regards.

  • Problem with outer join with filter on join column

    Hi,
    In physical layer I have one dimension and two facts, and there's an outer join between the facts.
    dim_DATE ,
    fact_1 ,
    fact_2
    Joins:
    dim_DATE inner join fact_1 on dim_DATE.DATE = fact_1.DATE
    fact_1 left outer join fact_2 on fact_1.DATE = fact_2.DATE and fact_1.SOME_ID = fact_2.SOME_ID
    When I run a report with a date as a filter, OBIEE executes "optimized" physical SQL:
    select fact1.X, fact2.Y
    from
    Fact_1 left outer join on fact_1.DATE = fact_2.DATE and fact_1.SOME_ID = fact_2.SOME_ID
    where Fact_1.DATE = TO_DATE('2009-05-28' , 'YYYY-MM-DD' )
    and  Fact_2.DATE = TO_DATE('2009-05-28' , 'YYYY-MM-DD')
    The filter on Fact_2.DATE effectively replaces outer join with inner.
    Is there a way to disable this "optimization", which is actually very good for inner joins, but doesn't allow outer joins?
    Thanks in advance,
    Alex
    Edited by: AM_1 on Aug 11, 2009 8:20 AM

    If you want to perform a Fact-based partitioning with OBIEE (two fact with the same dimension), you have to :
    * create in your physical layer for each fact table the joins with the dimension
    * create in the Business Model layer ONE star schema with ONE logical fact table containing the columns of your two physical fact table
    In this way when you choose minimal one column of your fact1 and one column of your fact2, OBIEE will perform two query against each fact table/dimension, join them with an OUTER JOIN and your problem will disappear.
    Cheers
    Nico

  • Problem with JFrame class.

    To risolve my problem i need for few diferent frame
    ( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
    If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
    I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
    Help me.....

    Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.

  • Problem with timestamp in query

    I have problem with timestamp in JPA query.
    I wonna select all data from database where difference between two timestamps is more than 3 month.
    Database:
    ID timestamp1 timestamp2
    1 20008-11-19 15:02000 20008-08-19 15:02000
    2 20008-11-19 15:02000 20008-11-14 15:02000
    @Column(name = "timestamp1", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date timestamp1;
    @Column(name = "timestamp2", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date timestamp2;
    sql query works:
    select id from table where
    MONTH( DATE(timestamp1) - DATE(timestamp2) ) > 3
    but how I can write in Java?
    I't doesnt wrk:
    Query query = em.createQuery("SELECT f.id FROM Foo f WHERE MONTH( DATE(f.timestamp1) - DATE(f.timestamp2) ) > 3 ")
    error:
    ExceptionUtil E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method .
    Exception data: <openjpa-1.0.2-r420667:627158 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter 'SELECT f.id FROM Foo f WHERE MONTH( DATE(f.timestamp1) - DATE(f.timestamp2) ) > 3'.
    Error message: <openjpa-1.0.2-r420667:627158 nonfatal user error> org.apache.openjpa.kernel.jpql.ParseException: Encountered "MONTH (" at character 438, but expected: ["(", "+", "-", ".", ":", "", "=", "?", "ABS", "ALL", "AND", "ANY", "AS", "ASC", "AVG", "BETWEEN", "BOTH", "BY", "CONCAT", "COUNT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DELETE", "DESC", "DISTINCT", "EMPTY", "ESCAPE", "EXISTS", "FETCH", "FROM", "GROUP", "HAVING", "IN", "INNER", "IS", "JOIN", "LEADING", "LEFT", "LENGTH", "LIKE", "LOCATE", "LOWER", "MAX", "MEMBER", "MIN", "MOD", "NEW", "NOT", "NULL", "OBJECT", "OF", "OR", "ORDER", "OUTER", "SELECT", "SET", "SIZE", "SOME", "SQRT", "SUBSTRING", "SUM", "TRAILING", "TRIM", "UPDATE", "UPPER", "WHERE", <BOOLEAN_LITERAL>, <DECIMAL_LITERAL>, <IDENTIFIER>, <INTEGER_LITERAL>, <STRING_LITERAL>].
    at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.parse(JPQLExpressionBuilder.java:1665)
    at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.<init>(JPQLExpressionBuilder.java:1645)

    The error is indocating improper formatting of your JPQL string. MONTH is not understood. I would recommend using your SQL string in a createNativeQuery(...) call instead.
    Doug

  • Problem with 'Word edit cell.vi' , Inputs transduced with the value of every row repeated

    Hello,
    Im using LV2013 with office 2013 report tool kit. I am trying to use Word edit cell to input values in table previously created in template .doc.
    Indeed, i trying the example Generate report from template and didnt works well. I search for solution and I see it was a problem with previous version but it seems not solve totally in this version for word office 2010. 
    http://digital.ni.com/public.nsf/allkb/4041ECB5D02BA57D862579A00002FE8D
    I checked this thread but i didnt get it to works. http://forums.ni.com/t5/LabVIEW/Problem-with-append-table-and-Word-2010/m-p/2190960#M702610
    Any way to solve it?.
    Thanks for help.
    Fred
    Attachments:
    error.png ‏32 KB
    Untitled 1.vi ‏19 KB
    exampleTemplate.doc ‏37 KB

    Hello, I solve it adding this to Word_insert_Table.
    http://forums.ni.com/t5/LabVIEW/Report-Generation-MS-Word-Table-Bug/td-p/1605170
    Thanks.
    Open [LabVIEW installation folder]\vi.lib\addons\_office\_wordsub.llb\Word_Insert_Table.vi
    There is a nested for loop that interprets the provided string array data and reformats it into a long ASCII string for the copy buffer. It should look like this:
    Change the nested loop to look like this:
    The changes I've made are twofold:
    1. Within the inner loop, replace the "\n" char with a Tab character
    2. Just after the inner loop, add a new "concatenate strings" function that adds "\n".

  • Problem with performance in a code.

    Hi People! I have problems with the performance of this program. The tables that I use have much data and the program take two hours to finish.
    Please, some one tell me how can I make a better performance.
    Thanks!
    This is the program:
    TABLES:
            faglflext,         "Saldos mensuales por cta. 
                                contable y prf center.
            zavg_bal_table,
            skat.              "Chart of accounts
    ********************INTERNAL TABLE DEFINITION***************************
    DATA: BEGIN OF t_itab1 OCCURS 0.
    DATA: rbukrs      TYPE faglflext-rbukrs. "Company Code
    DATA: racct       TYPE faglflext-racct. "Account ID
    DATA: prctr       TYPE faglflext-prctr. "Profit Center
    DATA: kslvt       TYPE faglflext-kslvt. "Total of the period in group currency
    DATA: ksl01       TYPE faglflext-ksl01. "Total of the period in group currency
    DATA: ksl02       TYPE faglflext-ksl02. "Total of the period in group currency
    DATA: ksl03       TYPE faglflext-ksl03. "Total of the period in group currency
    DATA: ksl04       TYPE faglflext-ksl04. "Total of the period in group currency
    DATA: ksl05       TYPE faglflext-ksl05. "Total of the period in group currency
    DATA: ksl06       TYPE faglflext-ksl06. "Total of the period in group currency
    DATA: ksl07       TYPE faglflext-ksl07. "Total of the period in group currency
    DATA: ksl08       TYPE faglflext-ksl08. "Total of the period in group currency
    DATA: ksl09       TYPE faglflext-ksl09. "Total of the period in group currency
    DATA: ksl10       TYPE faglflext-ksl10. "Total of the period in group currency
    DATA: ksl11       TYPE faglflext-ksl11. "Total of the period in group currency
    DATA: ksl12       TYPE faglflext-ksl12. "Total of the period in group currency
    DATA: ksl13       TYPE faglflext-ksl13. "Total of the period in group currency
    DATA: ksl14       TYPE faglflext-ksl14. "Total of the period in group currency
    DATA: ksl15       TYPE faglflext-ksl15. "Total of the period in group currency
    DATA: ksl16       TYPE faglflext-ksl16. "Total of the period in group currency
    DATA: rldnr       TYPE faglflext-rldnr. "Ledger in GL Accounting
    DATA: rtcur       TYPE faglflext-rtcur. "Currency Key
    DATA: txt20       TYPE skat-txt20.      "Description Text
    DATA: saknr       TYPE skat-saknr.      "G/L account number
    DATA: ktopl       TYPE skat-ktopl.      "Chart of Accounts
    DATA: rpmax       TYPE faglflext-rpmax. "Period
    DATA: total_sum   LIKE faglflext-ksl01. "Amount of the first month
    DATA: ryear       LIKE faglflext-ryear. "Fiscal Year
    DATA: year        LIKE faglflext-ryear. "Past Year
    DATA: day_a       TYPE sy-datum.
    DATA: per_day     TYPE rr_umper.
    DATA: average     TYPE vtcur12.
    DATA: agregate    TYPE vtcur12.
    DATA: accumulate  TYPE vtcur12.
    DATA: average_sap TYPE rr_umper.
    DATA: END OF t_itab1.
    DATA: BEGIN OF t_itab2 OCCURS 0.
    DATA: rbukrs    TYPE faglflext-rbukrs. "Company Code
    DATA: racct     TYPE faglflext-racct. "Account ID
    DATA: prctr     TYPE faglflext-prctr. "Profit Center
    DATA: kslvt     TYPE faglflext-kslvt. "Total of the period in group currency
    DATA: ksl01     TYPE faglflext-ksl01. "Total of the period in group currency
    DATA: ksl02     TYPE faglflext-ksl02. "Total of the period in group currency
    DATA: ksl03     TYPE faglflext-ksl03. "Total of the period in group currency
    DATA: ksl04     TYPE faglflext-ksl04. "Total of the period in group currency
    DATA: ksl05     TYPE faglflext-ksl05. "Total of the period in group currency
    DATA: ksl06     TYPE faglflext-ksl06. "Total of the period in group currency
    DATA: ksl07     TYPE faglflext-ksl07. "Total of the period in group currency
    DATA: ksl08     TYPE faglflext-ksl08. "Total of the period in group currency
    DATA: ksl09     TYPE faglflext-ksl09. "Total of the period in group currency
    DATA: ksl10     TYPE faglflext-ksl10. "Total of the period in group currency
    DATA: ksl11     TYPE faglflext-ksl11. "Total of the period in group currency
    DATA: ksl12     TYPE faglflext-ksl12. "Total of the period in group currency
    DATA: ksl13     TYPE faglflext-ksl13. "Total of the period in group currency
    DATA: ksl14     TYPE faglflext-ksl14. "Total of the period in group currency
    DATA: ksl15     TYPE faglflext-ksl15. "Total of the period in group currency
    DATA: ksl16     TYPE faglflext-ksl16. "Total of the period in group currency
    DATA: rldnr     TYPE faglflext-rldnr. "Ledger in GL Accounting
    DATA: rtcur     TYPE faglflext-rtcur. "Currency Key
    DATA: txt20     TYPE skat-txt20.      "Description Text
    DATA: saknr     TYPE skat-saknr.      "G/L account number
    DATA: ktopl     TYPE skat-ktopl.      "Chart of Accounts
    DATA: rpmax     TYPE faglflext-rpmax. "Period
    DATA: total_sum LIKE faglflext-ksl01. "Amount of the first month
    DATA: ryear     LIKE faglflext-ryear. "Fiscal Year
    DATA: year      LIKE faglflext-ryear. "Past Year
    DATA: END OF t_itab2.
    DATA: BEGIN OF t_zavg OCCURS 0.
    DATA: bukrs       TYPE bukrs.
    DATA: racct       TYPE racct.
    DATA: prctr       TYPE prctr.
    DATA: day_a       TYPE sy-datum.
    DATA: per_day     TYPE rr_umper.
    DATA: average     TYPE vtcur12.
    DATA: agregate    TYPE vtcur12.
    DATA: accumulate  TYPE vtcur12.
    DATA: average_sap TYPE rr_umper.
    DATA: END OF t_zavg.
    DATA: BEGIN OF t_zavg2 OCCURS 0.
    DATA: day_a       TYPE sy-datum.
    DATA: racct       TYPE racct.
    DATA: prctr       TYPE prctr.
    DATA: per_day     TYPE rr_umper.
    DATA: average     TYPE vtcur12.
    DATA: agregate    TYPE vtcur12.
    DATA: accumulate  TYPE vtcur12.
    DATA: average_sap TYPE rr_umper.
    DATA: END OF t_zavg2.
    *                      Variable definition                             *
    DATA: balance_month_01          LIKE faglflext-ksl01.
    DATA: balance_month_02          LIKE faglflext-ksl01.
    DATA: balance_month_03          LIKE faglflext-ksl01.
    DATA: balance_month_04          LIKE faglflext-ksl01.
    DATA: balance_month_05          LIKE faglflext-ksl01.
    DATA: balance_month_06          LIKE faglflext-ksl01.
    DATA: balance_month_07          LIKE faglflext-ksl01.
    DATA: balance_month_08          LIKE faglflext-ksl01.
    DATA: balance_month_09          LIKE faglflext-ksl01.
    DATA: balance_month_10          LIKE faglflext-ksl01.
    DATA: balance_month_11          LIKE faglflext-ksl01.
    DATA: balance_month_12          LIKE faglflext-ksl01.
    DATA: balance_month_13          LIKE faglflext-ksl01.
    DATA: current_average_balance   LIKE zavg_bal_table-average.
    DATA: current_balance           LIKE faglflext-ksl01.
    DATA: current_activity_balance  LIKE faglflext-ksl01.
    DATA: current_aggregate_balance LIKE zavg_bal_table-agregate.
    DATA: average_balance_ytd       LIKE zfintbco0001-period_avg_12.
    DATA: count                     TYPE i.
    DATA: wa_itab                   LIKE LINE OF t_itab1.
    DATA: wa_low                    LIKE LINE OF t_itab1.
    DATA: wa_high                   LIKE LINE OF t_itab1.
    DATA: wa_itab2                  LIKE LINE OF t_itab2.
    DATA: wa_zavg2                  LIKE LINE OF t_zavg2.
    DATA: wa_zavg                   LIKE LINE OF t_zavg.
    DATA: t_acum                    TYPE i.
    DATA: companycode               TYPE faglflext-rbukrs.
    DATA: descripcion               TYPE skat-txt20.
    DATA: oref                      TYPE REF TO cx_root,
          emsg                      TYPE zedesc,
          param1                    TYPE zparm,
          parm1                     TYPE zparm.
    DATA: avg1                      TYPE faglflext-ksl01.  "AVG = AVERAGE
    DATA: avg2                      TYPE faglflext-ksl01.
    DATA: avg3                      TYPE faglflext-ksl01.
    DATA: avg4                      TYPE faglflext-ksl01.
    DATA: avg5                      TYPE faglflext-ksl01.
    DATA: avg6                      TYPE faglflext-ksl01.
    DATA: avg7                      TYPE faglflext-ksl01.
    DATA: avg8                      TYPE faglflext-ksl01.
    DATA: avg9                      TYPE faglflext-ksl01.
    DATA: avg10                     TYPE faglflext-ksl01.
    DATA: avg11                     TYPE faglflext-ksl01.
    DATA: avg12                     TYPE faglflext-ksl01.
    DATA: conteo                    TYPE i.
    DATA: conteo2                   TYPE i.
    DATA: numerocta                 TYPE faglflext-racct.
    DATA: profitcenter              TYPE faglflext-prctr.
    DATA: average_month_01          TYPE zavg_bal_table-average.
    DATA: aggregate_month_01        TYPE zavg_bal_table-agregate.
    DATA: average_month_02          TYPE zavg_bal_table-average.
    DATA: aggregate_month_02        TYPE zavg_bal_table-agregate.
    DATA: average_month_03          TYPE zavg_bal_table-average.
    DATA: aggregate_month_03        TYPE zavg_bal_table-agregate.
    DATA: average_month_04          TYPE zavg_bal_table-average.
    DATA: aggregate_month_04        TYPE zavg_bal_table-agregate.
    DATA: average_month_05          TYPE zavg_bal_table-average.
    DATA: aggregate_month_05        TYPE zavg_bal_table-agregate.
    DATA: average_month_06          TYPE zavg_bal_table-average.
    DATA: aggregate_month_06        TYPE zavg_bal_table-agregate.
    DATA: average_month_07          TYPE zavg_bal_table-average.
    DATA: aggregate_month_07        TYPE zavg_bal_table-agregate.
    DATA: average_month_08          TYPE zavg_bal_table-average.
    DATA: aggregate_month_08        TYPE zavg_bal_table-agregate.
    DATA: average_month_09          TYPE zavg_bal_table-average.
    DATA: aggregate_month_09        TYPE zavg_bal_table-agregate.
    DATA: average_month_10          TYPE zavg_bal_table-average.
    DATA: aggregate_month_10        TYPE zavg_bal_table-agregate.
    DATA: average_month_11          TYPE zavg_bal_table-average.
    DATA: aggregate_month_11        TYPE zavg_bal_table-agregate.
    DATA: average_month_12          TYPE zavg_bal_table-average.
    DATA: aggregate_month_12        TYPE zavg_bal_table-agregate.
    DATA: ano                       TYPE i.
    DATA: ano_pasado                TYPE i.
    DATA: ano_corriente             TYPE i.
    DATA: mesdia                    TYPE adb_pfrom.
    DATA: firstline                 TYPE i.
    DATA: kslvt                     TYPE faglflext-kslvt.
    DATA: ksl01                     TYPE faglflext-ksl01.
    DATA: ksl02                     TYPE faglflext-ksl02.
    DATA: ksl03                     TYPE faglflext-ksl03.
    DATA: ksl04                     TYPE faglflext-ksl04.
    DATA: ksl05                     TYPE faglflext-ksl05.
    DATA: ksl06                     TYPE faglflext-ksl06.
    DATA: ksl07                     TYPE faglflext-ksl07.
    DATA: ksl08                     TYPE faglflext-ksl08.
    DATA: ksl09                     TYPE faglflext-ksl09.
    DATA: ksl10                     TYPE faglflext-ksl10.
    DATA: ksl11                     TYPE faglflext-ksl11.
    DATA: ksl12                     TYPE faglflext-ksl12.
    DATA: ksl13                     TYPE faglflext-ksl13.
    DATA: ksl14                     TYPE faglflext-ksl14.
    DATA: ksl15                     TYPE faglflext-ksl15.
    DATA: ksl16                     TYPE faglflext-ksl16.
    DATA: itab_kslvt                TYPE faglflext-kslvt.
    DATA: itab_ksl01                TYPE faglflext-ksl01.
    DATA: itab_ksl02                TYPE faglflext-ksl02.
    DATA: itab_ksl03                TYPE faglflext-ksl03.
    DATA: itab_ksl04                TYPE faglflext-ksl04.
    DATA: itab_ksl05                TYPE faglflext-ksl05.
    DATA: itab_ksl06                TYPE faglflext-ksl06.
    DATA: itab_ksl07                TYPE faglflext-ksl07.
    DATA: itab_ksl08                TYPE faglflext-ksl08.
    DATA: itab_ksl09                TYPE faglflext-ksl09.
    DATA: itab_ksl10                TYPE faglflext-ksl10.
    DATA: itab_ksl11                TYPE faglflext-ksl11.
    DATA: itab_ksl12                TYPE faglflext-ksl12.
    DATA: itab_ksl13                TYPE faglflext-ksl13.
    DATA: itab_ksl14                TYPE faglflext-ksl14.
    DATA: itab_ksl15                TYPE faglflext-ksl15.
    DATA: itab_ksl16                TYPE faglflext-ksl16.
    DATA: itab_bal00                TYPE faglflext-kslvt.
    DATA: itab_bal01                TYPE faglflext-ksl01.
    DATA: itab_bal02                TYPE faglflext-ksl02.
    DATA: itab_bal03                TYPE faglflext-ksl03.
    DATA: itab_bal04                TYPE faglflext-ksl04.
    DATA: itab_bal05                TYPE faglflext-ksl05.
    DATA: itab_bal06                TYPE faglflext-ksl06.
    DATA: itab_bal07                TYPE faglflext-ksl07.
    DATA: itab_bal08                TYPE faglflext-ksl08.
    DATA: itab_bal09                TYPE faglflext-ksl09.
    DATA: itab_bal10                TYPE faglflext-ksl10.
    DATA: itab_bal11                TYPE faglflext-ksl11.
    DATA: itab_bal12                TYPE faglflext-ksl12.
    DATA: itab_bal13                TYPE faglflext-ksl13.
    DATA: itab_bal14                TYPE faglflext-ksl14.
    DATA: itab_bal15                TYPE faglflext-ksl15.
    DATA: itab_bal16                TYPE faglflext-ksl16.
    DATA: numero_de_cta             TYPE  faglflext-racct.
    DATA: company_code              TYPE  faglflext-rbukrs.
    DATA: profit_center             TYPE  faglflext-prctr.
    DATA: currency_code             TYPE  faglflext-rtcur.
    DATA: average_month             TYPE  zavg_bal_table-average.
    DATA: aggregate_month           TYPE  zavg_bal_table-agregate.
    * VARIABLES FOR INTERFACES LOG
    DATA: v_tipo                    TYPE zzfinbc85typede VALUE 1. "Tipo 1 = OUT
    DATA: v_nom_int(9)              TYPE c VALUE 'ZFINFII00'. "Nombre de la interfaz
    DATA: v_modulo(2)               TYPE c VALUE 'FI'. "Modulo
    DATA: v_comp_code(4)            TYPE c VALUE '0000'. "Compañia 0000
    DATA: v_alegacy(4)              TYPE c VALUE '0001'.
    DATA: v_fecha                   TYPE d.
    DATA: v_error2(3)               TYPE c VALUE 'E'.
    DATA: l_sys_exc                 TYPE REF TO  cx_ai_system_fault.
    DATA: last_day                  TYPE sy-datum.
    DATA: numero_mes                TYPE i.
    DATA: ryear                     TYPE faglflext-ryear.
    DATA: numero_cuenta             TYPE faglflext-racct.
    DATA: numero_profit             TYPE faglflext-prctr.
    DATA: day_a                     TYPE i.
    DATA: text(20)                  TYPE c.
    *Acknowledge
    DATA: lo_async_messaging        TYPE REF TO if_wsprotocol_async_messaging,
    lo_msg_id_protocol              TYPE REF TO if_wsprotocol_message_id,
    l_msg_id                        TYPE sxmsguid,
    l_ack_request                   TYPE prx_ack_request_details.
    DATA: fecha                     TYPE sy-datum.
    DATA: fecha_ejecutandose        TYPE sy-datum.
    DATA: fecha_corriente           TYPE i.
    DATA: jan_fin                   TYPE sy-datum.
    DATA: feb_fin                   TYPE sy-datum.
    DATA: febb_fin                  TYPE sy-datum.
    DATA: mar_fin                   TYPE sy-datum.
    DATA: apr_fin                   TYPE sy-datum.
    DATA: may_fin                   TYPE sy-datum.
    DATA: jun_fin                   TYPE sy-datum.
    DATA: jul_fin                   TYPE sy-datum.
    DATA: aug_fin                   TYPE sy-datum.
    DATA: sep_fin                   TYPE sy-datum.
    DATA: oct_fin                   TYPE sy-datum.
    DATA: nov_fin                   TYPE sy-datum.
    DATA: dec_fin                   TYPE sy-datum.
    DATA: porciento1                TYPE faglflext-ksl01.
    DATA: porciento2                TYPE faglflext-ksl01.
    DATA: porciento3                TYPE faglflext-ksl01.
    DATA: porciento4                TYPE faglflext-ksl01.
    DATA: porciento5                TYPE faglflext-ksl01.
    DATA: porciento6                TYPE faglflext-ksl01.
    DATA: porciento7                TYPE faglflext-ksl01.
    DATA: porciento8                TYPE faglflext-ksl01.
    DATA: porciento9                TYPE faglflext-ksl01.
    DATA: porciento10               TYPE faglflext-ksl01.
    DATA: porciento11               TYPE faglflext-ksl01.
    DATA: porciento12               TYPE faglflext-ksl01.
    data: mes(2)                    type c value '00'.
    data: mes_anterior              type sy-datum.
    data: ceros(2)                  type c.
    *DEFINICION DE RANGOS.
    RANGES profit FOR faglflext-prctr.
    RANGES account FOR faglflext-racct.
    RANGES end_month FOR zavg_bal_table-day_a.
    *Sele asigna el fin de mes a cada variable para que sea utilizada luego en el programa.
    jan_fin = '20060131'.
    feb_fin = '20060228'.
    febb_fin = '20060229'.
    mar_fin = '20060331'.
    apr_fin = '20060430'.
    may_fin = '20060531'.
    jun_fin = '20060630'.
    jul_fin = '20060731'.
    aug_fin = '20060831'.
    sep_fin = '20060930'.
    oct_fin = '20061031'.
    nov_fin = '20061130'.
    dec_fin = '20061231'.
    *Inicializando las variables a valor '0'.
    balance_month_01          = 0.
    balance_month_02          = 0.
    balance_month_03          = 0.
    balance_month_04          = 0.
    balance_month_05          = 0.
    balance_month_06          = 0.
    balance_month_07          = 0.
    balance_month_08          = 0.
    balance_month_09          = 0.
    balance_month_10          = 0.
    balance_month_11          = 0.
    balance_month_12          = 0.
    balance_month_13          = 0.
    current_average_balance   = 0.
    current_balance           = 0.
    current_activity_balance  = 0.
    current_aggregate_balance = 0.
    average_balance_ytd       = 0.
    count                     = 0.
    t_acum                    = 0.
    conteo                    = 1.
    conteo2                   = 1.
    ceros                     = '00'.
    *THIS IS A STRUCTURE NAMED E_SKAT. WITH THE TWO FIELDS NAMED SAKNR     *
    *AND TXT20.                                                            *
    TYPES: BEGIN OF e_skat,
             ktopl LIKE skat-ktopl,
             saknr LIKE skat-saknr,
             txt20 LIKE skat-txt20,
           END OF e_skat.
    *         SORT THE STRUCTURE IN ORDER FOR BEST PERFORMANCE             *
    DATA it_skat TYPE SORTED TABLE OF e_skat
         WITH UNIQUE KEY saknr WITH HEADER LINE.
    DATA: wa_skat                  LIKE LINE OF it_skat.
    *           CONSTANT DEFINITIONS (HAVE THE SAME VALUE EVER)            *
    CONSTANTS:
          etype                     TYPE zetype  VALUE 'INTER',       "Utilizada con la funcion de error
          innum                     TYPE zintnum VALUE 'ZFINFII00',       "Utilizada con la funcion de error
          inname                    TYPE zinname VALUE 'Sendero and Cognos Interfase', "Utilizada con la funcion de error
          c_cuenta(10)              TYPE c VALUE '0000270011',
          c_ol(2)                   TYPE c VALUE '0L',
          c_chart(4)                TYPE c VALUE 'CAPI',              "Chart Of Accounts
          c_ceros(17)               TYPE n VALUE '00000000000000.00', "ceros
          acct_cog(10)              TYPE n VALUE '0000270011',        "Numero de cta. que se busca en COGNOS.
          capi(4)                   TYPE c VALUE 'CAPI'.
    *                PARAMETROS de entrada para el usuario.                *
    SELECTION-SCREEN BEGIN OF BLOCK bl1 WITH FRAME TITLE text-001.
    PARAMETERS:
               p_date   TYPE sy-datum DEFAULT sy-datum.       "Fecha de corrida
    IF p_date IS INITIAL.
      p_date = sy-datum.
    ENDIF.
    *     PARAMETEROS DE ENTRADA POR MEDIO DE RANGOS PARA EL USUARIO       *
    SELECT-OPTIONS:
                p_bukrs FOR faglflext-rbukrs.
    SELECTION-SCREEN END OF BLOCK bl1.
    *IF THE USER SELECT THIS CHECK BOX WITH A CHECK MARK THE PROGRAM       *
    *SUBMIT THIS INTERFACE TO.                                             *
    SELECTION-SCREEN BEGIN OF BLOCK bl2 WITH FRAME TITLE text-002.
    PARAMETERS:
              p_cognos    TYPE c AS CHECKBOX.
    SELECTION-SCREEN END OF BLOCK bl2.
    * This statement calls the subroutine specified, SENDERO or COGNOS     *
    IF p_cognos IS INITIAL.
      PERFORM sendero.
    ELSE.
      PERFORM cognos.
    ENDIF.
    EXIT.
    *                      SENEDERO INTERFACE                              *
    FORM sendero.
    *ESTE SELECT EXTRAE LA DATA DE LA TABLA FAGFLEXT Y SKAT
      DATA: msgdetails     TYPE zgl_sendero_file_dt_tab.
      DATA: wa_msgdetails  LIKE LINE OF msgdetails.
      SELECT a~ryear a~rpmax a~rtcur a~racct a~rbukrs a~prctr
             a~kslvt a~ksl01 a~ksl02 a~ksl03 a~ksl04 a~ksl05
             a~ksl06 a~ksl07 a~ksl08 a~ksl09 a~ksl10 a~ksl11
             a~ksl12 a~ksl13 a~ksl14 a~ksl15 a~ksl16 b~saknr
             b~txt20 b~ktopl
            FROM  faglflext AS a INNER JOIN skat AS b ON a~racct = b~saknr AND a~rclnt = b~mandt
            CLIENT SPECIFIED INTO CORRESPONDING FIELDS OF TABLE t_itab1
        WHERE  a~rclnt = sy-mandt
          AND  a~rbukrs IN p_bukrs
          AND  a~rldnr  = '0L'
          AND  a~ryear  = p_date+0(4)
          AND  b~spras  EQ sy-langu
          AND  b~ktopl  EQ 'CAPI'.
    *SI NO ENCUENTRA DATA EN LA TABLA FAGLFLEXT ENVIA EL MENSAJE DE ERROR
    *A LA TABLA DE ERROR.
      IF sy-subrc <> 0.
        MOVE 'No data found in FLAGLFLEXT or ZAVG_BAL_TABLE for this process.'(e01) TO emsg.
    *    PERFORM call_error_function USING emsg.
    *    PERFORM call_log_function_send.
        MESSAGE: emsg TYPE 'E'.
      ENDIF.
    *EN ESTE SELECT SACO LA DESCRIPCION DE LA CUENTA
      SORT t_itab1 BY racct ASCENDING.
      DELETE t_itab1 WHERE racct = ''.
      SORT t_itab1 BY prctr ASCENDING.
      CLEAR t_itab1.
      READ TABLE t_itab1 INTO wa_low  INDEX 1 .
      DESCRIBE TABLE t_itab1 LINES firstline.
      READ TABLE t_itab1 INTO wa_high INDEX firstline.
      IF wa_high-prctr = 'DUMMY'.                      "SI EL ULTIMO RECORD CONTIENE ALGUN 'DUMMY' ESCOJER EL RECORD DE ARRIBA.
        firstline = firstline - 1.                     "CONTIENE EL NUMERO DEL INDICE.
        READ TABLE t_itab1 INTO wa_high INDEX firstline.
      ENDIF.
      profit-sign    = 'I'.
      profit-option  = 'BT'.
      profit-low     = wa_low-prctr.
      profit-high    = wa_high-prctr.
      APPEND profit.
    *COMPUTOS PARA CALCULAR EL ULTIMO DIA DEL MES.
      fecha       = p_date.
      numero_mes = p_date+4(2).                       "PASO NUMERO DEL MES A VARIABLE.
      p_date+4(2) = p_date+4(2) - numero_mes.         "LE RESTO EL MISMO MES A LA FECHA PARA COMENZAR EL CONTEO DESDE EL MES 1.
      DO numero_mes TIMES.                           "SE VA A EJECUTAR LAS MISMAS VECES DEL NUMERO DEL MES.
        p_date+4(2) = p_date+4(2) + 1.                  "SE INCREMENTA EL NUMERO DEL MES.
        CALL FUNCTION 'SG_PS_GET_LAST_DAY_OF_MONTH'    "Obtiene el ultimo numero del mes.
          EXPORTING
            day_in            = p_date
          IMPORTING
            last_day_of_month = last_day
          EXCEPTIONS
            day_in_not_valid  = 1
            OTHERS            = 2.
        IF sy-subrc <> 0.
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
        ENDIF.
        IF fecha = p_date.
          fecha = fecha - 1.   "le resta a fecha -1 para que busque en la tabla zavg_bal_table el record del dia anterior.
          end_month-sign    = 'I'.
          end_month-option  = 'EQ'.
          end_month-low     = fecha.
          APPEND end_month.
        ELSE.
          end_month-sign    = 'I'.
          end_month-option  = 'EQ'.
          end_month-low     = last_day.
          APPEND end_month.
        ENDIF.
      ENDDO.
      SORT end_month BY low ASCENDING.
      SELECT bukrs racct prctr day_a per_day average agregate accumulate average_sap
        FROM zavg_bal_table CLIENT SPECIFIED APPENDING TABLE t_zavg
        WHERE mandt = sy-mandt
          AND bukrs IN p_bukrs
          AND  day_a <= sy-datum
          AND  prctr IN profit.
      SORT t_itab1 BY rbukrs racct prctr.
      SORT t_zavg  BY  bukrs racct prctr day_a.
    *IMPRESION Y ENVIO DE LOS DATOS REQUERIDOS
    *Estos If verifican el mes que se esta ejecutando por el usuario para cambiarselo a la variable que identifica el fin de mes.
      IF p_date+4(2) = jan_fin+4(2).
        jan_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = feb_fin+4(2).
        feb_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = mar_fin+4(2).
        mar_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = apr_fin+4(2).
        apr_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = may_fin+4(2).
        may_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = jun_fin+4(2).
        jun_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = jul_fin+4(2).
        jul_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = aug_fin+4(2).
        aug_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = sep_fin+4(2).
        sep_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = oct_fin+4(2).
        oct_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = nov_fin+4(2).
        nov_fin+6(2) = p_date+6(2).
      ENDIF.
      IF p_date+4(2) = dec_fin+4(2).
        dec_fin+6(2) = p_date+6(2).
      ENDIF.
    *Comienza primer loop en el programa a t_itab1 que es la tabla interna que contiene los datos de faglflext.
      LOOP AT t_itab1 INTO wa_itab WHERE racct  NE ''.
        AT NEW prctr.  "Limpia las variables que se muestran en el clear cada ves que comienza un nuevo profit center.
          CLEAR: itab_kslvt, itab_ksl01, itab_ksl02, itab_ksl03, itab_ksl04, itab_ksl05, itab_ksl06, itab_ksl07, itab_ksl08,
                 itab_ksl09, itab_ksl10, itab_ksl11, itab_ksl12, itab_ksl13, itab_ksl14, itab_ksl15, itab_ksl16,
                 itab_bal00, itab_bal01, itab_bal02, itab_bal03, itab_bal04, itab_bal05, itab_bal06, itab_bal07,
                 itab_bal08, itab_bal09, itab_bal10, itab_bal11, itab_bal12, itab_bal13, itab_bal14, itab_bal15,
                 itab_bal16.
        ENDAT.
    *Se le pasa a la variable itab_ksl## el valor del mes que contenga flext.
        itab_kslvt = itab_kslvt + wa_itab-kslvt. itab_ksl01 = itab_ksl01 + wa_itab-ksl01. itab_ksl02 = itab_ksl02 + wa_itab-ksl02.
        itab_ksl03 = itab_ksl03 + wa_itab-ksl03. itab_ksl04 = itab_ksl04 + wa_itab-ksl04.
        itab_ksl05 = itab_ksl05 + wa_itab-ksl05. itab_ksl06 = itab_ksl06 + wa_itab-ksl06.
        itab_ksl07 = itab_ksl07 + wa_itab-ksl07. itab_ksl08 = itab_ksl08 + wa_itab-ksl08.
        itab_ksl09 = itab_ksl09 + wa_itab-ksl09. itab_ksl10 = itab_ksl10 + wa_itab-ksl10.
        itab_ksl11 = itab_ksl11 + wa_itab-ksl11. itab_ksl12 = itab_ksl12 + wa_itab-ksl12.
        itab_ksl13 = itab_ksl13 + wa_itab-ksl13. itab_ksl14 = itab_ksl14 + wa_itab-ksl14.
        itab_ksl15 = itab_ksl15 + wa_itab-ksl15. itab_ksl16 = itab_ksl16 + wa_itab-ksl16.
    *En estas variables va acumulando el valor por mes. Osea, va sumando todo lo que tenga de ese mes por profit center. Al venir un profit
    *nuevo esta se limpia.
        itab_bal00 = itab_bal00 + wa_itab-kslvt. itab_bal01 = itab_bal01 + wa_itab-ksl01. itab_bal02 = itab_bal02 + wa_itab-ksl02.
        itab_bal03 = itab_bal03 + wa_itab-ksl03. itab_bal04 = itab_bal04 + wa_itab-ksl04.
        itab_bal05 = itab_bal05 + wa_itab-ksl05. itab_bal06 = itab_bal06 + wa_itab-ksl06.
        itab_bal07 = itab_bal07 + wa_itab-ksl07. itab_bal08 = itab_bal08 + wa_itab-ksl08.
        itab_bal09 = itab_bal09 + wa_itab-ksl09. itab_bal10 = itab_bal10 + wa_itab-ksl10.
        itab_bal11 = itab_bal11 + wa_itab-ksl11. itab_bal12 = itab_bal12 + wa_itab-ksl12.
        itab_bal13 = itab_bal13 + wa_itab-ksl13. itab_bal14 = itab_bal14 + wa_itab-ksl14.
        itab_bal15 = itab_bal15 + wa_itab-ksl15. itab_bal16 = itab_bal16 + wa_itab-ksl16.
        ryear = wa_itab-ryear.
        CLEAR t_zavg.
        sy-subrc = 0.
        numero_de_cta   = wa_itab-racct.
        company_code    = wa_itab-rbukrs.
        profit_center   = wa_itab-prctr.
        currency_code   = wa_itab-rtcur.
        descripcion     = wa_itab-txt20.
    *Segundo loop a realizarce. Este utiliza la tabla interna: t_zavg la cual contiene los datos extraidos de zavg_bal_table.
        LOOP AT t_zavg INTO wa_zavg WHERE bukrs = wa_itab-rbukrs AND racct = wa_itab-racct AND prctr = wa_itab-prctr.
          AT NEW prctr.  "Al cambiar el profit center limpia las variables que se encuentran en el clear.
            CLEAR: average_month_01, average_month_02, average_month_03, average_month_04, average_month_05,
             average_month_06, average_month_07, average_month_08, average_month_09, average_month_10, average_month_11,
             average_month_12, average_month.
          ENDAT.
    *Dependiendo del mes que contiene el record de la tabla t_zavg este va acumulando el average_month.
          IF wa_zavg-day_a+4(2) = '01'.
            average_month_01   = average_month_01 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '02'.
            average_month_02   = average_month_02 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '03'.
            average_month_03   = average_month_03 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '04'.
            average_month_04   = average_month_04 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '05'.
            average_month_05   = average_month_05 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '06'.
            average_month_06   = average_month_06 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '07'.
            average_month_07   = average_month_07 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '08'.
            average_month_08   = average_month_08 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '09'.
            average_month_09   = average_month_09 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '10'.
            average_month_10   = average_month_10 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '11'.
            average_month_11   = average_month_11 + wa_zavg-accumulate.
          ENDIF.
          IF wa_zavg-day_a+4(2) = '12'.
            average_month_12   = average_month_12 + wa_zavg-accumulate.
          ENDIF.
    *Este if verifica que cuando el record que se esta verificando sea con fecha de fin de mes calcule el resto del codigo que se encuentra debajo.
          IF wa_zavg-day_a = jan_fin OR wa_zavg-day_a = feb_fin OR wa_zavg-day_a = mar_fin OR wa_zavg-day_a = apr_fin OR wa_zavg-day_a = may_fin OR wa_zavg-day_a = jun_fin OR
          wa_zavg-day_a = jul_fin OR wa_zavg-day_a = aug_fin OR wa_zavg-day_a = sep_fin OR wa_zavg-day_a = oct_fin OR
          wa_zavg-day_a = nov_fin OR wa_zavg-day_a = dec_fin.
            aggregate_month =  wa_zavg-agregate.
            day_a  = wa_zavg-day_a.
    *Calcula el aggregate_month dependiendo de la fecha del record que se esta procesando.
            IF wa_zavg-day_a+4(2) = '01'.
              aggregate_month_01 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '02'.
              aggregate_month_02 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '03'.
              aggregate_month_03 = wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '04'.
              aggregate_month_04 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '05'.
              aggregate_month_05 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '06'.
              aggregate_month_06 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '07'.
              aggregate_month_07 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '08'.
              aggregate_month_08 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '09'.
              aggregate_month_09 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '10'.
              aggregate_month_10 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '11'.
              aggregate_month_11 =  wa_zavg-agregate.
            ENDIF.
            IF wa_zavg-day_a+4(2) = '12'.
              aggregate_month_12 =  wa_zavg-agregate.
            ENDIF.
          ENDIF.
    *Este if verifica que cuando el record que se esta verificando sea con fecha de fin de mes calcule el resto del codigo que se encuentra debajo.
          IF wa_zavg-day_a+4(4) = jan_fin+4(4) OR wa_zavg-day_a+4(4) = feb_fin+4(4) OR wa_zavg-day_a+4(4) = febb_fin+4(4) OR wa_zavg-day_a+4(4) = mar_fin+4(4) OR
             wa_zavg-day_a+4(4) = apr_fin+4(4) OR wa_zavg-day_a+4(4) = may_fin+4(4) OR wa_zavg-day_a+4(4) = jun_fin+4(4) OR wa_zavg-day_a+4(4) = jul_fin+4(4) OR
             wa_zavg-day_a+4(4) = aug_fin+4(4) OR wa_zavg-day_a+4(4) = sep_fin+4(4) OR wa_zavg-day_a+4(4) = oct_fin+4(4) OR wa_zavg-day_a+4(4) = nov_fin+4(4) OR
             wa_zavg-day_a+4(4) = dec_fin+4(4).
    *Calcula la division entre la cantidad acumulada por mes y la fecha del fin de mes.
            IF average_month_01 IS NOT INITIAL.
              porciento1 = average_month_01 / jan_fin+6(2).
              average_month   = porciento1.
            ENDIF.
            IF average_month_02 IS NOT INITIAL.
              porciento2 = average_month_02 / feb_fin+6(2).
              average_month   = porciento2.
            ENDIF.
            IF average_month_03 IS NOT INITIAL.
              porciento3 = average_month_03 / mar_fin+6(2).
              average_month   = porciento3.
            ENDIF.
            IF average_month_04 IS NOT INITIAL.
              porciento4 = average_month_04 / apr_fin+6(2).
              average_month   = porciento4.
            ENDIF.
            IF average_month_05 IS NOT INITIAL.
              porciento5 = average_month_05 / may_fin+6(2).
              average_month   = porciento5.
            ENDIF.
            IF average_month_06 IS NOT INITIAL.
              porciento6 = average_month_06 / jun_fin+6(2).
              average_month   = porciento6.
            ENDIF.
            IF average_month_07 IS NOT INITIAL.
              porciento7 = average_month_07 / jul_fin+6(2).
              average_month   = porciento7.
            ENDIF.
            IF average_month_08 IS NOT INITIAL.
              porciento8 = average_month_08 / aug_fin+6(2).
              average_month   = porciento8.
            ENDIF.
            IF average_month_09 IS NOT INITIAL.
              porciento9 = average_month_09 / sep_fin+6(2).
              average_month   = porciento9.
            ENDIF.
            IF average_month_10 IS NOT INITIAL.
              porciento10 = average_month_10 / oct_fin+6(2).
              average_month   = porciento10.
            ENDIF.
            IF average_month_11 IS NOT INITIAL.
              porciento11 = average_month_11 / nov_fin+6(2).
              average_month   = porciento11.
            ENDIF.
            IF average_month_12 IS NOT INITIAL.
              porciento12 = average_month_12 / dec_fin+6(2).
              average_month   = porciento12.
            ENDIF.
    *Cuando la fecha que esta entrando el usuario es la misma a la del record que se esta procesando en ese momento ejecuta el siguiente IF.
            IF p_date+4(4) = wa_zavg-day_a+4(4).
              current_average_balance   =  average_month.
              current_aggregate_balance =  aggregate_month.
              average_balance_ytd       =  average_month.
            ENDIF.
          ENDIF.
        ENDLOOP.
        AT END OF prctr.
          IF sy-subrc = 0.
    *ESTAS VARIABLES SE ESTAN PASANDO A UNA VARIABLE NORMAL YA QUE SI SE DEJAN DENTRO DEL WORK AREA (WA) LE PONE ASTERISCOS.
    *LOS IF QUE SE DEMUESTRAN ABAJO SON PARECIDOS A LOS UTILIZADOS EN LA   *
    *PARTE POSTERIOR LO UNICO QUE LA FECHA UTILIZADA NO ES EXTRAIDA DE LA  *
    *TABLA, ES LA QUE EL USUARIO INSERTA DENTRO DEL PARAMETRO.             *
            IF p_date+4(2) >= '01'.
              COMPUTE: balance_month_01 =   itab_bal00 + itab_bal01.
            ENDIF.
            IF p_date+4(2) >= '02'.
              COMPUTE: balance_month_02 = itab_bal00 + itab_bal01 + itab_bal02.
            ENDIF.
            IF p_date+4(2) >= '03'.
              COMPUTE: balance_month_03 = itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03.
            ENDIF.
            IF p_date+4(2) >= '04'.
              COMPUTE: balance_month_04 = itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04.
            ENDIF.
            IF p_date+4(2) >= '05'.
              COMPUTE: balance_month_05 = itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05.
            ENDIF.
            IF p_date+4(2) >= '06'.
              COMPUTE: balance_month_06 =  itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06.
            ENDIF.
            IF p_date+4(2) >= '07'.
              COMPUTE: balance_month_07 =  itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07.
            ENDIF.
            IF p_date+4(2) >= '08'.
              COMPUTE: balance_month_08 =  itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08.
            ENDIF.
            IF p_date+4(2) >= '09'.
              COMPUTE: balance_month_09 =  itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08 + itab_bal09.
            ENDIF.
            IF p_date+4(2) >= '10'.
              COMPUTE: balance_month_10 =  itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08 + itab_bal09 + itab_bal10.
            ENDIF.
            IF p_date+4(2) >= '11'.
              COMPUTE: balance_month_11 = itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08 + itab_bal09 + itab_bal10 + itab_bal11.
            ENDIF.
            IF p_date+4(2) >= '12'.
              COMPUTE: balance_month_12 =  itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08 + itab_bal09 + itab_bal10 + itab_bal11 + itab_bal12.
            ENDIF.
            IF p_date+4(2) >= '13'.
              COMPUTE: balance_month_13 = itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08 + itab_bal09 + itab_bal10 + itab_bal11 + itab_bal12 + itab_bal13.
            ENDIF.
          COMPUTE: current_balance =  + itab_bal00 + itab_bal01 + itab_bal02 + itab_bal03 + itab_bal04 + itab_bal05 + itab_bal06 + itab_bal07 + itab_bal08 + itab_bal09 + itab_bal10 + itab_bal11 + itab_bal12 + itab_bal13 + itab_bal14 + itab_bal15 + itab_bal16.
    *Computo para el activity balance.
            IF p_date+4(2) = '01'.
              current_activity_balance =   itab_ksl01.
            ENDIF.
            IF p_date+4(2) = '02'.
              current_activity_balance =   itab_ksl02.
            ENDIF.
            IF p_date+4(2) = '03'.
              current_activity_balance =   itab_ksl03.
            ENDIF.
            IF p_date+4(2) = '04'.
              current_activity_balance =   itab_ksl04.
            ENDIF.
            IF p_date+4(2) = '05'.
              current_activity_balance =   itab_ksl05.
            ENDIF.
            IF p_date+4(2) = '06'.
              current_activity_balance =   itab_ksl06.
            ENDIF.
            IF p_date+4(2) = '07'.
              current_activity_balance =   itab_ksl07.
            ENDIF.
            IF p_date+4(2) = '08'.
              current_activity_balance =   itab_ksl08.
            ENDIF.
            IF p_date+4(2) = '09'.
              current_activity_balance =   itab_ksl09.
            ENDIF.
            IF p_date+4(2) = '10'.
              current_activity_balance =   itab_ksl10.
            ENDIF.
            IF p_date+4(2) = '11'.
              current_activity_balance =   itab_ksl11.
            ENDIF.
            IF p_date+4(2) = '12'.
              current_activity_balance =   itab_ksl12.
            ENDIF.
    *LE RESTA 1 AL AÑO CORRIENTE PARA VERIFICAR LUEGO SI EXISTE INFORMACION*
    *DE AÑOS ANTERIORES.                                                   *
            ano = ryear - 1.
    *               Get the values of the past year.                    *
            ano =  p_date+0(4) - 1.
            IF ryear = ano.
              wa_msgdetails-activity_previous_year = itab_ksl12.
    *     balance_previous_year = wa_msgdetails-balance_previous_year.  *
              wa_msgdetails-average_previous_year  = average_month_12.
              wa_msgdetails-aggreg_previous_year   = aggregate_month_12.
            ELSE.
    *If the table don't have data the variables get '0000000000000'.    *
              wa_msgdetails-activity_previous_year          = '00000000000000.00'.
              wa_msgdetails-average_previous_year           = '00000000000000.00'.
              wa_msgdetails-aggreg_previous_year            = '00000000000000.00'.
              AT LAST.
                wa_msgdetails-balance_previous_year           = '00000000000000.00'.
                wa_msgdetails-balance_previous_year           = itab_kslvt +
                                                                itab_ksl01 +
                                                                itab_ksl02 +
                                                                itab_ksl03 +
                                                                itab_ksl04 +
                                                                itab_ksl05 +
                                                                itab_ksl06 +
                                                                itab_ksl07 +
                                                                itab_ksl08 +
                                                                itab_ksl09 +
                                                                itab_ksl10 +
                                                                itab_ksl11 +
                                                                itab_ksl12.
              ENDAT.
            ENDIF.
            wa_msgdetails-account             = numero_de_cta.
            wa_msgdetails-company             = company_code.
            wa_msgdetails-cost_center         = profit_center.
            wa_msgdetails-currency_code       = currency_code.
            wa_msgdetails-account_description = descripcion.
            wa_msgdetails-activity_month_01   = itab_ksl01.
            wa_msgdetails-average_month_01    = porciento1.
            wa_msgdetails-aggreg_month_01     = aggregate_month_01.
            wa_msgdetails-activity_month_02   = itab_ksl02.
            wa_msgdetails-average_month_02    = porciento2.
            wa_msgdetails-aggreg_month_02     = aggregate_month_02.
            wa_msgdetails-activity_month_03   = itab_ksl03.
            wa_msgdetails-average_month_03    = porciento3.
            wa_msgdetails-aggreg_month_03     = aggregate_month_03.
            wa_msgdetails-activity_month_04   = itab_ksl04.
            wa_msgdetails-average_month_04    = porciento4.
            wa_msgdetails-aggreg_month_04     = aggregate_month_04.
            wa_msgdetails-activity_month_05   = itab_ksl05.
            wa_msgdetails-average_month_05    = porciento5.
            wa_msgdetails-aggreg_month_05     = aggregate_month_05.
            wa_msgdetails-activity_month_06   = itab_ksl06.
            wa_msgdetails-average_month_06    = porciento6.
            wa_msgdetails-aggreg_month_06     = aggregate_month_06.
            wa_msgdetails-activity_month_07   = itab_ksl07.
            wa_msgdetails-average_month_07    = porciento7.
            wa_msgdetails-aggreg_month_07     = aggregate_month_07.
            wa_msgdetails-activity_month_08   = itab_ksl08.
            wa_msgdetails-average_month_08    = porciento8.
            wa_msgdetails-aggreg_month_08     = aggregate_month_08.
            wa_msgdetails-activity_month_09   = itab_ksl09.
            wa_msgdetails-average_month_09    = porciento9.
            wa_msgdetails-aggreg_month_09     = aggregate_month_09.
            wa_msgdetails-activity_month_10   = itab_ksl10.
            wa_msgdetails-average_month_10    = porciento10.
            wa_msgdetails-aggreg_month_10     = aggregate_month_10.
            wa_msgdetails-activity_month_11   = itab_ksl11.
            wa_msgdetails-average_month_11    = porciento11.
            wa_msgdetails-aggreg_month_11     = aggregate_month_11.
            wa_msgdetails-activity_month_12   = itab_ksl12.
            wa_msgdetails-average_month_12    = porciento12.
            wa_msgdetails-aggreg_month_12     = aggregate_month_12.
            wa_msgdetails-activity_month_13   = itab_ksl13.
            wa_msgdetails-average_month_13    = '00000000000000.00'.
            wa_msgdetails-aggreg_month_13     = '00000000000000.00'.
            wa_msgdetails-balance_month_01          = balance_month_01.
            wa_msgdetails-balance_month_02          = balance_month_02.
            wa_msgdetails-balance_month_03          = balance_month_03.
            wa_msgdetails-balance_month_04          = balance_month_04.
            wa_msgdetails-balance_month_05          = balance_month_05.
            wa_msgdetails-balance_month_06          = balance_month_06.
            wa_msgdetails-balance_month_07          = balance_month_07.
            wa_msgdetails-balance_month_08          = balance_month_08.
            wa_msgdetails-balance_month_09          = balance_month_09.
            wa_msgdetails-balance_month_10          = balance_month_10.
            wa_msgdetails-balance_month_11          = balance_month_11.
            wa_msgdetails-balance_month_12          = balance_month_12.
            wa_msgdetails-balance_month_13          = balance_month_13.
            wa_msgdetails-current_balance           = current_balance.
            wa_msgdetails-current_activity_balance  = current_activity_balance.
            CLEAR: porciento1, porciento2, porciento3, porciento4, porciento5, porciento6, porciento7, porciento8, porciento9, porciento10, porciento11,
                   porciento12, average_month.
    *se multiplican las siguientes variables que contienen cantidades por -1 cuando el primer numero de la cta. es igual a
    * 5, 6, 7, ó 8.
            IF numero_de_cta+4(1) = '5' OR numero_de_cta+4(1) = '6' OR numero_de_cta+4(1) = '7' OR numero_de_cta+4(1) = '8'.
              IF wa_msgdetails-current_balance IS NOT INITIAL.
                wa_msgdetails-current_balance = wa_msgdetails-current_balance * -1.
              ENDIF.
              IF wa_msgdetails-activity_previous_year IS NOT INITIAL.
                wa_msgdetails-activity_previous_year = wa_msgdetails-activity_previous_year * -1.
              ENDIF.
              IF wa_msgdetails-average_previous_year IS NOT INITIAL.
                wa_msgdetails-average_previous_year = wa_msgdetails-average_previous_year * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_previous_year IS NOT INITIAL.
                wa_msgdetails-aggreg_previous_year = wa_msgdetails-aggreg_previous_year * -1.
              ENDIF.
              IF wa_msgdetails-balance_previous_year IS NOT INITIAL.
                wa_msgdetails-balance_previous_year = wa_msgdetails-balance_previous_year * -1.
              ENDIF.
              IF wa_msgdetails-current_activity_balance IS NOT INITIAL.
                wa_msgdetails-current_activity_balance = wa_msgdetails-current_activity_balance * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_01 IS NOT INITIAL.
                wa_msgdetails-activity_month_01 = wa_msgdetails-activity_month_01 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_01 IS NOT INITIAL.
                wa_msgdetails-balance_month_01 = wa_msgdetails-balance_month_01 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_01 IS NOT INITIAL.
                wa_msgdetails-average_month_01 = wa_msgdetails-average_month_01 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_01 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_01 = wa_msgdetails-aggreg_month_01 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_02 IS NOT INITIAL.
                wa_msgdetails-activity_month_02 = wa_msgdetails-activity_month_02 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_02 IS NOT INITIAL.
                wa_msgdetails-balance_month_02 = wa_msgdetails-balance_month_02 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_02 IS NOT INITIAL.
                wa_msgdetails-average_month_02 = wa_msgdetails-average_month_02 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_02 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_02 = wa_msgdetails-aggreg_month_02 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_03 IS NOT INITIAL.
                wa_msgdetails-activity_month_03 = wa_msgdetails-activity_month_03 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_03 IS NOT INITIAL.
                wa_msgdetails-balance_month_03 = wa_msgdetails-balance_month_03 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_03 IS NOT INITIAL.
                wa_msgdetails-average_month_03 = wa_msgdetails-average_month_03 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_03 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_03 = wa_msgdetails-aggreg_month_03 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_04 IS NOT INITIAL.
                wa_msgdetails-activity_month_04 = wa_msgdetails-activity_month_04 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_04 IS NOT INITIAL.
                wa_msgdetails-balance_month_04 = wa_msgdetails-balance_month_04 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_04 IS NOT INITIAL.
                wa_msgdetails-average_month_04 = wa_msgdetails-average_month_04 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_04 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_04 = wa_msgdetails-aggreg_month_04 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_05 IS NOT INITIAL.
                wa_msgdetails-activity_month_05 = wa_msgdetails-activity_month_05 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_05 IS NOT INITIAL.
                wa_msgdetails-balance_month_05 = wa_msgdetails-balance_month_05 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_05 IS NOT INITIAL.
                wa_msgdetails-average_month_05 = wa_msgdetails-average_month_05 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_05 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_05 = wa_msgdetails-aggreg_month_05 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_06 IS NOT INITIAL.
                wa_msgdetails-activity_month_06 = wa_msgdetails-activity_month_06 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_06 IS NOT INITIAL.
                wa_msgdetails-balance_month_06 = wa_msgdetails-balance_month_06 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_06 IS NOT INITIAL.
                wa_msgdetails-average_month_06 = wa_msgdetails-average_month_06 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_06 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_06 = wa_msgdetails-aggreg_month_06 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_07 IS NOT INITIAL.
                wa_msgdetails-activity_month_07 = wa_msgdetails-activity_month_07 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_07 IS NOT INITIAL.
                wa_msgdetails-balance_month_07 = wa_msgdetails-balance_month_07 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_07 IS NOT INITIAL.
                wa_msgdetails-average_month_07 = wa_msgdetails-average_month_07 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_07 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_07 = wa_msgdetails-aggreg_month_07 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_08 IS NOT INITIAL.
                wa_msgdetails-activity_month_08 = wa_msgdetails-activity_month_08 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_08 IS NOT INITIAL.
                wa_msgdetails-balance_month_08 = wa_msgdetails-balance_month_08 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_08 IS NOT INITIAL.
                wa_msgdetails-average_month_08 = wa_msgdetails-average_month_08 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_08 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_08 = wa_msgdetails-aggreg_month_08 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_09 IS NOT INITIAL.
                wa_msgdetails-activity_month_09 = wa_msgdetails-activity_month_09 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_09 IS NOT INITIAL.
                wa_msgdetails-balance_month_09 = wa_msgdetails-balance_month_09 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_09 IS NOT INITIAL.
                wa_msgdetails-average_month_09 = wa_msgdetails-average_month_09 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_09 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_09 = wa_msgdetails-aggreg_month_09 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_10 IS NOT INITIAL.
                wa_msgdetails-activity_month_10 = wa_msgdetails-activity_month_10 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_10 IS NOT INITIAL.
                wa_msgdetails-balance_month_10 = wa_msgdetails-balance_month_10 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_10 IS NOT INITIAL.
                wa_msgdetails-average_month_10 = wa_msgdetails-average_month_10 * -1.
              ENDIF.
              IF wa_msgdetails-aggreg_month_10 IS NOT INITIAL.
                wa_msgdetails-aggreg_month_10 = wa_msgdetails-aggreg_month_10 * -1.
              ENDIF.
              IF wa_msgdetails-activity_month_11 IS NOT INITIAL.
                wa_msgdetails-activity_month_11 = wa_msgdetails-activity_month_11 * -1.
              ENDIF.
              IF wa_msgdetails-balance_month_11 IS NOT INITIAL.
                wa_msgdetails-balance_month_11 = wa_msgdetails-balance_month_11 * -1.
              ENDIF.
              IF wa_msgdetails-average_month_11 IS NOT INITIAL.
                wa_msgdetails-average_month_11 = wa_msgdetails-average_month_11 *

    Hi,
    Are the month-ends (jan_fin etc) stored in the system? There are many variable declarations and if statements that could probably be eliminated if that is the case.  More efficient use of storing those variables in internal tables so that the data is only used when needed.
    Warren

  • Laptop mode tools problem with kernel 3.0

    today I just updated the system and my laptop runs dramatically hotter after that. I read the archwiki, it does talk about the laptop mode tools problem with kernel 3.0 but when I opened the file /usr/sbin/laptop_mode, the lines which the wiki mentions are not there. Does anyone here have the same problem and can you offer the solution?
    Here is my /usr/sbin/laptop_mode
    #! /bin/sh
    # Script to start or stop laptop_mode, and to control various settings of the
    # kernel, hardware etc. that influence power consumption.
    # This script is a part of Laptop Mode Tools. If you are running a supported
    # power management daemon, this script will be automatically called on power
    # state change.
    # Configure laptop mode tools in /etc/laptop-mode/laptop-mode.conf, and in
    # the broken-out config files in /etc/laptop-mode/conf.d.
    # Please consult the manual pages laptop-mode.conf(8) and laptop_mode(8) for
    # additional information.
    # Maintainer: Ritesh Raj Sarraf ([email protected])
    # Original Author: Bart Samwel ([email protected])
    # Project home page: http://samwel.tk/laptop_mode
    # Contributors to this script: Bart Samwel
    # Kiko Piris
    # Micha Feigin
    # Andrew Morton
    # Herve Eychenne
    # Dax Kelson
    # Jan Polacek
    # ... and many others that I've stopped
    # keeping track of.
    # Based on a script for Linux 2.4 written by Jens Axboe.
    set -a
    # The laptop mode tools version number. Extracted by the installer makefile
    # as well, so don't change the format!
    LMTVERSION=1.59
    # This script is loaded from multiple scripts to set the config defaults
    # and to read the configuration on top of those. Only when the command is
    # recognized does this script do anything else.
    VERBOSE_OUTPUT=0
    ENABLE_LAPTOP_MODE_ON_BATTERY=1
    ENABLE_LAPTOP_MODE_ON_AC=0
    ENABLE_LAPTOP_MODE_WHEN_LID_CLOSED=0
    PARTITIONS="auto /dev/mapper/*"
    LM_BATT_MAX_LOST_WORK_SECONDS=600
    LM_AC_MAX_LOST_WORK_SECONDS=360
    DEF_MAX_AGE=30
    LM_READAHEAD=3072
    NOLM_READAHEAD=128
    CONTROL_READAHEAD=1
    CONTROL_NOATIME=0
    USE_RELATIME=1
    CONTROL_HD_IDLE_TIMEOUT=1
    LM_AC_HD_IDLE_TIMEOUT=4 # 20 seconds
    LM_BATT_HD_IDLE_TIMEOUT=4 # 20 seconds
    NOLM_HD_IDLE_TIMEOUT=244 # 2 hours
    DEF_UPDATE=5
    DEF_XFS_AGE_BUFFER=15
    DEF_XFS_SYNC_INTERVAL=30
    DEF_XFS_BUFD_INTERVAL=1
    XFS_HZ=100
    CONTROL_MOUNT_OPTIONS=1
    BATT_HD_POWERMGMT=1
    LM_AC_HD_POWERMGMT=254
    NOLM_AC_HD_POWERMGMT=254
    CONTROL_HD_POWERMGMT=0
    CONTROL_HD_WRITECACHE=0
    NOLM_AC_HD_WRITECACHE=1
    NOLM_BATT_HD_WRITECACHE=0
    LM_HD_WRITECACHE=0
    LM_DIRTY_RATIO=60
    LM_DIRTY_BACKGROUND_RATIO=1
    NOLM_DIRTY_BACKGROUND_RATIO=10
    NOLM_DIRTY_RATIO=40
    LM_SECONDS_BEFORE_SYNC=2
    BATT_CPU_MAXFREQ=medium
    BATT_CPU_MINFREQ=slowest
    BATT_CPU_GOVERNOR=ondemand
    BATT_CPU_IGNORE_NICE_LOAD=1
    LM_AC_CPU_MAXFREQ=fastest
    LM_AC_CPU_MINFREQ=slowest
    LM_AC_CPU_GOVERNOR=ondemand
    LM_AC_CPU_IGNORE_NICE_LOAD=1
    NOLM_AC_CPU_MAXFREQ=fastest
    NOLM_AC_CPU_MINFREQ=slowest
    NOLM_AC_CPU_GOVERNOR=ondemand
    NOLM_AC_CPU_IGNORE_NICE_LOAD=0
    CONTROL_CPU_FREQUENCY=0
    HD="/dev/[hs]d[abcdefgh]"
    CONTROL_SYSLOG_CONF=0
    LM_AC_SYSLOG_CONF=/etc/syslog-on-ac-with-lm.conf
    NOLM_AC_SYSLOG_CONF=/etc/syslog-on-ac-without-lm.conf
    BATT_SYSLOG_CONF=/etc/syslog-on-battery.conf
    SYSLOG_CONF_SIGNAL_PROGRAM=syslogd
    SYSLOG_CONF=/etc/syslog.conf
    CONTROL_DPMS_STANDBY=0
    BATT_DPMS_STANDBY=300
    LM_AC_DPMS_STANDBY=1200
    NOLM_AC_DPMS_STANDBY=1200
    CONTROL_CPU_THROTTLING=0
    BATT_CPU_THROTTLING=medium
    LM_AC_CPU_THROTTLING=minimum
    NOLM_AC_CPU_THROTTLING=minimum
    CONTROL_START_STOP=1
    CONTROL_TERMINAL=0
    TERMINALS="/dev/vc/1 /dev/vcs1"
    BATT_TERMINAL_BLANK_MINUTES=1
    BATT_TERMINAL_POWERDOWN_MINUTES=2
    LM_AC_TERMINAL_BLANK_MINUTES=10
    LM_AC_TERMINAL_POWERDOWN_MINUTES=10
    NOLM_AC_TERMINAL_BLANK_MINUTES=10
    NOLM_AC_TERMINAL_POWERDOWN_MINUTES=50
    ENABLE_AUTO_HIBERNATION=0
    HIBERNATE_COMMAND=/usr/sbin/hibernate
    AUTO_HIBERNATION_ON_CRITICAL_BATTERY_LEVEL=1
    DISABLE_LAPTOP_MODE_ON_CRITICAL_BATTERY_LEVEL=1
    AUTO_HIBERNATION_BATTERY_CHARGE_MAH=0
    AUTO_HIBERNATION_BATTERY_CHARGE_MWH=0
    MINIMUM_BATTERY_CHARGE_MAH=0
    MINIMUM_BATTERY_CHARGE_MWH=0
    ASSUME_SCSI_IS_SATA=1
    CONTROL_BRIGHTNESS=0
    BATT_BRIGHTNESS_COMMAND=false
    LM_AC_BRIGHTNESS_COMMAND=false
    NOLM_AC_BRIGHTNESS_COMMAND=false
    LOG_TO_SYSLOG=1
    DEBUG=0
    ENABLE_LAPTOP_MODE_TOOLS=1
    # Initialize the PATH Variable
    export PATH="${PATH}":/bin:/sbin:/usr/bin:/usr/sbin
    # This is a 2 phase locking approach. LMT_REQ_LOCK is the outer lock and LMT_INVOC_LOCK is the inner lock
    # We take this approach to ensure the scenario that, "At any point when an event occurs (AC/BATT), the
    # kernel can generate multiple events spanning over a couple of events. The first event is honored and
    # lmt executes. If the last event triggered at the 9th second, there is a fair chance that a good amount
    # of state change would have occured in the OS, to honor that state, we keep an outer lock (LMT_REQ_LOCK)
    # handy, so that those changes can also be applied and not forgotten.
    # Workflow:
    # Event-1 is generated and lmt executes (lmt runtime could span 5-10 seconds)
    # At seventh second, 4 events generate. But Event-1 is still running.
    # We don't want to discard all the remaining 4 events, but at least honor 1 so that we can act to the changes
    # that occured in the last 7 seconds.
    # So, Event-2 acquire LMT_REQ_LOCK and waits to acquire LMT_INVOC_LOCK (which is acquire by Event-1)
    LMT_REQ_LOCK="/var/lock/lmt-req.lock"
    LMT_INVOC_LOCK="/var/lock/lmt-invoc.lock"
    FLOCK=`which flock`
    checkint ()
    # $1 arg should be the string/integer
    # that you want to check for as an integer.
    echo $1 | grep "[^0-9]" > /dev/null 2>&1
    return $?;
    # Returns 1 if it is an integer
    # Function to handle logging
    LOGGER=`which logger`;
    log ()
    # $1 should be msg type
    # $2 should be the real msg
    if [ x$LOG_TO_SYSLOG = x1 ]; then
    # NOTE: Add the check on $2 being empty, once you are confident
    # that there aren't any bugs in logging. And no bugs in executing
    # modules and logging
    if [ -x $LOGGER -a "$1" != "STATUS" ]; then
    #if [ -z $2 ]; then
    # continue
    #elif [ "$1" = "MSG" ]; then
    if [ "$1" = "MSG" ]; then
    logger -p daemon.info -t laptop-mode "$2";
    elif [ "$1" = "ERR" ]; then
    logger -p daemon.err -t laptop-mode "$2";
    elif [ "$1" = "VERBOSE" ]; then
    if [ x$VERBOSE_OUTPUT = x1 ]; then
    logger -p daemon.debug -t laptop-mode "$2";
    fi
    else
    logger -p daemon.notice -t laptop-mode "$2";
    fi
    fi
    fi
    if [ "$1" = "VERBOSE" ]; then
    $LM_VERBOSE && echo "$2" >/dev/fd/2;
    elif [ "$1" = "ERR" ]; then
    echo "$2" >/dev/fd/2;
    else
    # Message of type MSG and STATUS can go to stdout.
    echo "$2" >/dev/fd/1;
    fi
    enableDebug ()
    # Check if debug is enabled
    if [ x$(($(basename $1 | cut -d . -f1 | tr "[:lower:]" "[:upper:]" | sed 's/-/_/g')_DEBUG)) = x1 ]; then
    set -vx
    fi
    disableDebug ()
    # Check if debug is enabled
    if [ x$(($(basename $1 | cut -d . -f1 | tr "[:lower:]" "[:upper:]" | sed 's/-/_/g')_DEBUG)) = x1 ]; then
    set +vx
    fi
    # No default on these ones -- we need to detect if they have been set, for
    # backward compatibility with MINIMUM_BATTERY_MINUTES etc.
    AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT=
    MINIMUM_BATTERY_CHARGE_PERCENT=
    # Backward compatibility variable that is sometimes
    # set externally (Debian init system)
    unset VERBOSE
    lmt_load_config ()
    # Source config. Some config settings have been moved from the main config file
    # to modular configuration files, and to support existing laptop-mode.conf
    # files from earlier versions, we source the modular configuration files FIRST.
    if [ -d /etc/laptop-mode/conf.d ] ; then
    for CONF in /etc/laptop-mode/conf.d/*.conf ; do
    if [ -r "$CONF" ] ; then
    . "$CONF"
    #Handle individual module debug settings
    if [ "$DEBUG" -eq 1 ]; then
    export $(basename $CONF | cut -d . -f1 | tr "[:lower:]" "[:upper:]" | sed 's/-/_/g')_DEBUG=1
    log "VERBOSE" "Enabling debug mode for module $CONF"
    fi
    DEBUG=0
    else
    log "MSG" "Warning: Configuration file $CONF is not readable, skipping."
    fi
    done
    fi
    if [ -r /etc/laptop-mode/laptop-mode.conf ] ; then
    . /etc/laptop-mode/laptop-mode.conf
    else
    log "ERR" "$0: Configuration file /etc/laptop-mode/laptop-mode.conf not present or not readable."
    exit 1
    fi
    if [ x$ENABLE_LAPTOP_MODE_TOOLS = x0 ]; then
    log "MSG" "laptop-mode-tools is disabled in config file. Exiting"
    exit 0;
    fi
    # Add a simple bash debug mode switch
    if [ "$DEBUG" -eq 1 ]; then
    set -vx;
    fi
    # Support for old config settings
    if [ "$AC_HD" != "" ] ; then
    AC_HD_WITHOUT_LM="$AC_HD"
    AC_HD_WITH_LM="$AC_HD"
    fi
    if [ "$VERBOSE" != "" ] ; then
    VERBOSE_OUTPUT="$VERBOSE"
    fi
    if [ "$CPU_MAXFREQ" != "" ] ; then
    BATT_CPU_MAXFREQ="$CPU_MAXFREQ"
    fi
    if [ "$MAX_AGE" != "" ] ; then
    LM_BATT_MAX_LOST_WORK_SECONDS="$MAX_AGE"
    LM_AC_MAX_LOST_WORK_SECONDS="$MAX_AGE"
    fi
    if [ "$DEF_AGE" != "" ] ; then
    DEF_MAX_AGE="$DEF_AGE"
    fi
    if [ "$LAPTOP_MODE_ALWAYS_ON" != "" ] ; then
    ENABLE_LAPTOP_MODE_ALWAYS="$LAPTOP_MODE_ALWAYS_ON"
    fi
    if [ "$LM_WHEN_LID_CLOSED" != "" ] ; then
    ENABLE_LAPTOP_MODE_WHEN_LID_CLOSED="$LM_WHEN_LID_CLOSED"
    fi
    if [ "$REMOUNT_PARTITIONS" != "" ] ; then
    PARTITIONS="$REMOUNT_PARTITIONS"
    fi
    if [ "$READAHEAD" != "" ] ; then
    LM_READAHEAD="$READAHEAD"
    fi
    if [ "$DO_REMOUNT_NOATIME" != "" ] ; then
    CONTROL_NOATIME="$DO_REMOUNT_NOATIME"
    fi
    if [ "$DO_HD" != "" ] ; then
    CONTROL_HD_IDLE_TIMEOUT="$DO_HD"
    fi
    if [ "$AC_HD_WITH_LM" != "" ] ; then
    LM_AC_HD_IDLE_TIMEOUT="$AC_HD_WITH_LM"
    fi
    if [ "$AC_HD_WITHOUT_LM" != "" ] ; then
    NOLM_HD_IDLE_TIMEOUT="$AC_HD_WITHOUT_LM"
    fi
    if [ "$BATT_HD" != "" ] ; then
    LM_BATT_HD_IDLE_TIMEOUT="$BATT_HD"
    fi
    if [ "$DO_REMOUNTS" != "" ] ; then
    CONTROL_MOUNT_OPTIONS="$DO_REMOUNTS"
    fi
    if [ "$DO_HD_POWERMGMT" != "" ] ; then
    CONTROL_HD_POWERMGMT="$DO_HD_POWERMGMT"
    fi
    if [ "$AC_HDPARM_POWERMGMT_WITH_LM" != "" ] ; then
    LM_AC_HD_POWERMGMT="$AC_HDPARM_POWERMGMT_WITH_LM"
    fi
    if [ "$AC_HDPARM_POWERMGMT_WITHOUT_LM" != "" ] ; then
    NOLM_AC_HD_POWERMGMT="$AC_HDPARM_POWERMGMT_WITHOUT_LM"
    fi
    if [ "$BATT_HDPARM_POWERMGMT" != "" ] ; then
    BATT_HD_POWERMGMT="$BATT_HDPARM_POWERMGMT"
    fi
    if [ "$DO_WRITECACHE" != "" ] ; then
    CONTROL_HD_WRITECACHE="$DO_WRITECACHE"
    fi
    if [ "$AC_WRITECACHE_WITHOUT_LM" != "" ] ; then
    NOLM_AC_HD_WRITECACHE="$AC_WRITECACHE_WITHOUT_LM"
    fi
    if [ "$BATT_WRITECACHE" != "" ] ; then
    LM_HD_WRITECACHE="$BATT_WRITECACHE"
    fi
    if [ "$DIRTY_RATIO" != "" ]; then
    LM_DIRTY_RATIO="$DIRTY_RATIO"
    fi
    if [ "$DIRTY_BACKGROUND_RATIO" != "" ] ; then
    LM_DIRTY_BACKGROUND_RATIO="$DIRTY_BACKGROUND_RATIO"
    fi
    if [ "$DEF_DIRTY_RATIO" != "" ]; then
    NOLM_DIRTY_RATIO="$DEF_DIRTY_RATIO"
    fi
    if [ "$DEF_DIRTY_BACKGROUND_RATIO" != "" ] ; then
    NOLM_DIRTY_BACKGROUND_RATIO="$DEF_DIRTY_BACKGROUND_RATIO"
    fi
    if [ "$DO_CPU" != "" ] ; then
    CONTROL_CPU_FREQUENCY="$DO_CPU"
    fi
    if [ "$CONTROL_CPU_MAXFREQ" != "" ] ; then
    CONTROL_CPU_FREQUENCY="$CONTROL_CPU_MAXFREQ"
    fi
    if [ "$AC_CPU_MAXFREQ_WITH_LM" != "" ] ; then
    LM_AC_CPU_MAXFREQ="$AC_CPU_MAXFREQ_WITH_LM"
    fi
    if [ "$AC_CPU_MAXFREQ_WITHOUT_LM" != "" ] ; then
    NOLM_AC_CPU_MAXFREQ="$AC_CPU_MAXFREQ_WITHOUT_LM"
    fi
    if [ "$DO_SYSLOG" != "" ] ; then
    CONTROL_SYSLOG_CONF="$DO_SYSLOG"
    fi
    if [ "$SYSLOG_SIGNAL_PROGRAM" != "" ] ;then
    SYSLOG_CONF_SIGNAL_PROGRAM="$SYSLOG_SIGNAL_PROGRAM"
    fi
    if [ "$AC_SYSLOG_WITH_LM" != "" ] ; then
    LM_AC_SYSLOG_CONF="$AC_SYSLOG_WITH_LM"
    fi
    if [ "$AC_SYSLOG_WITHOUT_LM" != "" ] ; then
    NOLM_AC_SYSLOG_CONF="$AC_SYSLOG_WITHOUT_LM"
    fi
    if [ "$BATT_SYSLOG" != "" ] ; then
    BATT_SYSLOG_CONF="$BATT_SYSLOG"
    fi
    if [ "$ENABLE_LAPTOP_MODE_ALWAYS" != "" ] ; then
    ENABLE_LAPTOP_MODE_ON_AC="$ENABLE_LAPTOP_MODE_ALWAYS"
    fi
    if [ "$MINIMUM_BATTERY_MINUTES" != "" -a "$MINIMUM_BATTERY_CHARGE_PERCENT" = "" ] ; then
    # Use a very conservative estimate (1% = 1 battery minute, 100 minutes in a battery)
    # for backward compatibility.
    MINIMUM_BATTERY_CHARGE_PERCENT="$MINIMUM_BATTERY_MINUTES"
    fi
    if [ -z "$MINIMUM_BATTERY_CHARGE_PERCENT" ] ; then
    # Apply the default, now that we've determined that this is the minimum.
    MINIMUM_BATTERY_CHARGE_PERCENT=3
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_MINUTES" != "" -a "$AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT" = "" ] ; then
    # Use a very conservative estimate (1% = 1 battery minute, 100 minutes in a battery)
    # for backward compatibility.
    AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT="$AUTO_HIBERNATION_BATTERY_MINUTES"
    fi
    if [ -z "$AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT" ] ; then
    # Apply the default, now that we've determined that this is the minimum.
    AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT=2
    fi
    # Postprocessing
    if [ "$VERBOSE_OUTPUT" -ne 0 ] ; then
    OUTPUT="/dev/stdout"
    LM_VERBOSE="[ 1 = 1 ]"
    else
    OUTPUT="/dev/null"
    LM_VERBOSE="[ 1 = 0 ]"
    fi
    if [ "$PARTITIONS" = "" ] ; then
    PARTITIONS="auto /dev/mapper/*"
    fi
    # Expand shell wild cards immediately.
    PARTITIONS=$( echo $PARTITIONS )
    TERMINALS=$( echo $TERMINALS )
    # Convert seconds to hdparm -S format
    # Everything over 20 minutes is interpreted as 2 hours.
    seconds_to_hdparm_S() {
    if [ "$1" -eq 0 ] ; then
    # disable.
    echo 0
    elif [ "$1" -gt 0 -a "$1" -lt 5 ] ; then
    # 5 seconds minimum
    echo 1
    elif [ "$1" -le $((240*5)) ] ; then
    # Values between 1 and 240 signify increments of 5 seconds
    echo $(($1 / 5))
    elif [ "$1" -lt $((30*60)) ] ; then
    # Values between 20 and 30 minutes are rounded up to 30 minutes.
    echo 241
    elif [ "$1" -lt $((12*30*60)) ] ; then
    # Values between 30 minutes and 6 hours (exclusive) yield values between
    # 241 and 251, in 30-minute increments.
    echo $(( 240 + ($1 / (30*60)) ))
    else
    # Larger values effectively indicate no timeout at all.
    echo 0
    fi
    # Convert configured idle timeouts to hdparm -S format.
    if [ "$LM_AC_HD_IDLE_TIMEOUT_SECONDS" != "" ] ; then
    LM_AC_HD_IDLE_TIMEOUT=$(seconds_to_hdparm_S $LM_AC_HD_IDLE_TIMEOUT_SECONDS)
    fi
    if [ "$LM_BATT_HD_IDLE_TIMEOUT_SECONDS" != "" ] ; then
    LM_BATT_HD_IDLE_TIMEOUT=$(seconds_to_hdparm_S $LM_BATT_HD_IDLE_TIMEOUT_SECONDS)
    fi
    if [ "$NOLM_HD_IDLE_TIMEOUT_SECONDS" != "" ] ; then
    NOLM_HD_IDLE_TIMEOUT=$(seconds_to_hdparm_S $NOLM_HD_IDLE_TIMEOUT_SECONDS)
    fi
    # The main workhorse.
    lmt_main_function ()
    if [ "$1" = "status" ] ; then
    # Display a status report.
    log "STATUS" "Mounts:"
    mount | sed "s/^/ /"
    log "STATUS" " "
    log "STATUS" "Drive power status:"
    for disk in $HD; do
    if [ -r $disk ]; then
    hdparm -C $disk 2>/dev/null | sed "s/^/ /"
    else
    log "STATUS" " Cannot read $disk, permission denied - $0 needs to be run as root"
    fi
    done
    log "STATUS" " "
    log "STATUS" "(NOTE: drive settings affected by Laptop Mode cannot be retrieved.)"
    log "STATUS" " "
    log "STATUS" "Readahead states:"
    cat /etc/mtab | while read DEV MP FST OPTS DUMP PASS ; do
    # skip funny stuff
    case "$FST" in
    rootfs|unionfs|tmpfs|squashfs|sysfs|usbfs|proc|devpts) continue
    esac
    if [ -b $DEV ] ; then
    if [ -r $DEV ] ; then
    log "STATUS" " $DEV: $((`blockdev --getra $DEV` / 2)) kB"
    else
    log "STATUS" " Cannot read $DEV, permission denied - $0 needs to be run as root"
    fi
    fi
    done
    log "STATUS" " "
    if [ -e /var/run/laptop-mode-tools/enabled ] ; then
    log "STATUS" "Laptop Mode Tools is allowed to run: /var/run/laptop-mode-tools/enabled exists."
    else
    log "STATUS" "Laptop Mode Tools is NOT allowed to run: /var/run/laptop-mode-tools/enabled does not exist."
    fi
    log "STATUS" " "
    STATFILES="/proc/sys/vm/laptop_mode /proc/apm /proc/pmu/info /proc/sys/vm/bdflush /proc/sys/vm/dirty_ratio /proc/sys/fs/xfs/age_buffer /proc/sys/fs/xfs/sync_interval /proc/sys/fs/xfs/lm_age_buffer /proc/sys/fs/xfs/lm_sync_interval /proc/sys/vm/pagebuf/lm_flush_age /proc/sys/fs/xfs/xfsbufd_centisecs /proc/sys/fs/xfs/xfssyncd_centisecs /proc/sys/vm/dirty_background_ratio /proc/sys/vm/dirty_expire_centisecs /proc/sys/fs/xfs/age_buffer/centisecs /proc/sys/vm/dirty_writeback_centisecs /sys/devices/system/cpu/*/cpufreq/cpuinfo_*_freq /sys/devices/system/cpu/*/cpufreq/scaling_governor /proc/acpi/button/lid/*/state /proc/acpi/ac_adapter/*/state /proc/acpi/battery/*/state /sys/class/power_supply/*/online /sys/class/power_supply/*/state"
    for THISFILE in $STATFILES ; do
    if [ -e "$THISFILE" ] ; then
    log "STATUS" "$THISFILE:"
    if [ -r "$THISFILE" ] ; then
    cat "$THISFILE" | sed "s/^/ /"
    else
    log "STATUS" " Not accessible, permission denied - $0 needs to be run as root."
    fi
    log "STATUS" " "
    fi
    done
    elif [ "$1" != "readconfig" -a "$1" != "defaults" ] ; then
    KLEVEL="$(uname -r |
    IFS='.-' read a b c
    echo $a.$b
    KMINOR="$(uname -r |
    IFS='.-' read a b c d
    # Strip any stuff from the end -- only the initial digits are part of the KMINOR.
    echo $c | sed -e 's/\([[:digit:]]*\).*/\1/'
    # Stop exporting everything -- what we do from here is private.
    set +a
    if [ "$1" = "--version" ] ; then
    log "MSG" "Laptop Mode Tools $LMTVERSION"
    exit 0
    fi
    if [ ! -e /proc/sys/vm/laptop_mode ] ; then
    log "ERR" "Kernel does not have support for laptop mode. Please apply the laptop mode"
    log "ERR" "patch or install a newer kernel."
    exit 1
    fi
    if [ ! -w /proc/sys/vm/laptop_mode ] ; then
    log "ERR" "You do not have enough privileges to enable laptop_mode."
    exit 1
    fi
    INIT=0 # Display info in init script format?
    FORCE=0 # Force reapplying the current state?
    while [ "$1" != "" ] ; do
    case "$1" in
    init) INIT=1 ;;
    force) FORCE=1 ;;
    # Old options. We always do "auto" for any option now, but
    # we still have to accept the options.
    start) ;;
    stop) ;;
    auto) ;;
    modules=*)
    MODULES=$1
    MODULES=${MODULES#"modules="}
    devices=*)
    DEVICES=$1
    DEVICES=${DEVICES#"devices="}
    *) log "ERR" "Unrecognized option $1."
    exit 1 ;;
    esac
    shift
    done
    mkdir -p /var/run/laptop-mode-tools
    # Used to display laptop mode state later on. This is the enabled/disabled
    # state for laptop mode processing, it tells us nothing about whether laptop
    # mode is actually _active_.
    STATE=enabled
    if [ "$ENABLE_LAPTOP_MODE_ON_BATTERY" -eq 0 -a "$ENABLE_LAPTOP_MODE_ON_AC" -eq 0 -a "$ENABLE_LAPTOP_MODE_WHEN_LID_CLOSED" -eq 0 ] ; then
    STATE=disabled
    fi
    # Determine the power state.
    # First try /sys/class/power_supply/*
    FOUND_SYS_CLASS_POWER_SUPPLY_AC=0
    ON_AC=0
    for POWER_SUPPLY in /sys/class/power_supply/* ; do
    if [ -f $POWER_SUPPLY/type ] ; then
    if [ "$(cat $POWER_SUPPLY/type)" = "Mains" ] ;then
    log "VERBOSE" "Determining power state from $POWER_SUPPLY/online."
    FOUND_SYS_CLASS_POWER_SUPPLY_AC=1
    if [ "$(cat $POWER_SUPPLY/online)" = 1 ] ; then
    ON_AC=1
    fi
    fi
    fi
    done
    if [ $FOUND_SYS_CLASS_POWER_SUPPLY_AC = 1 ] ; then
    # Already found it!
    log "VERBOSE" "Not trying other options, already found a power supply."
    elif [ -d /proc/acpi/ac_adapter ] ; then
    log "VERBOSE" "Determining power state from /proc/acpi/ac_adapter."
    ADAPTERS_FOUND=0
    ON_AC=0
    for ADAPTER in /proc/acpi/ac_adapter/* ; do
    if [ -f $ADAPTER/state ] ; then
    ADAPTERS_FOUND=1
    STATUS=`awk '/^state: / { print $2 }' $ADAPTER/state`
    if [ "$STATUS" = "on-line" ] ; then
    ON_AC=1
    fi
    fi
    done
    if [ "$ADAPTERS_FOUND" -eq 0 ] ; then
    ON_AC=1
    fi
    elif [ -f /proc/pmu/info ] ; then
    log "VERBOSE" "Determining power state from /proc/pmu/info."
    if ( grep -q "^AC Power.*0$" /proc/pmu/info ) ; then
    log "VERBOSE" "/proc/pmu/info indicates absence of AC power."
    ON_AC=0
    else
    # It is possible that there is no AC Power = 1 in the file,
    # but we always assume AC power when we're not sure.
    ON_AC=1
    log "VERBOSE" "/proc/pmu/info indicates presence of AC power."
    fi
    elif [ -f /proc/apm ] ; then
    log "VERBOSE" "Determining power state from /proc/apm."
    read D1 D2 D3 APM_AC_STATE D0 </proc/apm
    if [ "$APM_AC_STATE" = "0x00" ] ; then
    ON_AC=0
    else
    ON_AC=1
    fi
    else
    log "VERBOSE" "No /sys/class/power_supply, ACPI, APM or PMU power management information found -- assuming AC power is present."
    ON_AC=1
    fi
    # Determine whether to activate or deactivate laptop mode.
    ACTIVATE=0
    if [ "$ON_AC" -eq 1 ] ; then
    if [ "$ENABLE_LAPTOP_MODE_ON_AC" -ne 0 ] ; then
    log "VERBOSE" "On AC power: Activating, because ENABLE_LAPTOP_MODE_ON_AC is set."
    ACTIVATE=1
    else
    log "VERBOSE" "On AC power: Deactivating, because ENABLE_LAPTOP_MODE_ON_AC is not set."
    ACTIVATE=0
    fi
    else
    if [ "$ENABLE_LAPTOP_MODE_ON_BATTERY" -ne 0 ] ; then
    log "VERBOSE" "On battery power: Activating, because ENABLE_LAPTOP_MODE_ON_BATTERY is set."
    ACTIVATE=1
    else
    log "VERBOSE" "On battery power: Deactivating, because ENABLE_LAPTOP_MODE_ON_BATTERY is not set."
    ACTIVATE=0
    fi
    fi
    if [ "$ENABLE_LAPTOP_MODE_WHEN_LID_CLOSED" -ne 0 -a "$ACTIVATE" -eq 0 ] ; then
    if [ -x "`which hal-find-by-property`" ] ; then
    HAL_LID_BUTTON=$(hal-find-by-property --key "button.type" --string "lid")
    fi
    if [ "$HAL_LID_BUTTON" != "" ] ; then
    HAL_LID_BUTTON_STATE=$(hal-get-property --udi $(hal-find-by-property --key "button.type" --string "lid") --key "button.state.value")
    if [ "$HAL_LID_BUTTON_STATE" = "true" ] ; then
    log "VERBOSE" "Setting action to \"start\" because the lid is closed (says HAL)."
    ACTIVATE=1
    fi
    elif [ -f /proc/acpi/button/lid/*/state ] ; then
    if ( grep -q "closed" /proc/acpi/button/lid/*/state ) ; then
    log "VERBOSE" 'Setting action to "start" because the lid is closed (says /proc/acpi/button/lid/*/state).'
    ACTIVATE=1
    fi
    else
    log "MSG" "Warning: ENABLE_LAPTOP_MODE_WHEN_LID_CLOSED is set, but there is no file"
    log "MSG" "/proc/acpi/button/lid/.../state, and hal information is not available either!"
    fi
    fi
    # If the init script has not been run or has been run with the "stop"
    # argument, then we should never start laptop mode.
    if [ ! -f /var/run/laptop-mode-tools/enabled ] ; then
    log "VERBOSE" "Laptop mode disabled because /var/run/laptop-mode-tools/enabled is missing."
    STATE=disabled
    fi
    if [ "$ACTIVATE" -eq 1 -a -f /etc/default/laptop-mode ] ; then
    . /etc/default/laptop-mode
    if ! ( echo "$ENABLE_LAPTOP_MODE" |grep y ) ; then
    log "VERBOSE" "Not starting laptop mode because it is disabled in /etc/default/laptop-mode."
    STATE=disabled
    fi
    fi
    if [ "$STATE" = "disabled" ] ; then
    ACTIVATE=0
    fi
    # Check whether we are allowed to activate the data-loss-sensitive stuff.
    # If the battery charge is too low, we want to disable this, but not the
    # other power-saving stuff.
    if [ "$ACTIVATE" -eq 0 ] ; then
    ACTIVATE_WITH_POSSIBLE_DATA_LOSS=0
    elif [ "$ON_AC" = 1 ] ; then
    log "VERBOSE" "On AC, not checking minimum battery charge."
    ACTIVATE_WITH_POSSIBLE_DATA_LOSS=1
    else
    ACTIVATE_WITH_POSSIBLE_DATA_LOSS=1
    ENOUGH_CHARGE=0
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=0
    # Weird way of checking that /sys/class/power_supply is not empty -- but it works.
    if [ "$(echo /sys/class/power_supply/*)" != '/sys/class/power_supply/*' ] ; then
    log "VERBOSE" "Not on AC and we have battery information in /sys/class/power_supply/BAT* -- checking minimum battery charge."
    for BATT in /sys/class/power_supply/* ; do
    BATT_TYPE=$(cat $BATT/type)
    log "VERBOSE" "$BATT is of type $BATT_TYPE."
    if [ "$BATT_TYPE" != "Battery" ] ; then
    log "VERBOSE" "Not of type \"Battery\", skipping."
    else
    PREV_ENOUGH_CHARGE=$ENOUGH_CHARGE
    PREV_ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=$ENOUGH_CHARGE_TO_PREVENT_HIBERNATION
    log "VERBOSE" "Checking levels for $BATT."
    PRESENT=$(cat $BATT/present)
    log "VERBOSE" "Present: $PRESENT."
    # Only do if the battery is present
    if [ "$PRESENT" -eq 1 ] ; then
    FOUND_AN_ENABLED_CHECK=0
    FOUND_AN_ENABLED_HIBERNATION_CHECK=0
    # Get the remaining capacity.
    IN_UAH=0
    IN_UWH=0
    if [ -f $BATT/charge_now ] ; then
    REMAINING=$(cat $BATT/charge_now)
    IN_UAH=1 # charge_* is in microAmpere-hours
    elif [ -f $BATT/energy_now ] ; then
    REMAINING=$(cat $BATT/energy_now)
    IN_UWH=1 # energy_* is in microWatt-hours
    else
    REMAINING=0
    fi
    if [ -z "$REMAINING" -o "$REMAINING" -eq 0 ] ; then
    log "VERBOSE" "Battery does not report remaining charge. Perhaps it is not present?"
    REMAINING=0
    fi
    log "VERBOSE" "Remaining charge: $REMAINING"
    if [ -f $BATT/charge_full_design ] ; then
    CAPACITY=$(cat $BATT/charge_full_design)
    elif [ -f $BATT/energy_full_design ] ; then
    CAPACITY=$(cat $BATT/energy_full_design)
    else
    CAPACITY=0
    fi
    if [ -z "$CAPACITY" -o "$CAPACITY" -eq 0 ] ; then
    log "VERBOSE" "Battery does not report design full charge, using non-design full charge."
    if [ -f $BATT/charge_full ] ; then
    CAPACITY=$(cat $BATT/charge_full)
    elif [ -f $BATT/energy_full_design ] ; then
    CAPACITY=$(cat $BATT/energy_full)
    else
    CAPACITY=0
    fi
    if [ -z "$CAPACITY" -o "$CAPACITY" -eq 0 ] ; then
    log "VERBOSE" "Battery does not report non-design full charge."
    CAPACITY=0
    fi
    fi
    log "VERBOSE" "Full capacity: $CAPACITY"
    # Check the charge percentage
    if [ "$MINIMUM_BATTERY_CHARGE_PERCENT" -ne 0 ] ; then
    FOUND_AN_ENABLED_CHECK=1
    if [ "$CAPACITY" -eq 0 ] ; then
    log "MSG" "WARNING: Battery does not report a capacity. Minimum battery"
    log "MSG" "charge checking does not work without a design capacity."
    ENOUGH_CHARGE=1
    elif [ "$(($REMAINING * 100 / $CAPACITY))" -ge "$MINIMUM_BATTERY_CHARGE_PERCENT" ] ; then
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT" -ne 0 ] ; then
    FOUND_AN_ENABLED_HIBERNATION_CHECK=1
    if [ "$CAPACITY" -eq 0 ] ; then
    log "MSG" "WARNING: Battery does not report a design capacity. Auto hibernation"
    log "MSG" "does not work without a design capacity."
    ENOUGH_CHARGE=1
    elif [ "$(($REMAINING * 100 / $CAPACITY))" -ge "$AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT" ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    # $BATT/alarm is the design_capacity_warning of a battery.
    ALARM_LEVEL=$(cat $BATT/alarm)
    if [ "$ALARM_LEVEL" -ne 0 ] ; then
    if [ "$REMAINING" -le "$ALARM_LEVEL" ] ; then
    # Restore the state we had before checking this battery, so that
    # this battery does not count as having enough charge.
    ENOUGH_CHARGE=$PREV_ENOUGH_CHARGE
    elif [ "$FOUND_AN_ENABLED_CHECK" -eq 0 ] ; then
    # This is the only check that is enabled. In that case a non-critical
    # battery level counts as "enough". (If we would count non-critical
    # battery levels as enough *always*, then the other settings would
    # have no effect; this is only a final fallback.)
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_ON_CRITICAL_BATTERY_LEVEL" -ne 0 ] ; then
    if [ "$REMAINING" -le "$ALARM_LEVEL" ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=$PREV_ENOUGH_CHARGE_TO_PREVENT_HIBERNATION
    elif [ "$FOUND_AN_ENABLED_HIBERNATION_CHECK" -eq 0 ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    # Fallback: hard values
    if [ "$IN_UAH" -ne 0 ] ; then
    if [ "$MINIMUM_BATTERY_CHARGE_MAH" -ne 0 ] ; then
    FOUND_AN_ENABLED_CHECK=1
    if [ "$REMAINING" -ge $((1000*"$MINIMUM_BATTERY_CHARGE_MAH")) ] ; then
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_CHARGE_MAH" -ne 0 ] ; then
    FOUND_AN_ENABLED_HIBERNATION_CHECK=1
    if [ "$REMAINING" -ge $((1000*"$AUTO_HIBERNATION_BATTERY_CHARGE_MAH")) ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    elif [ "$IN_UWH" -ne 0 ] ; then
    if [ "$MINIMUM_BATTERY_CHARGE_MWH" -ne 0 ] ; then
    FOUND_AN_ENABLED_CHECK=1
    if [ "$REMAINING" -ge $((1000*"$MINIMUM_BATTERY_CHARGE_MWH")) ] ; then
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_CHARGE_MWH" -ne 0 ] ; then
    FOUND_AN_ENABLED_HIBERNATION_CHECK=1
    if [ "$REMAINING" -ge $((1000*"$AUTO_HIBERNATION_BATTERY_CHARGE_MWH")) ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    else
    log "ERR" "Failed to determine battery charge. Battery charge units are not in"
    log "ERR" "mWh, uWh, mAh or uAh."
    fi
    else
    log "VERBOSE" "Battery is not present."
    fi
    fi
    done
    elif [ "$(echo /proc/acpi/battery/*)" != '/proc/acpi/battery/*' ] ; then
    log "VERBOSE" "Not on AC and we have batteries in /proc/acpi/battery -- checking minimum battery charge."
    for BATT in /proc/acpi/battery/* ; do
    PREV_ENOUGH_CHARGE=$ENOUGH_CHARGE
    PREV_ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=$ENOUGH_CHARGE_TO_PREVENT_HIBERNATION
    BATT_STATE=$BATT/state
    BATT_INFO=$BATT/info
    log "VERBOSE" "Checking info and state for $BATT."
    # Only do if the battery is present
    if ( grep -q 'present:.*yes' $BATT_INFO ) ; then
    FOUND_AN_ENABLED_CHECK=0
    FOUND_AN_ENABLED_HIBERNATION_CHECK=0
    # Get the remaining capacity.
    REMAINING=`grep "remaining capacity:" $BATT_STATE | sed "s/.* \([0-9][0-9]* \).*/\1/" `
    if [ -z "$REMAINING" ] ; then
    log "VERBOSE" "Battery does not report remaining charte. Perhaps it is not present?"
    REMAINING=0
    fi
    log "VERBOSE" "Remaining charge: $REMAINING"
    CAPACITY=`grep "design capacity:" $BATT_INFO | sed "s/.* \([0-9][0-9]* \).*/\1/" `
    if [ -z "$CAPACITY" ] ; then
    log "VERBOSE" "Battery does not report capacity. Perhaps it is not present?"
    CAPACITY=0
    fi
    log "VERBOSE" "Design capacity: $CAPACITY"
    # Check the charge percentage
    if [ "$MINIMUM_BATTERY_CHARGE_PERCENT" -ne 0 ] ; then
    FOUND_AN_ENABLED_CHECK=1
    if [ "$CAPACITY" -eq 0 ] ; then
    log "MSG" "WARNING: Battery does not report a design capacity. Minimum battery"
    log "MSG" "charge checking does not work without a design capacity."
    ENOUGH_CHARGE=1
    elif [ "$(($REMAINING * 100 / $CAPACITY))" -ge "$MINIMUM_BATTERY_CHARGE_PERCENT" ] ; then
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT" -ne 0 ] ; then
    FOUND_AN_ENABLED_HIBERNATION_CHECK=1
    if [ "$CAPACITY" -eq 0 ] ; then
    log "MSG" "WARNING: Battery does not report a design capacity. Auto hibernation"
    log "MSG" "does not work without a design capacity."
    ENOUGH_CHARGE=1
    elif [ "$(($REMAINING * 100 / $CAPACITY))" -ge "$AUTO_HIBERNATION_BATTERY_CHARGE_PERCENT" ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    # Fallback: hard values.
    # Determine the reporting unit.
    IN_MAH=0
    IN_MWH=0
    if ( grep -q mWh $BATT_INFO ) ; then
    IN_MWH=1
    elif ( grep -q mAh $BATT_INFO ) ; then
    IN_MAH=1
    fi
    if [ "$IN_MAH" -ne 0 ] ; then
    if [ "$MINIMUM_BATTERY_CHARGE_MAH" -ne 0 ] ; then
    FOUND_AN_ENABLED_CHECK=1
    if [ "$REMAINING" -ge "$MINIMUM_BATTERY_CHARGE_MAH" ] ; then
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_CHARGE_MAH" -ne 0 ] ; then
    FOUND_AN_ENABLED_HIBERNATION_CHECK=1
    if [ "$REMAINING" -ge "$AUTO_HIBERNATION_BATTERY_CHARGE_MAH" ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    elif [ "$IN_MWH" -ne 0 ] ; then
    if [ "$MINIMUM_BATTERY_CHARGE_MWH" -ne 0 ] ; then
    FOUND_AN_ENABLED_CHECK=1
    if [ "$REMAINING" -ge "$MINIMUM_BATTERY_CHARGE_MWH" ] ; then
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_BATTERY_CHARGE_MWH" -ne 0 ] ; then
    FOUND_AN_ENABLED_HIBERNATION_CHECK=1
    if [ "$REMAINING" -ge "$AUTO_HIBERNATION_BATTERY_CHARGE_MWH" ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    else
    log "ERR" "Failed to determine battery charge. Battery charge units are not in"
    log "ERR" "mWh or mAh."
    fi
    CAP_STATE=`sed -r 's/^capacity state:\s*(.*)\s*$/\1/;t;d' "$BATT_STATE"`
    if [ "$DISABLE_LAPTOP_MODE_ON_CRITICAL_BATTERY_LEVEL" -ne 0 ] ; then
    if [ "$CAP_STATE" = "critical" ] ; then
    # Restore the state we had before checking this battery, so that
    # this battery does not count as having enough charge.
    ENOUGH_CHARGE=$PREV_ENOUGH_CHARGE
    elif [ "$FOUND_AN_ENABLED_CHECK" -eq 0 ] ; then
    # This is the only check that is enabled. In that case a non-critical
    # battery level counts as "enough". (If we would count non-critical
    # battery levels as enough *always*, then the other settings would
    # have no effect; this is only a final fallback.)
    ENOUGH_CHARGE=1
    fi
    fi
    if [ "$AUTO_HIBERNATION_ON_CRITICAL_BATTERY_LEVEL" -ne 0 ] ; then
    if [ "$CAP_STATE" = "critical" ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=$PREV_ENOUGH_CHARGE_TO_PREVENT_HIBERNATION
    elif [ "$FOUND_AN_ENABLED_HIBERNATION_CHECK" -eq 0 ] ; then
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    fi
    fi
    else
    log "VERBOSE" "Battery is not present."
    fi
    done
    else
    ENOUGH_CHARGE=1
    ENOUGH_CHARGE_TO_PREVENT_HIBERNATION=1
    log "VERBOSE" "Not on AC and could not check battery state -- data loss sensitive features stay enabled and auto-hibernation will not work."
    fi
    if [ "$ENABLE_AUTO_HIBERNATION" -ne 0 -a "$ENOUGH_CHARGE_TO_PREVENT_HIBERNATION" -eq 0 ] ; then
    log "VERBOSE" "None of the batteries have a charge above the auto-hibernation level."
    log "VERBOSE" "Starting hibernation."
    if [ -x $HIBERNATE_COMMAND ]; then
    $HIBERNATE_COMMAND
    elif [ -f /sys/power/state ]; then
    grep -q disk /sys/power/state && echo disk > /sys/power/state
    fi
    # Don't continue -- if things are configured correctly, then we
    # will be called on resume.
    exit 0
    fi
    if [ "$ENOUGH_CHARGE" -eq 0 ] ; then
    log "VERBOSE" "None of the batteries have a charge above the minimum level."
    log "VERBOSE" "Deactivating data loss sensitive features."
    ACTIVATE_WITH_POSSIBLE_DATA_LOSS=0
    fi
    fi
    if [ "$INIT" -eq 0 ] ; then
    log "MSG" "Laptop mode "
    fi
    # WAS_ACTIVE is used later on. If there is no /var/run/laptop-mode-tools/state, then
    # we know that laptop mode wasn't active before.
    WAS_ACTIVE=0
    log "VERBOSE" "Checking if desired state is different from current state."
    if [ -f /var/run/laptop-mode-tools/state ] ; then
    read WAS_ACTIVE WAS_ON_AC WAS_ACTIVATE_WITH_POSSIBLE_DATA_LOSS WAS_STATE < /var/run/laptop-mode-tools/state
    if [ "$WAS_STATE" != "" ] ; then
    if [ "$WAS_ACTIVE" -eq "$ACTIVATE" -a "$WAS_ON_AC" -eq "$ON_AC" -a "$WAS_ACTIVATE_WITH_POSSIBLE_DATA_LOSS" -eq "$ACTIVATE_WITH_POSSIBLE_DATA_LOSS" -a "$WAS_STATE" = "$STATE" -a "$FORCE" -eq 0 ] ; then
    log "MSG" "$STATE, "
    if [ "$WAS_ACTIVE" -eq 1 ] ; then
    log "MSG" "active [unchanged]"
    if [ "$ACTIVATE_WITH_POSSIBLE_DATA_LOSS" -eq 0 ] ; then
    log "MSG" " (Data-loss sensitive features disabled.)"
    fi
    else
    log "MSG" "not active [unchanged]"
    fi
    exit 0
    fi
    fi
    else
    log "VERBOSE" "/var/run/laptop-mode-tools/state does not exist, no previous state."
    fi
    echo "$ACTIVATE $ON_AC $ACTIVATE_WITH_POSSIBLE_DATA_LOSS $STATE" > /var/run/laptop-mode-tools/state
    if [ "$ACTIVATE" -eq 1 ] ; then
    log "MSG" "$STATE, active"
    if [ "$ACTIVATE_WITH_POSSIBLE_DATA_LOSS" -eq 0 ] ; then
    log "MSG" " (Data-loss sensitive features disabled.)"
    fi
    else
    log "MSG" "$STATE, not active"
    fi
    # Finally, call laptop-mode-tools modules. The modules can use the settings
    # from the config files, but they may NOT assume the settings actually exist,
    # as no defaults have been given for them.
    # Note that the /usr/local/lib path is deprecated.
    export FORCE STATE ON_AC ACTIVATE ACTIVATE_WITH_POSSIBLE_DATA_LOSS KLEVEL KMINOR WAS_ACTIVE LM_VERBOSE DEVICES
    for SCRIPT in /usr/share/laptop-mode-tools/modules/* /usr/local/lib/laptop-mode-tools/modules/* /usr/local/share/laptop-mode-tools/modules/* /etc/laptop-mode/modules/* ; do
    if [ -z "$MODULES" ] ; then
    # If a module list has not been provided, execute all modules
    EXECUTE_SCRIPT=1
    else
    # If a module list has been provided, execute only the listed
    # modules.
    EXECUTE_SCRIPT=0
    for MODULE in $MODULES; do
    # Attempt to remove the module name from the end of the
    # full script path. If the module name matches the
    # script, the name will be removed from the end of the
    # full file path, leaving the path to the script. If
    # there was not a match made, the module name would not
    # be removed from the path, and $PATH_TO_SCRIPT would
    # be the same as $SCRIPT.
    PATH_TO_SCRIPT=${SCRIPT%%$MODULE}
    # Execute the script if a match was found (module name
    # was removed from the script path, making it shorter.
    if [ $PATH_TO_SCRIPT != $SCRIPT ] ; then
    EXECUTE_SCRIPT=1
    fi
    done
    fi
    if [ -x "$SCRIPT" -a $EXECUTE_SCRIPT -eq 1 ] ; then
    log "VERBOSE" "Invoking module $SCRIPT."
    SCRIPT_DEBUG=$SCRIPT; # We do this because in start-stop-programs module a $SCRIPT variable is used. That
    # changes the whole meaning when passed to disableDebug ()
    enableDebug $SCRIPT_DEBUG;
    . $SCRIPT
    disableDebug $SCRIPT_DEBUG;
    else
    log "VERBOSE" "Module $SCRIPT is not executable or is to be skipped."
    fi
    done
    exit 0
    # This fi closes the if for "readconfig". If I would have indented this one
    # I would have indented the whole file. :)
    fi
    lmt_load_config
    lock_retry ()
    ( $FLOCK -n -x -w 1 8 || exit 0;
    i=10;
    while [ $i -ge 1 ]
    do
    log "ERR" "Couldn't acquire lock. Retrying.... PID is $$\n"
    $FLOCK -x -w 1 9 && lmt_main_function "$@" && break;
    i=$(( $i - 1 ))
    done
    ) 8>$LMT_REQ_LOCK
    # Check and acquire locks and then exec.
    ( $FLOCK -n -x -w 1 8; ) 8>$LMT_REQ_LOCK
    ($FLOCK -n -x -w 1 9 && lmt_main_function "$@";) || lock_retry "$@"
    ) 9<>$LMT_INVOC_LOCK
    # We do a special run of battery polling daemon here so that it does not get
    # plagued by the lock. We need the polling daemon to be independent of any locks
    if [ x$ENABLE_BATTERY_LEVEL_POLLING = x1 ] && [ x$BLACKLIST_IN_FLOCK = x1 ]; then
    log "VERBOSE" "Battery level polling is enabled."
    if [ x$ON_AC = x1 ] ; then
    log "VERBOSE" "On AC, stopping the polling daemon."
    # In AC mode we disable the polling daemon.
    killall -q lm-polling-daemon
    else
    if ! pidof -x lm-polling-daemon ; then
    log "VERBOSE" "On battery and there was no polling daemon yet, starting the polling daemon."
    # If there is no polling daemon, we start one.
    /usr/share/laptop-mode-tools/module-helpers/lm-polling-daemon < /dev/null > /dev/null 2> /dev/null &
    fi
    fi
    else
    log "VERBOSE" "Battery level polling is disabled."
    fi
    exit 0;
    and here is the lines which archwiki mentions
    case "$KLEVEL" in
    "2.4" ) ;;
    "2.6" ) ;;
    log "ERR" "Unhandled kernel version: $KLEVEL ('uname -r' = '$(uname -r)')" >&2
    exit 1
    esac

    I had the problem but edited the line in /usr/sbin/laptop_mode and it worked. But thoes lines are not there anymore. I guess they changed it at the recent update of laptop-mode-tools.
    Regarding your heat problem; is there any other thing you use to cut down power usage (from AUR  maybe)? I use acpi_call from AUR had to edit lines there aswell, but it should be updated by now.

  • Problem with Credit Limit

    Hi all
    There seems to be a problem with the credit limit.  It was brought to my attention before and I believe someone has a query to rectify the problem.  Could someone please send me this query as one of my clients are going to heavliy rely on the credit limit function. 
    The problem is if I make the credit limit for a customer £500.  Then I post a Sales Order for £300 then another sale order for £300 it will allow this even though the total is over the £500 limit.
    Thank you in advance.
    Gail

    Gail,
    The following Query looks at the Order Total of the Order you are entering, the total balance of all previous orders and the Account Balance and compares with the Credit limit.
    SELECT DISTINCT 'TRUE' FROM [DBO\].[ORDR\] T0 INNER JOIN [DBO\].[OCRD\] T1 ON T0.CARDCODE = T1.CARDCODE WHERE T0.CARDCODE = $\[$4.1] AND T1.CreditLine < (T1.BalanceT1.OrdersBal$\[ORDR.DocTotal])
    You will need to save this query and creare an Approval Procedure
    The process of creating Approval Procedure is explained in this thread
    Credit Limit Approval
    Suda

Maybe you are looking for

  • Error iTunes??

    I would like for me, excuse my bad English (google translation), but I hope that you sent me still can help! I have an iPod nano 8GB bought, now I wanted to iTunes on my Windows Vista Home install. Unfortunately I always get the following error messa

  • How do I get my movie from iTunes onto my iPod?

    The file is an .mp4 and I have my iPod nano (3rd gen) plugged in and I have the 'manually manage music and videos' option selected on the summary tag. The problem is when I try to drag the .mp4 movie file from the Library to the Devices >> Movies, it

  • Airport Base Station Set Up

    Hi, I've been trying to get an Airport Base Station set up for a few weeks. There is currently a problem getting wireless connectivity. The computer recognizes the base station, but does not see the server. I'm not sure how to get a wireless connecti

  • Issue with Idoc when creating invoice taking wrong payment term

    Hi All, My Requirement is invoices created through B2B interface should hold the payment term of purchasing party instead of invoicing party 400021 is Invoicing party having payment term 2000 i.e. 20 days 414478 is the Purchasing party having the pay

  • CS4 Licensing Issue

    Can no longer use PS due to licensing issue. Told to see my IT people! I'm a single user and I AM IT! What to do? Thanks.